kklas / anchor-client-gen

A tool for generating solana web3 clients from anchor IDLs.
MIT License
135 stars 21 forks source link

feat: dependency inject programId with default value #62

Closed sol-mocha closed 1 year ago

sol-mocha commented 1 year ago

This PR addresses the concerns in #51 and allows callers to specify their own dynamic programId. If no programId is specified then the default value from programId.ts is used.

This feature will allow callers to decouple their internal management of their programId's from the generated code files from anchor-client-gen, making anchor-client-gen completely transparent to the integrating project, but still maintains backwards compatibility with the existing API.

example:

  static async fetch(
    c: Connection,
    address: PublicKey,
    programId: PublicKey = PROGRAM_ID
  ): Promise<Counter | null> {
    const info = await c.getAccountInfo(address)

    if (info === null) {
      return null
    }
    if (!info.owner.equals(programId)) {
      throw new Error("account doesn't belong to this program")
    }

    return this.decode(info.data)
  }
kklas commented 1 year ago

OK, seems like enough people want this. I've merged this and published v0.28.1. Thanks for the PR @dcaf-mocha!