@coral-xyz/anchor
Version:
Anchor client
77 lines • 2.79 kB
JavaScript
import camelCase from "camelcase";
import { Buffer } from "buffer";
import { PublicKey } from "@solana/web3.js";
import * as borsh from "@coral-xyz/borsh";
export function isCompositeAccounts(accountItem) {
return "accounts" in accountItem;
}
// Deterministic IDL address as a function of the program id.
export async function idlAddress(programId) {
const base = (await PublicKey.findProgramAddress([], programId))[0];
return await PublicKey.createWithSeed(base, seed(), programId);
}
// Seed for generating the idlAddress.
export function seed() {
return "anchor:idl";
}
const IDL_ACCOUNT_LAYOUT = borsh.struct([
borsh.publicKey("authority"),
borsh.vecU8("data"),
]);
export function decodeIdlAccount(data) {
return IDL_ACCOUNT_LAYOUT.decode(data);
}
export function encodeIdlAccount(acc) {
const buffer = Buffer.alloc(1000); // TODO: use a tighter buffer.
const len = IDL_ACCOUNT_LAYOUT.encode(acc, buffer);
return buffer.slice(0, len);
}
/**
* Convert the given IDL to camelCase.
*
* The IDL is generated from Rust which has different conventions compared to
* JS/TS, e.g. instruction names in Rust are snake_case.
*
* The conversion happens automatically for programs, however, if you are using
* internals such as `BorshInstructionCoder` and you only have the original
* (not camelCase) IDL, you might need to use this function.
*
* @param idl IDL to convert to camelCase
* @returns camelCase version of the IDL
*/
export function convertIdlToCamelCase(idl) {
const KEYS_TO_CONVERT = ["name", "path", "account", "relations", "generic"];
// `my_account.field` is getting converted to `myAccountField` but we
// need `myAccount.field`.
const toCamelCase = (s) => s
.split(".")
.map((part) => camelCase(part, { locale: false }))
.join(".");
const recursivelyConvertNamesToCamelCase = (obj) => {
for (const key in obj) {
const val = obj[key];
if (KEYS_TO_CONVERT.includes(key)) {
obj[key] = Array.isArray(val) ? val.map(toCamelCase) : toCamelCase(val);
}
else if (typeof val === "object") {
recursivelyConvertNamesToCamelCase(val);
}
}
};
const camelCasedIdl = structuredClone(idl);
recursivelyConvertNamesToCamelCase(camelCasedIdl);
return camelCasedIdl;
}
/** Conveniently handle all defined field kinds with proper type support. */
export function handleDefinedFields(fields, unitCb, namedCb, tupleCb) {
// Unit
if (!(fields === null || fields === void 0 ? void 0 : fields.length))
return unitCb();
// Named
if (fields[0].name) {
return namedCb(fields);
}
// Tuple
return tupleCb(fields);
}
//# sourceMappingURL=idl.js.map