2

When I have IDL and instruction data, how can I decode that into struct?

For example, I have IDL file and its corresponding instruction data encoded with bs58 like 368Yh7EEPvKQfQdCFA3GKqgk.

Given these, can I decode it into struct using anchor?

ChatGPT gives me code like this:

const { Buffer } = require('buffer');
const bs58 = require('bs58');

const instructionDataBase58 = '368Yh7EEPvKQfQdCFA3GKqgk';
const instructionDataBuffer = bs58.decode(instructionDataBase58);
...
const decodedInstruction = program.decodeInstruction(instructionDataBuffer);
console.log(decodedInstruction);

But I can't find method decodeInstruction. Anyone can help me?

2 Answers 2

4

When you build and anchor program it creates an IDL file and also typescript types. You can find them in the target folder under types.

Then you can use that to decode the data like this:

import IDL from "../idl/lumberjack.json";
import { Lumberjack } from "@/idl/lumberjack";

      Program program = new Program(IDL as Lumberjack, provider);
      
      const newGameData = program.coder.accounts.decode(
        "gameData",
        account.data
      );

Where the account name is the struct name in the program but in camelCase.

Or you can directly fetch and decode an account:

program.account.gameData
      .fetch(pda)
      .then((data) => {
        setGameData(data);
        setTotalWoodAvailable(data.totalWoodCollected.toNumber());
      })
      .catch((error) => {
        window.alert("No game data found, please init!");
      });

Here is a complete example: https://github.com/solana-developers/solana-game-preset/blob/main/app/contexts/GameStateProvider.tsx#L97

To parse only the instruction data you can do it like the Solana explorer does:

                coder = new BorshInstructionCoder(anchorProgram.idl);
                decodedIxData = coder.decode(ix.data);

Here is the code: https://github.com/solana-labs/explorer/blob/c10c8ff890ceeadaa090398a53bd37afab948fda/app/components/instruction/AnchorDetailsCard.tsx#L74

3
  • I want to decode instruction data, not account.
    – toygr
    Commented Nov 7 at 10:19
  • Oh sorry, i updated my answer.
    – Jonas H.
    Commented Nov 7 at 10:43
  • That's what I looking for. Thanks.
    – toygr
    Commented Nov 7 at 21:18
0

I'd recommend generating the types and decoders using solita

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.