@project-serum/anchor#ProgramAccount TypeScript Examples

The following examples show how to use @project-serum/anchor#ProgramAccount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Margin.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
static async loadPrefetched(
    program: Program<Zo>,
    st: State,
    ch: Cache | null,
    prefetchedMarginData: ProgramAccount<MarginSchema>,
    prefetchedControlData: ProgramAccount<ControlSchema>,
    withOrders: boolean,
  ): Promise<Margin> {
    if (ch)
      console.warn(
        "[DEPRECATED SOON: Cache param will soon be removed from here; cache is taken from state directly.]",
      );
    return (await super.loadPrefetchedWeb3(
      program,
      st,
      prefetchedMarginData,
      prefetchedControlData,
      withOrders,
    )) as Margin;
  }
Example #2
Source File: MarginWeb3.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
/**
   * Loads a new Margin object from prefetched schema;
   */
  protected static async loadPrefetchedWeb3(
    program: Program<Zo>,
    st: State,
    prefetchedMarginData: ProgramAccount<MarginSchema>,
    prefetchedControlData: ProgramAccount<ControlSchema>,
    withOrders: boolean,
  ): Promise<MarginWeb3> {
    const data = this.transformFetchedData(st, prefetchedMarginData.account);
    const control = await Control.loadPrefetched(
      program,
      prefetchedControlData.publicKey,
      prefetchedControlData.account,
    );
    const margin = new this(
      program,
      prefetchedMarginData.publicKey,
      data,
      control,
      st,
    );
    margin.loadBalances();
    margin.loadPositions();
    if (withOrders) {
      await margin.loadOrders();
    }
    return margin;
  }
Example #3
Source File: MarginWeb3.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
protected static async loadAllMarginAndControlSchemas(program: Program<Zo>) {
    const marginSchemas = (await program.account["margin"].all()).map(
      (t) => t as ProgramAccount<MarginSchema>,
    );
    const controlSchemas = (await program.account["control"].all()).map(
      (t) => t as ProgramAccount<ControlSchema>,
    );
    return marginSchemas.map((ms) => ({
      marginSchema: ms,
      controlSchema: controlSchemas.find((cs) =>
        cs.publicKey.equals(ms.account.control),
      ) as ProgramAccount<ControlSchema>,
    }));
  }
Example #4
Source File: mintWrapper.ts    From quarry with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Performs a mint of tokens to an account.
   * @returns
   */
  async performMintWithMinter({
    amount,
    minter,
  }: {
    amount: TokenAmount;
    minter: ProgramAccount<MinterData>;
  }): Promise<TransactionEnvelope> {
    const minterData = minter.account;
    const ata = await getOrCreateATA({
      provider: this.provider,
      mint: amount.token.mintAccount,
      owner: this.provider.wallet.publicKey,
    });
    return this.provider.newTX([
      ata.instruction,
      this.program.instruction.performMint(amount.toU64(), {
        accounts: {
          mintWrapper: minterData.mintWrapper,
          minterAuthority: minterData.minterAuthority,
          tokenMint: amount.token.mintAccount,
          destination: ata.address,
          minter: minter.publicKey,
          tokenProgram: TOKEN_PROGRAM_ID,
        },
      }),
    ]);
  }
Example #5
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Return all `Obligation` program accounts that have been created
   * @param {GetProgramAccountsFilter[]} [filters]
   * @returns {Promise<ProgramAccount<Obligation>[]>}
   * @memberof JetClient
   */
  async allObligations(filters?: GetProgramAccountsFilter[]): Promise<ProgramAccount<ObligationAccount>[]> {
    return (this.program.account.obligation as any).all(filters)
  }
Example #6
Source File: distribution.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   *
   * @static
   * @param {Program<RewardsIdl>} rewardsProgram
   * @returns {Promise<Distribution[]>}
   * @memberof Distribution
   */
  static async loadAll(rewardsProgram: Program<RewardsIdl>): Promise<Distribution[]> {
    const distributions = (await rewardsProgram.account.distribution.all()) as ProgramAccount<DistributionInfo>[]
    const addresses = distributions.map(dist => Distribution.derive(dist.account.seed, dist.account.seedLen))
    const vaultAddresses = addresses.map(address => address.vault)
    const vaults = await AssociatedToken.loadMultipleAux(rewardsProgram.provider.connection, vaultAddresses)

    return (
      _.zip(addresses, distributions, vaults)
        .filter(([address, distribution, vault]) => address && distribution && vault)
        .map(([address, distribution, vault]) => {
          if (!address) {
            throw new Error("Address is undefined")
          }
          if (!distribution) {
            throw new Error("Distribution is undefined")
          }
          if (!vault) {
            throw new Error("Vault is undefined")
          }
          return new Distribution(address, distribution.account, vault)
        })
        // Sort by beginAt descending
        .sort((a, b) =>
          b.distribution.tokenDistribution.beginAt.sub(a.distribution.tokenDistribution.beginAt).toNumber()
        )
    )
  }
