@coral-xyz/anchor
Version:
Anchor client
226 lines • 8.82 kB
JavaScript
import EventEmitter from "eventemitter3";
import { SystemProgram, } from "@solana/web3.js";
import { getProvider } from "../../provider.js";
import { BorshCoder } from "../../coder/index.js";
import { translateAddress } from "../common.js";
import * as rpcUtil from "../../utils/rpc.js";
export default class AccountFactory {
static build(idl, coder, programId, provider) {
var _a;
return ((_a = idl.accounts) !== null && _a !== void 0 ? _a : []).reduce((accountFns, acc) => {
accountFns[acc.name] = new AccountClient(idl, acc, programId, provider, coder);
return accountFns;
}, {});
}
}
export class AccountClient {
/**
* Returns the number of bytes in this account.
*/
get size() {
return this._size;
}
/**
* Returns the program ID owning all accounts.
*/
get programId() {
return this._programId;
}
/**
* Returns the client's wallet and network provider.
*/
get provider() {
return this._provider;
}
/**
* Returns the coder.
*/
get coder() {
return this._coder;
}
constructor(idl, idlAccount, programId, provider, coder) {
this._idlAccount = idlAccount;
this._programId = programId;
this._provider = provider !== null && provider !== void 0 ? provider : getProvider();
this._coder = coder !== null && coder !== void 0 ? coder : new BorshCoder(idl);
this._size = this._coder.accounts.size(idlAccount.name);
}
/**
* Returns a deserialized account, returning null if it doesn't exist.
*
* @param address The address of the account to fetch.
*/
async fetchNullable(address, commitment) {
const { data } = await this.fetchNullableAndContext(address, commitment);
return data;
}
/**
* Returns a deserialized account along with the associated rpc response context, returning null if it doesn't exist.
*
* @param address The address of the account to fetch.
*/
async fetchNullableAndContext(address, commitment) {
const accountInfo = await this.getAccountInfoAndContext(address, commitment);
const { value, context } = accountInfo;
return {
data: value && value.data.length !== 0
? this._coder.accounts.decode(this._idlAccount.name, value.data)
: null,
context,
};
}
/**
* Returns a deserialized account.
*
* @param address The address of the account to fetch.
*/
async fetch(address, commitment) {
const { data } = await this.fetchNullableAndContext(address, commitment);
if (data === null) {
throw new Error(`Account does not exist or has no data ${address.toString()}`);
}
return data;
}
/**
* Returns a deserialized account along with the associated rpc response context.
*
* @param address The address of the account to fetch.
*/
async fetchAndContext(address, commitment) {
const { data, context } = await this.fetchNullableAndContext(address, commitment);
if (data === null) {
throw new Error(`Account does not exist ${address.toString()}`);
}
return { data, context };
}
/**
* Returns multiple deserialized accounts.
* Accounts not found or with wrong discriminator are returned as null.
*
* @param addresses The addresses of the accounts to fetch.
*/
async fetchMultiple(addresses, commitment) {
const accounts = await this.fetchMultipleAndContext(addresses, commitment);
return accounts.map((account) => (account ? account.data : null));
}
/**
* Returns multiple deserialized accounts.
* Accounts not found or with wrong discriminator are returned as null.
*
* @param addresses The addresses of the accounts to fetch.
*/
async fetchMultipleAndContext(addresses, commitment) {
const accounts = await rpcUtil.getMultipleAccountsAndContext(this._provider.connection, addresses.map((address) => translateAddress(address)), commitment);
// Decode accounts where discriminator is correct, null otherwise
return accounts.map((result) => {
if (result == null) {
return null;
}
const { account, context } = result;
return {
data: this._coder.accounts.decode(this._idlAccount.name, account.data),
context,
};
});
}
/**
* Returns all instances of this account type for the program.
*
* @param filters User-provided filters to narrow the results from `connection.getProgramAccounts`.
*
* When filters are not defined this method returns all
* the account instances.
*
* When filters are of type `Buffer`, the filters are appended
* after the discriminator.
*
* When filters are of type `GetProgramAccountsFilter[]`,
* filters are appended after the discriminator filter.
*/
async all(filters) {
const filter = this.coder.accounts.memcmp(this._idlAccount.name, filters instanceof Buffer ? filters : undefined);
const coderFilters = [];
if ((filter === null || filter === void 0 ? void 0 : filter.offset) != undefined && (filter === null || filter === void 0 ? void 0 : filter.bytes) != undefined) {
coderFilters.push({
memcmp: { offset: filter.offset, bytes: filter.bytes },
});
}
if ((filter === null || filter === void 0 ? void 0 : filter.dataSize) != undefined) {
coderFilters.push({ dataSize: filter.dataSize });
}
let resp = await this._provider.connection.getProgramAccounts(this._programId, {
commitment: this._provider.connection.commitment,
filters: [...coderFilters, ...(Array.isArray(filters) ? filters : [])],
});
return resp.map(({ pubkey, account }) => {
return {
publicKey: pubkey,
account: this._coder.accounts.decode(this._idlAccount.name, account.data),
};
});
}
/**
* Returns an `EventEmitter` emitting a "change" event whenever the account
* changes.
*/
subscribe(address, commitment) {
const sub = subscriptions.get(address.toString());
if (sub) {
return sub.ee;
}
const ee = new EventEmitter();
address = translateAddress(address);
const listener = this._provider.connection.onAccountChange(address, (acc) => {
const account = this._coder.accounts.decode(this._idlAccount.name, acc.data);
ee.emit("change", account);
}, commitment);
subscriptions.set(address.toString(), {
ee,
listener,
});
return ee;
}
/**
* Unsubscribes from the account at the given address.
*/
async unsubscribe(address) {
let sub = subscriptions.get(address.toString());
if (!sub) {
console.warn("Address is not subscribed");
return;
}
if (subscriptions) {
await this._provider.connection
.removeAccountChangeListener(sub.listener)
.then(() => {
subscriptions.delete(address.toString());
})
.catch(console.error);
}
}
/**
* Returns an instruction for creating this account.
*/
async createInstruction(signer, sizeOverride) {
const size = this.size;
if (this._provider.publicKey === undefined) {
throw new Error("This function requires the Provider interface implementor to have a 'publicKey' field.");
}
return SystemProgram.createAccount({
fromPubkey: this._provider.publicKey,
newAccountPubkey: signer.publicKey,
space: sizeOverride !== null && sizeOverride !== void 0 ? sizeOverride : size,
lamports: await this._provider.connection.getMinimumBalanceForRentExemption(sizeOverride !== null && sizeOverride !== void 0 ? sizeOverride : size),
programId: this._programId,
});
}
async getAccountInfo(address, commitment) {
return await this._provider.connection.getAccountInfo(translateAddress(address), commitment);
}
async getAccountInfoAndContext(address, commitment) {
return await this._provider.connection.getAccountInfoAndContext(translateAddress(address), commitment);
}
}
// Tracks all subscriptions.
const subscriptions = new Map();
//# sourceMappingURL=account.js.map