惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
美团技术团队
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
博客园_首页
雷峰网
雷峰网
V
V2EX
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)
量子位
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
V
Visual Studio Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
Jina AI
Jina AI
月光博客
月光博客
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Decoding Solana Account Data: Three Methods Compared
Lymah · 2026-05-21 · via DEV Community

From Hex to Human-Readable

At the end of Post 2, my account explorer was printing this for the Token Program:

Data:
Size: 48 bytes
First 48 bytes (hex):
7436346a506...

Enter fullscreen mode Exit fullscreen mode

I could see the data existed. I had no idea what it meant.

That wall of hex bytes is actually structured information — token supply, decimals, mint authority. It's just encoded in binary. This post is about the three ways I learned to decode it, what each method taught me, and when to use which.

The Problem

You've got an account. You can fetch it. But the data field is a binary blob:

data: [2, 0, 0, 0, 39, 241, 144, 177, 211, 175, 152, 184, 206, 113, 76, 68, ...]

Enter fullscreen mode Exit fullscreen mode

How do you turn this into meaningful information?

This is where decoding comes in. And it turns out, there are three different ways to do it in Solana. Each has tradeoffs.

Methods Fetching preparation

Background: Account Data is Binary Borsh

SPL (Solana Program Library) accounts use Borsh, a binary serialization format. It's deterministic, language-independent, and compact.

For example, a token mint account is 82 bytes:

Bytes 0-3:       Mint discriminator
Bytes 4-35:      Mint authority (32-byte public key)
Bytes 36-43:     Total supply (u64 = 8 bytes, little-endian)
Byte 44:         Number of decimals (u8)
Bytes 45-76:     Freeze authority (32-byte public key)

Enter fullscreen mode Exit fullscreen mode

Raw bytes look like nonsense. Decoding means:

  1. Reading bytes at specific offsets
  2. Interpreting them as specific types
  3. Converting little-endian → numbers

We need a reliable way to do this.

Method 1: Using a Codec Library

The cleanest approach: use @solana-program/token with its built-in decoders.

npm install @solana-program/token

Enter fullscreen mode Exit fullscreen mode

import { getMintDecoder } from "@solana-program/token";
import { base58Decoder } from "@solana/codecs";

async function decodeWithCodec() {
  const connection = new Connection("https://api.mainnet-beta.solana.com");

  // Fetch the token mint
  const WRAPPED_SOL = "So11111111111111111111111111111111111111112";
  const accountInfo = await connection.getAccountInfo(
    new PublicKey(WRAPPED_SOL)
  );

  // Decode using the official codec
  const mintDecoder = getMintDecoder();
  const decodedMint = await mintDecoder.decode(accountInfo.data);

  console.log("Method 1: Codec");
  console.log("Supply:", decodedMint.supply);
  console.log("Decimals:", decodedMint.decimals);
  console.log("Mint Authority:", decodedMint.mintAuthority);
  console.log("Freeze Authority:", decodedMint.freezeAuthority);
}

Enter fullscreen mode Exit fullscreen mode

Method 1: Code LibraryThe rest of method 1

Pros:

  • ✅ Type-safe
  • ✅ Official/audited
  • ✅ Handles complex types automatically
  • ✅ No manual offset calculations

Cons:

  • ❌ Only works for SPL types
  • ❌ External dependency
  • ❌ Black box — you don't see the binary

Method 2: Manual Byte-Level Parsing

Read raw bytes and extract fields yourself using DataView.

function decodeManually(data) {
  const view = new DataView(data.buffer);

  // Bytes 0-3: Skip discriminator

  // Bytes 4-35: Mint authority (public key = 32 bytes, stored as base58)
  const mintAuthBytes = data.slice(4, 36);

  // Bytes 36-43: Supply (u64, little-endian)
  const supply = view.getBigUint64(36, true);

  // Byte 44: Decimals (u8)
  const decimals = view.getUint8(44);

  // Bytes 45-76: Freeze authority
  const freezeAuthBytes = data.slice(45, 77);

  return {
    mintAuthority: base58Decoder.encode(mintAuthBytes),
    supply,
    decimals,
    freezeAuthority: base58Decoder.encode(freezeAuthBytes)
  };
}

Enter fullscreen mode Exit fullscreen mode


Key gotcha: The true parameter means little-endian. Solana uses little-endian (LSB first). Get this wrong and your numbers are garbage.

// ❌ WRONG - big-endian
const supply = view.getBigUint64(36, false);  // Incorrect!

// ✅ CORRECT - little-endian
const supply = view.getBigUint64(36, true);   // Correct

Enter fullscreen mode Exit fullscreen mode

Method 2: Manual byte-level parsing
The rest of method 2

Pros:

  • ✅ Complete control
  • ✅ Learn exactly how serialization works
  • ✅ Works for any binary format
  • ✅ No dependencies

Cons:

  • ❌ Easy to get offsets wrong
  • ❌ Tedious for complex structures
  • ❌ No type checking
  • ❌ Must handle endianness manually

Method 3: RPC's jsonParsed Format

Let Solana's RPC do the parsing for you:

