4

I've been looking around the posts and I don't really see anything that can help me so I'm trying here. I'm looking for a way to fetch the IDL of a program by the ID of this program (provided that it has obviously init and deployed). Do you know if there is a way? Ideally via a classic RPC request without needing to build a Wallet + Provider to fetch it.

If this is not possible, why?

Thank you!

2 Answers 2

6

A published Anchor IDL is stored in a separate account, based on a PDA.

So reading an Anchor IDL is essentially just a getAccountInfo RPC call. You just need to first find the PDA for it (locally). No wallets are involved.

Here is a TypeScript example:

import { decodeIdlAccount } from '@project-serum/anchor/dist/cjs/idl';
import { utf8 } from '@project-serum/anchor/dist/cjs/utils/bytes';
import { inflate } from "pako";
import { PublicKey } from "@solana/web3.js";

const base = (await PublicKey.findProgramAddress([], programId))[0];
const idlAddress = await PublicKey.createWithSeed(base, "anchor:idl", programId);
const idlAccountInfo = await connection.getAccountInfo(idlAddress);
const idlAccount = decodeIdlAccount(idlAccountInfo.data.slice(8)); // chop off discriminator
const inflatedIdl = inflate(idlAccount.data);
const idlJson = JSON.parse(utf8.decode(inflatedIdl));

I am pulling a couple of functions from @project-serum/anchor but if you don't want any dependency on the Anchor package at all, please just check the implementation of those functions and include them in your code.

Here is also how Anchor itself does it for reference.

2
  • Thanks for your answer ! From this address, how can I read the JSON with all instructions inside the IDL ? Because idlBuffer return only a buffer, not a JSON readable IDL
    – Swifty
    Commented Sep 2, 2022 at 21:42
  • 1
    That's been outlined in the reference I provided. I updated my answer to include that too.
    – sohrab
    Commented Sep 4, 2022 at 11:19
0

You need a provider since it needs to know which cluster you are connecting to.

Alternatively, you can try this. for ex, if you want to the IDL for Marinade Finance (program ID is MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD)

via Solscan

https://solscan.io/account/MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD#anchorProgramIDL

You can use the public APIs here - https://public-api.solscan.io/docs/

or via explorer

https://explorer.solana.com/address/MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD/anchor-program

1
  • Yes but on my side I need a code solution without an external API. The comment below is more like I looking for
    – Swifty
    Commented Sep 2, 2022 at 21:43

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.