Solana トランザクション構築
Solanaブロックチェーン上で、命令の作成、アカウント特定、計算予算設定、優先手数料、バージョン管理されたトランザクションなど、トランザクション構築に必要な作業を効率的に実行するSkill。
📜 元の英語説明(参考)
Solana transaction construction including instruction building, account resolution, compute budget, priority fees, and versioned transactions
🇯🇵 日本人クリエイター向け解説
Solanaブロックチェーン上で、命令の作成、アカウント特定、計算予算設定、優先手数料、バージョン管理されたトランザクションなど、トランザクション構築に必要な作業を効率的に実行するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o solana-tx-building.zip https://jpskill.com/download/10438.zip && unzip -o solana-tx-building.zip && rm solana-tx-building.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/10438.zip -OutFile "$d\solana-tx-building.zip"; Expand-Archive "$d\solana-tx-building.zip" -DestinationPath $d -Force; ri "$d\solana-tx-building.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
solana-tx-building.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
solana-tx-buildingフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
Solanaトランザクションの構築
このスキルでは、Solanaトランザクションをプログラムで構築、シミュレート、および検査する方法について説明します。生の命令エンコードから、バージョン管理されたトランザクション形式、計算予算管理、優先手数料、およびアドレスルックアップテーブルまで、Solanaトランザクションの完全な構造について説明します。
安全性: このスキルは、トランザクションの構築と分析のみを対象としています。このスキルのスクリプトは、実際のトランザクションに署名したり、送信したりすることは決してありません。送信する前に必ずシミュレートしてください。自動署名は絶対に行わないでください。
トランザクションの構造
Solanaトランザクションは、以下で構成されます。
- 署名: 1つ以上のEd25519署名(それぞれ64バイト)
- メッセージ: シリアライズ可能なペイロード。以下を含みます。
- ヘッダー: 必要な署名者、読み取り専用署名者、読み取り専用非署名者の数
- アカウントキー: 命令によって参照されるすべての
pubkeyの配列 - 最新のブロックハッシュ: リプレイ保護のための32バイトのハッシュ(約60〜90秒で期限切れ)
- 命令: プログラム呼び出しの配列
トランザクションサイズ制限
ハードリミットは、シリアライズされたトランザクション全体で1232バイトです。これにより、含めることができる命令とアカウントの数が制限されます。制限内に収まるための戦略:
- アドレスルックアップテーブル(ALT)を備えたバージョン管理されたトランザクションを使用する
- 命令ごとのアカウント数を最小限に抑える
- 関連する操作をサポートされている単一の命令に結合する
- 複雑な操作を複数のトランザクションに分割する
命令形式
各命令には、3つのフィールドが含まれています。
Instruction {
program_id_index: u8, // アカウントキー配列へのインデックス
accounts: [u8], // アカウントキー配列へのインデックス
data: [u8], // プログラムによって解釈される不透明なバイト配列
}
アカウントメタ
命令で参照されるすべてのアカウントには、メタデータがあります。
AccountMeta {
pubkey: Pubkey, // 32バイトの公開鍵
is_signer: bool, // トランザクションに署名する必要がある
is_writable: bool, // この命令によって書き込まれる
}
4つの組み合わせにより、アカウントの役割が決まります。
| is_signer | is_writable | 役割 |
|---|---|---|
| true | true | 手数料支払者、転送を実行するトークン所有者 |
| true | false | マルチシグ共同署名者、読み取り専用権限 |
| false | true | 宛先アカウント、書き込まれるPDA |
| false | false | プログラムID、sysvar、クロック |
レガシー vs バージョン管理されたトランザクション
レガシートランザクション
元の形式。すべてのアカウントは、アカウントキー配列にリストされている必要があります。1232バイトの制限では、命令データのサイズに応じて、約20〜35個のアカウントを収めることができます。
バージョン管理されたトランザクション(v0)
アドレスルックアップテーブル(ALT)をサポートするために導入されました。v0トランザクションには、以下が含まれます。
- バージョンプレフィックスバイト(v0の場合は
0x80) - レガシーと同じメッセージ構造
- 追加の
address_table_lookups配列
ALTを使用すると、完全な32バイトの pubkey を含めるのではなく、オンチェーンテーブルへのコンパクトなインデックスでアカウントを参照できます。これにより、トランザクションが参照できるアカウントの数が劇的に増加します。
AddressTableLookup {
account_key: Pubkey, // ALTアカウントアドレス
writable_indexes: [u8], // 書き込み可能なアカウントのインデックス
readonly_indexes: [u8], // 読み取り専用アカウントのインデックス
}
v0を使用するタイミング: 20を超えるアカウントを参照するトランザクション、マルチホップルートを使用する Jupiter スワップ、複雑な DeFi インタラクション。
計算予算
すべてのトランザクションには、消費できる計算ユニット(CU)の数と支払う優先手数料を決定する計算予算があります。
計算予算命令
計算予算プログラム(ComputeBudget111111111111111111111111111111)からの2つの主要な命令:
1. 計算ユニット制限の設定
Instruction data: [0x02, <units as u32 LE>]
このトランザクションが消費できる最大CUを設定します。デフォルトは、命令あたり200,000(トランザクションあたり最大1,400,000)です。これを必要以上に低く設定すると、トランザクションは失敗します。高く設定しても予算が無駄になるだけで、コストはかかりません(要求された分だけ支払い、消費された分は支払いません)。
2. 計算ユニット価格の設定
Instruction data: [0x03, <micro_lamports as u64 LE>]
CUあたりの価格をマイクロランプで設定します。これが優先手数料のメカニズムです。合計優先手数料は次のとおりです。
priority_fee = compute_unit_limit * compute_unit_price / 1_000_000
優先手数料の見積もり
適切な優先手数料を見積もるには:
- トランザクションが触れるアカウントで
getRecentPrioritizationFeesRPCメソッドを呼び出します - 最近のスロットの中央値または75パーセンタイルの手数料を確認します
- 輻輳中は、手数料が急上昇します。動的に監視および調整します
import httpx
def get_priority_fees(rpc_url: str, accounts: list[str]) -> list[dict]:
"""Fetch recent prioritization fees for given accounts."""
resp = httpx.post(rpc_url, json={
"jsonrpc": "2.0",
"id": 1,
"method": "getRecentPrioritizationFees",
"params": [accounts]
})
return resp.json()["result"]
一般的なトランザクションパターン
1. SOL転送
最も単純なトランザクション:System Program転送。
# System Program転送命令データレイアウト:
# [2, 0, 0, 0] (u32 LE = 命令インデックス2 = Transfer)
# + amount as u64 LE (lamports)
import struct
def build_sol_transfer_data(lamports: int) -> bytes:
"""Build instruction data for a SOL transfer."""
return struct.pack("<I", 2) + struct.pack("<Q", lamports)
必要なアカウント:
- 送信者(署名者、書き込み可能)
- 受信者(書き込み可能)
2. SPLトークン転送
SPLトークンを転送するには、Token Programが必要です。
# Token Program転送命令:
# [3] (命令インデックス3 = Transfer)
# + amount as u64 LE
def build_token_transfer_data(amount: int) -> bytes:
"""Build instruction data for an SPL token transfer."""
return bytes([3]) + struct.pack("<Q", amount)
必要なアカウント:
- ソーストークンアカウント(書き込み可能)
- 宛先トークンアカウント(書き込み可能)
- 所有者/デリゲート(署名者)
3. Create As
(原文がここで切り詰められています)
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
Solana Transaction Building
This skill covers how to construct, simulate, and inspect Solana transactions programmatically. It addresses the full anatomy of a Solana transaction — from raw instruction encoding to versioned transaction formats, compute budget management, priority fees, and address lookup tables.
Safety: This skill is for transaction construction and analysis only. Scripts in this skill NEVER sign or submit real transactions. Always simulate before sending. Never auto-sign.
Transaction Anatomy
A Solana transaction consists of:
- Signatures: One or more Ed25519 signatures (64 bytes each)
- Message: The serializable payload containing:
- Header: Counts of required signers, read-only signers, read-only non-signers
- Account keys: Array of all pubkeys referenced by instructions
- Recent blockhash: 32-byte hash for replay protection (expires ~60-90 seconds)
- Instructions: Array of program calls
Transaction Size Limit
The hard limit is 1232 bytes for the entire serialized transaction. This constrains how many instructions and accounts you can include. Strategies to stay within the limit:
- Use versioned transactions with Address Lookup Tables (ALTs)
- Minimize the number of accounts per instruction
- Combine related operations into single instructions where supported
- Split complex operations across multiple transactions
Instruction Format
Each instruction contains three fields:
Instruction {
program_id_index: u8, // Index into the account keys array
accounts: [u8], // Indices into account keys array
data: [u8], // Opaque byte array interpreted by the program
}
Account Meta
Every account referenced in an instruction has metadata:
AccountMeta {
pubkey: Pubkey, // 32-byte public key
is_signer: bool, // Must sign the transaction
is_writable: bool, // Will be written to by this instruction
}
The four combinations determine the account's role:
| is_signer | is_writable | Role |
|---|---|---|
| true | true | Fee payer, token owner performing transfer |
| true | false | Multisig co-signer, read-only authority |
| false | true | Destination account, PDA being written |
| false | false | Program ID, sysvar, clock |
Legacy vs Versioned Transactions
Legacy Transactions
The original format. All accounts must be listed in the account keys array. With the 1232-byte limit, you can fit roughly 20-35 accounts depending on instruction data size.
Versioned Transactions (v0)
Introduced to support Address Lookup Tables (ALTs). A v0 transaction includes:
- A version prefix byte (
0x80for v0) - The same message structure as legacy
- An additional
address_table_lookupsarray
ALTs let you reference accounts by a compact index into an on-chain table rather than including the full 32-byte pubkey. This dramatically increases the number of accounts a transaction can reference.
AddressTableLookup {
account_key: Pubkey, // The ALT account address
writable_indexes: [u8], // Indices for writable accounts
readonly_indexes: [u8], // Indices for read-only accounts
}
When to use v0: Any transaction referencing more than ~20 accounts, Jupiter swaps with multi-hop routes, complex DeFi interactions.
Compute Budget
Every transaction has a compute budget that determines how many compute units (CUs) it can consume and what priority fee to pay.
Compute Budget Instructions
Two key instructions from the Compute Budget Program (ComputeBudget111111111111111111111111111111):
1. Set Compute Unit Limit
Instruction data: [0x02, <units as u32 LE>]
Sets the maximum CUs this transaction can consume. Default is 200,000 per instruction (max 1,400,000 per transaction). Setting this lower than needed causes the transaction to fail. Setting it higher wastes budget but does not cost more (you only pay for requested, not consumed).
2. Set Compute Unit Price
Instruction data: [0x03, <micro_lamports as u64 LE>]
Sets the price per CU in micro-lamports. This is the priority fee mechanism. The total priority fee is:
priority_fee = compute_unit_limit * compute_unit_price / 1_000_000
Priority Fee Estimation
To estimate an appropriate priority fee:
- Call
getRecentPrioritizationFeesRPC method with the accounts your transaction touches - Look at the median or 75th percentile fee from recent slots
- During congestion, fees spike — monitor and adjust dynamically
import httpx
def get_priority_fees(rpc_url: str, accounts: list[str]) -> list[dict]:
"""Fetch recent prioritization fees for given accounts."""
resp = httpx.post(rpc_url, json={
"jsonrpc": "2.0",
"id": 1,
"method": "getRecentPrioritizationFees",
"params": [accounts]
})
return resp.json()["result"]
Common Transaction Patterns
1. SOL Transfer
The simplest transaction: a System Program transfer.
# System Program transfer instruction data layout:
# [2, 0, 0, 0] (u32 LE = instruction index 2 = Transfer)
# + amount as u64 LE (lamports)
import struct
def build_sol_transfer_data(lamports: int) -> bytes:
"""Build instruction data for a SOL transfer."""
return struct.pack("<I", 2) + struct.pack("<Q", lamports)
Accounts required:
- Sender (signer, writable)
- Recipient (writable)
2. SPL Token Transfer
Transferring SPL tokens requires the Token Program.
# Token Program transfer instruction:
# [3] (instruction index 3 = Transfer)
# + amount as u64 LE
def build_token_transfer_data(amount: int) -> bytes:
"""Build instruction data for an SPL token transfer."""
return bytes([3]) + struct.pack("<Q", amount)
Accounts required:
- Source token account (writable)
- Destination token account (writable)
- Owner/delegate (signer)
3. Create Associated Token Account (ATA)
Before transferring tokens, the recipient must have an Associated Token Account.
# ATA Program: instruction index 0 = Create
# No instruction data needed (empty bytes)
ATA_PROGRAM_ID = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
Accounts required (in order):
- Payer (signer, writable) — pays rent
- Associated token account (writable) — the ATA to create
- Wallet address — owner of the new ATA
- Token mint
- System Program
- Token Program
4. Jupiter Swap
Jupiter provides a /swap-instructions endpoint that returns pre-built instructions. See the jupiter-api skill for full details.
General flow:
- Get a quote from
/quote - Get swap instructions from
/swap-instructions - Build transaction with setup instructions + swap instruction + cleanup instructions
- Add compute budget instructions
- Simulate, then sign and send
Simulation
Always simulate before sending. Use the simulateTransaction RPC method:
def simulate_transaction(rpc_url: str, tx_base64: str) -> dict:
"""Simulate a transaction without submitting it.
Args:
rpc_url: Solana RPC endpoint URL.
tx_base64: Base64-encoded serialized transaction.
Returns:
Simulation result with logs and compute units consumed.
"""
resp = httpx.post(rpc_url, json={
"jsonrpc": "2.0",
"id": 1,
"method": "simulateTransaction",
"params": [
tx_base64,
{"encoding": "base64", "replaceRecentBlockhash": True}
]
})
result = resp.json()["result"]
if result["value"]["err"]:
print(f"Simulation failed: {result['value']['err']}")
for log in result["value"].get("logs", []):
print(f" {log}")
else:
cu = result["value"].get("unitsConsumed", 0)
print(f"Simulation OK — {cu} compute units consumed")
return result
The replaceRecentBlockhash: True flag lets you simulate even if your blockhash has expired, which is useful for testing transaction construction without timing pressure.
Error Handling
Common transaction errors and their causes:
| Error | Cause | Fix |
|---|---|---|
BlockhashNotFound |
Blockhash expired (~60-90s) | Fetch new blockhash and rebuild |
InsufficientFunds |
Not enough SOL for fees + transfer | Check balance before building |
AccountNotFound |
Token account doesn't exist | Create ATA first |
ProgramFailedToComplete |
Exceeded compute budget | Increase compute unit limit |
TransactionTooLarge |
Over 1232 bytes | Use ALTs or split into multiple txs |
InvalidAccountData |
Wrong account passed to instruction | Verify account derivation |
SignatureVerificationFailed |
Missing or wrong signer | Check all is_signer accounts signed |
Retry Strategy
import time
def send_with_retry(
rpc_url: str,
build_fn,
max_retries: int = 3,
base_delay: float = 0.5
) -> dict:
"""Build and send a transaction with blockhash refresh on expiry.
Args:
rpc_url: Solana RPC endpoint.
build_fn: Callable that takes a blockhash and returns a signed tx.
max_retries: Maximum retry attempts.
base_delay: Base delay between retries in seconds.
Returns:
Send result from RPC.
"""
for attempt in range(max_retries):
blockhash = get_latest_blockhash(rpc_url)
tx = build_fn(blockhash)
result = send_transaction(rpc_url, tx)
if "error" not in result:
return result
err = result["error"]
if "BlockhashNotFound" in str(err):
time.sleep(base_delay * (attempt + 1))
continue
raise RuntimeError(f"Transaction failed: {err}")
raise RuntimeError("Max retries exceeded")
Transaction Decoding
To decode an existing transaction from the chain:
def decode_transaction(rpc_url: str, signature: str) -> dict:
"""Fetch and return a parsed transaction.
Args:
rpc_url: Solana RPC endpoint.
signature: Transaction signature (base58).
Returns:
Parsed transaction data.
"""
resp = httpx.post(rpc_url, json={
"jsonrpc": "2.0",
"id": 1,
"method": "getTransaction",
"params": [
signature,
{"encoding": "jsonParsed", "maxSupportedTransactionVersion": 0}
]
})
return resp.json()["result"]
Integration with Other Skills
solana-rpc: Provides the RPC connection layer for submitting and querying transactionsjupiter-api: Supplies swap instructions that this skill assembles into transactionsdex-execution: Orchestrates the full execution flow using transactions built by this skillmev-analysis: Evaluates MEV risk of constructed transactions before submissionhelius-api: Enhanced transaction parsing and webhook-based confirmation tracking
Safety Checklist
Before submitting any transaction to mainnet:
- Simulate first — always call
simulateTransactionbeforesendTransaction - Verify accounts — confirm all account addresses are correct (especially for token transfers)
- Check balances — ensure sufficient SOL for fees and any transfers
- Review compute budget — set appropriate CU limit based on simulation
- Confirm priority fee — check current network fees, do not overpay
- Never auto-sign — require explicit user confirmation before signing
- Use devnet for testing — build and test on devnet before mainnet
- Log everything — record transaction signatures, simulation results, and errors
Files
References
references/transaction_anatomy.md— Message format, versioned transactions, compute budget, blockhash managementreferences/common_instructions.md— Instruction layouts for System, Token, ATA, Compute Budget, Memo, and Jupiter programs
Scripts
scripts/build_transfer.py— Build and simulate a SOL transfer transaction (demo mode, never signs)scripts/decode_transaction.py— Fetch and decode on-chain transactions with program identification