coral-xyz / anchor

⚓ Solana Sealevel Framework
https://anchor-lang.com
Apache License 2.0
3.67k stars 1.34k forks source link

Refactor `fetchIdl` to take in `connection`, instead of `provider` #1373

Open zkhalapyan opened 2 years ago

zkhalapyan commented 2 years ago

fetchIdl requires a provider, but only consumes a connection — more pragmatically, to create a provider, one must first have access to a wallet which requires authentication that's not always available. More ideologically, the more direct inputs we provide to the function, the less coupled and more flexible and testible our systems (law of demeter).

Alternatively, is there a way to fetch the IDL without having access to a provider? Or is there a way to create a Provider without having access to a wallet?

nickcruz commented 2 years ago

If it's strictly to fetch an IDL / create a Program for fetching some parsed account data, I did this just to satisfy the Provider requirement:

// Create a connection as you like (even just a normal @solana/web3.js Connection is fine)
const connection = createConnection("devnet");

// Create your Anchor Provider that rejects when it signs anything.
const provider = new Provider(
  connection,
  {
    signTransaction: () => Promise.reject(),
    signAllTransactions: () => Promise.reject(),
    publicKey: new PublicKey("BSFtCudCd4pR4LSFqWPjbtXPKSNVbGkc35gRNdnqjMCU"),
  },
  {}
);

Later when you actually want to get your program, say just to get some data, you can use this provider and then get some account:

const program = (await Program.at(
  programId,
  provider
)) as Program<MergeReceipt>;

const receiptAccount = await program.account.receiptAccount.fetch(
  dataAccount
);
zkhalapyan commented 2 years ago

Ah, I see — thanks. I would say this looks fragile and could break in case the implementation detail of IDL fetcher changes, but then everything is fragile, so probably ok for now. The slightly less fragile version I think is to expose a wrapped version on the backend that uses a keypair and provide some APIs to read the data.