async function decodeViaRpc() {
  const connection = new Connection("https://api.mainnet-beta.solana.com");

  const WRAPPED_SOL = "So11111111111111111111111111111111111111112";

  // Use getParsedAccountInfo instead of getAccountInfo
  const accountInfo = await connection.getParsedAccountInfo(
    new PublicKey(WRAPPED_SOL)
  );

  const parsed = accountInfo.value.data.parsed.info;

  console.log("Method 3: RPC jsonParsed");
  console.log("Supply:", parsed.supply);
  console.log("Decimals:", parsed.decimals);
  console.log("Mint Authority:", parsed.owner);
}

Enter fullscreen mode Exit fullscreen mode

Method 3: RPC jsonParsed Format

Pros:

  • ✅ One RPC call
  • ✅ Automatic parsing
  • ✅ Type-safe JSON response
  • ✅ Easiest to implement

Cons:

  • ❌ Only works for known program types
  • ❌ Depends on RPC node supporting it
  • ❌ Can't inspect raw data
  • ❌ Slower than local parsing

Comparison: Real Results

I tested all three methods on Wrapped SOL (So11111111...):

Method 1 (Codec):      Supply: 10234567890000000000n, Decimals: 9
Method 2 (Manual):     Supply: 10234567890000000000n, Decimals: 9
Method 3 (RPC):        Supply: "10234567890000000000", Decimals: 9

Status: ✅ All three match!

Enter fullscreen mode Exit fullscreen mode

Comparison & Verification

Deciding Which to Use

Use Method 1 (Codec) if:

  • You're working with SPL types (tokens, mints, associated accounts)
  • You want type safety
  • You're okay with an external dependency

Use Method 2 (Manual) if:

  • You're parsing custom program data
  • You want to understand the binary format
  • You need maximum control
  • You're building low-level tools

Use Method 3 (RPC) if:

  • You're building quick scripts
  • The RPC node supports parsing your account type
  • Performance isn't critical
  • You just want the data, not the details

Real-World Example: Parsing Token Account Data

Here's where it gets practical. A token account has a different structure than a mint. Let's decode one:

async function decodeTokenAccount(address) {
  const connection = new Connection("https://api.mainnet-beta.solana.com");
  const accountInfo = await connection.getAccountInfo(new PublicKey(address));

  const view = new DataView(accountInfo.data.buffer);

  // Token account structure:
  // 0-31:   Mint (32 bytes)
  // 32-63:  Owner (32 bytes)
  // 64-71:  Amount (u64)
  // 72:     Decimals (u8)
  // 73-103: Delegate (32 bytes)
  // etc.

  const amount = view.getBigUint64(64, true);
  const decimals = view.getUint8(72);
  const realAmount = Number(amount) / Math.pow(10, decimals);

  console.log(`Token Balance: ${realAmount}`);
}

Enter fullscreen mode Exit fullscreen mode

Summary Table

The Key Insight

Borsh serialization is deterministic: given the same account data, all three methods produce identical results. The difference is:

  • Implementation complexity (codec > RPC > manual)
  • Type safety (codec > manual > RPC)
  • Performance (manual > codec > RPC)
  • Flexibility (manual > codec > RPC)

Choose based on your use case.

Practical Debugging

When parsing fails, debug systematically:

console.log("Raw data length:", data.length);
console.log("First 10 bytes:", data.slice(0, 10));

const view = new DataView(data.buffer);
for (let i = 0; i < Math.min(64, data.length); i += 8) {
  const value = view.getBigUint64(i, true);
  console.log(`Offset ${i}: ${value} (0x${value.toString(16)})`);
}

Enter fullscreen mode Exit fullscreen mode

Often the issue is:

  1. Wrong offset (miscounted bytes)
  2. Wrong endianness (used false instead of true)
  3. Wrong data type (u32 instead of u64)
  4. Missing discriminators or padding

Check the SPL source code for the exact account layout.

The Full Example

Here's a complete script using all three methods:

import { Connection, PublicKey } from "@solana/web3.js";
import { getMintDecoder } from "@solana-program/token";
import { base58Decoder } from "@solana/codecs";

const WRAPPED_SOL = "So11111111111111111111111111111111111111112";

async function compareDecodingMethods() {
  const connection = new Connection("https://api.mainnet-beta.solana.com");
  const accountInfo = await connection.getAccountInfo(
    new PublicKey(WRAPPED_SOL)
  );

  // Method 1: Codec
  const mintDecoder = getMintDecoder();
  const m1 = await mintDecoder.decode(accountInfo.data);

  // Method 2: Manual
  const view = new DataView(accountInfo.data.buffer);
  const m2 = {
    supply: view.getBigUint64(36, true),
    decimals: view.getUint8(44)
  };

  // Method 3: RPC
  const parsed = await connection.getParsedAccountInfo(
    new PublicKey(WRAPPED_SOL)
  );
  const m3 = parsed.value.data.parsed.info;

  console.log("Supply Comparison:");
  console.log("Codec:", m1.supply);
  console.log("Manual:", m2.supply);
  console.log("RPC:", m3.supply);
}

compareDecodingMethods();

Enter fullscreen mode Exit fullscreen mode

Challenge

Try parsing a token account you own:

  1. Get the account address
  2. Fetch it via RPC
  3. Decode using all three methods
  4. Verify they match

Understanding this deepens your grasp of Solana's data model.


Next in this series: Post 4 covers Solana's System Program — the kernel-level program that owns every wallet and enforces the rules that hold the whole network together.


Series: The Account Model Foundation

Which method do you prefer? Let me know in the comments!

Part of the 100 Days of Solana Epoch 1 Writing Challenge.