Example #7
Source File: useParsedAccount.ts    From sail with Apache License 2.0 6 votes vote down vote up
useParsedAccount = <T>(
  key: PublicKey | null | undefined,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): ParsedAccountQueryResult<T> => {
  const { fetchKeys, onBatchCache } = useSail();
  const { network } = useSolana();

  const query = useQuery(
    makeParsedAccountQuery(key, network, fetchKeys, parser, options)
  );

  useAccountsSubscribe(useMemo(() => [key], [key]));

  // refresh from the cache whenever the cache is updated
  const { refetch } = query;
  useEffect(() => {
    if (!key) {
      return;
    }
    return onBatchCache((e) => {
      if (e.hasKey(key)) {
        void refetch();
      }
    });
  }, [key, fetchKeys, onBatchCache, refetch]);

  return query;
}
Example #8
Source File: bulkUserSubscription.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
/**
 * @param users
 * @param accountLoader
 */
export async function bulkPollingUserSubscribe(
	users: ClearingHouseUser[],
	accountLoader: BulkAccountLoader
): Promise<void> {
	if (users.length === 0) {
		await accountLoader.load();
		return;
	}

	// Fetch all the accounts first
	const program = users[0].clearingHouse.program;
	let userProgramAccounts: ProgramAccount[];
	let orderProgramAccounts: ProgramAccount[];
	await Promise.all([
		(async () => {
			userProgramAccounts = await program.account.user.all();
		})(),
		(async () => {
			orderProgramAccounts = await program.account.userOrders.all();
		})(),
	]);

	// Create a map of the authority to keys
	const authorityToKeys = new Map<string, UserPublicKeys>();
	const userToAuthority = new Map<string, string>();
	for (const userProgramAccount of userProgramAccounts) {
		const userAccountPublicKey = userProgramAccount.publicKey;
		const userAccount = userProgramAccount.account as UserAccount;

		authorityToKeys.set(userAccount.authority.toString(), {
			user: userAccountPublicKey,
			userPositions: userAccount.positions,
			userOrders: undefined,
		});

		userToAuthority.set(
			userAccountPublicKey.toString(),
			userAccount.authority.toString()
		);
	}
	for (const orderProgramAccount of orderProgramAccounts) {
		const userOrderAccountPublicKey = orderProgramAccount.publicKey;
		const userOrderAccount = orderProgramAccount.account as UserOrdersAccount;

		const authority = userToAuthority.get(userOrderAccount.user.toString());
		const userPublicKeys = authorityToKeys.get(authority);
		userPublicKeys.userOrders = userOrderAccountPublicKey;
	}

	await Promise.all(
		users.map((user) => {
			// Pull the keys from the authority map so we can skip fetching them in addToAccountLoader
			const userPublicKeys = authorityToKeys.get(user.authority.toString());
			return (
				user.accountSubscriber as PollingUserAccountSubscriber
			).addToAccountLoader(userPublicKeys);
		})
	);

	await accountLoader.load();

	await Promise.all(
		users.map(async (user) => {
			return user.subscribe();
		})
	);
}
Example #9
Source File: useParsedAccount.ts    From sail with Apache License 2.0 5 votes vote down vote up
useParsedAccounts = <T>(
  keys: (PublicKey | null | undefined)[],
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): ParsedAccountQueryResult<T>[] => {
  const { network } = useSolana();
  const data = useAccountsData(keys);
  return useQueries(
    keys.map(
      (key, i): UseQueryOptions<ProgramAccount<T> | null | undefined> => {
        const datum = data[i];
        return {
          queryKey: [
            "sail/parsedAccount",
            network,
            parser.programID.toString(),
            parser.name,
            key ? key.toString() : key,
          ],
          queryFn: () => {
            if (!datum) {
              return datum;
            }
            try {
              const parsed = parser.parse(datum.accountInfo.data);
              return { publicKey: datum.accountId, account: parsed };
            } catch (e) {
              throw new SailProgramAccountParseError(e, datum, parser);
            }
          },
          enabled: key !== undefined && datum !== undefined,
          ...options,
        };
      }
    )
  );
}
Example #10
Source File: useParsedAccount.ts    From sail with Apache License 2.0 5 votes vote down vote up
makeParsedAccountQuery = <T>(
  key: PublicKey | null | undefined,
  network: Network,
  fetchKeys: FetchKeysFn,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): UseQueryOptions<ProgramAccount<T> | null | undefined> => ({
  queryKey: [
    "sail/parsedAccount",
    network,
    parser.programID.toString(),
    parser.name,
    key ? key.toString() : key,
  ],
  queryFn: async (): Promise<ProgramAccount<T> | null | undefined> => {
    const [result] = await fetchKeysMaybe(fetchKeys, [key]);
    if (!result) {
      return result;
    }
    const data = result.data;
    if (!data) {
      return null;
    }

    try {
      const parsed = parser.parse(data.accountInfo.data);
      return {
        publicKey: data.accountId,
        account: parsed,
      };
    } catch (e) {
      throw new SailProgramAccountParseError(e, data, parser);
    }
  },
  staleTime: Infinity,
  enabled: key !== undefined,
  ...options,
})