@project-serum/anchor#Provider TypeScript Examples

The following examples show how to use @project-serum/anchor#Provider. 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: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   * @static
   * @param {Provider} provider
   * @returns {(Program<StakeIdl> | undefined)}
   * @memberof StakeClient
   */
  static use(provider: Provider): Program<StakeIdl> | undefined {
    return Hooks.usePromise(async () => StakeClient.connect(provider), [provider.connection])
  }
Example #2
Source File: index.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Create a new client for interacting with the Jet staking program.
 * @param {Provider} provider The provider with wallet/network access that can be used to send transactions.
 * @param {PublicKey} programId
 * @returns {Promise<Program<Idl>>} The client
 * @memberof JetClient
 */
export async function connect<T extends Idl>(programId: Address, provider: Provider): Promise<Program<T>> {
  const idl = await Program.fetchIdl<T>(programId, provider)

  if (!idl) {
    throw new Error("Program lacks an IDL account.")
  }

  return new Program(idl, programId, provider)
}
Example #3
Source File: index.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Fetches multiple idls from the blockchain.
 *
 * In order to use this method, an IDL must have been previously initialized
 * via the anchor CLI's `anchor idl init` command.
 *
 * @param programIds The on-chain addresses of the programs.
 * @param provider   The network and wallet context.
 */
export async function fetchMultipleIdls<Idls extends Idl[] = Idl[]>(
  provider: Provider,
  programIds: Address[]
): Promise<Idls> {
  const idlAddresses: PublicKey[] = []
  for (const programId of programIds) {
    const programAddress = translateAddress(programId)

    const idlAddr = await idlAddress(programAddress)
    idlAddresses.push(idlAddr)
  }

  const accountInfos = await provider.connection.getMultipleAccountsInfo(idlAddresses)

  const idls: Idl[] = []
  for (const accountInfo of accountInfos) {
    if (!accountInfo) {
      throw new Error("Idl does not exists")
    }
    const idlAccount = decodeIdlAccount(accountInfo.data.slice(8))
    const inflatedIdl = inflate(idlAccount.data)
    const idl = JSON.parse(utf8.decode(inflatedIdl))
    idls.push(idl)
  }
  return idls as Idls
}
Example #4
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
static async connect(provider: Provider, cluster: JetCluster): Promise<JetPrograms> {
    const config = JetClient.getConfig(cluster)

    const [marginIdl, metadataIdl, marginPoolIdl, marginSerumIdl, marginSwapIdl] = await fetchMultipleIdls<
      [JetMarginIdl, JetMetadataIdl, JetMarginPoolIdl, JetMarginSerumIdl, JetMarginSwapIdl]
    >(provider, [
      config.marginProgramId,
      config.metadataProgramId,
      config.marginPoolProgramId,
      config.marginSerumProgramId,
      config.marginSwapProgramId
    ])

    const programs: JetPrograms = {
      config,
      margin: new Program(marginIdl, config.marginProgramId, provider),
      metadata: new Program(metadataIdl, config.metadataProgramId, provider),
      marginPool: new Program(marginPoolIdl, config.marginPoolProgramId, provider),
      marginSerum: new Program(marginSerumIdl, config.marginSerumProgramId, provider),
      marginSwap: new Program(marginSwapIdl, config.marginSwapProgramId, provider)
    }

    return programs
  }
Example #5
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Create a new client for interacting with the Jet lending program.
   * @param {Provider} provider The provider with wallet/network access that can be used to send transactions.
   * @param {boolean} [devnet] Flag to determine if the connection is for devnet
   * @returns {Promise<JetClient>} The client
   * @memberof JetClient
   */
  static async connect(provider: Provider, devnet?: boolean): Promise<JetClient> {
    const idl = await Program.fetchIdl(JET_ID, provider)
    return new JetClient(new Program<Jet>(idl as Jet, JET_ID, provider), devnet)
  }
Example #6
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * @static
   * @param {Provider} provider
   * @returns {(JetClient | undefined)} JetClient | undefined
   * @memberof JetClient
   */
  static use(provider: Provider, devnet?: boolean): JetClient | undefined {
    return Hooks.usePromise(async () => provider && JetClient.connect(provider, devnet), [provider])
  }
Example #7
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Create a new client for interacting with the Jet rewards program
   * @param {Provider} provider The provider with wallet/network access that can be used to send transactions.
   * @returns {Promise<Program<RewardsIdl>>} The program
   * @memberof RewardsClient
   */
  static async connect(provider: Provider): Promise<Program<RewardsIdl>> {
    return await connect(RewardsClient.PROGRAM_ID, provider)
  }
Example #8
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * React hook to use the rewards program
   *
   * @static
   * @param {Provider} provider
   * @returns {(Program<RewardsIdl> | undefined)} The program
   * @memberof RewardsClient
   */
  static use(provider: Provider | undefined): Program<RewardsIdl> | undefined {
    return Hooks.usePromise(async () => provider && RewardsClient.connect(provider), [provider?.connection])
  }
Example #9
Source File: client.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Create a new client for interacting with the Jet staking program.
   * @param {Provider} provider The provider with wallet/network access that can be used to send transactions.
   * @returns {Promise<Program<StakeIdl>>} The client
   * @memberof StakeClient
   */
  static async connect(provider: Provider): Promise<Program<StakeIdl>> {
    return await connect(StakeClient.PROGRAM_ID, provider)
  }
Example #10
Source File: index.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Instantiates a Client for the Jet P2P program using the
   * argued provider instance.
   * @static
   * @param {Provider} provider
   * @returns {Promise<Client>}
   * @memberof Client
   */
  static async connect(provider: Provider): Promise<Client> {
    const idl = await Program.fetchIdl(JET_P2P_PROGRAM_ID, provider)
    return new Client(new Program(idl as any, JET_P2P_PROGRAM_ID, provider))
  }
Example #11
Source File: helpers.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
createUnderlyingAndQuoteMints = async (
  provider: Provider,
  wallet: Keypair,
  mintAuthority: Keypair
) => {
  const underlyingToken = await Token.createMint(
    provider.connection,
    wallet,
    mintAuthority.publicKey,
    null,
    0,
    TOKEN_PROGRAM_ID
  );

  const quoteToken = await Token.createMint(
    provider.connection,
    wallet,
    mintAuthority.publicKey,
    null,
    0,
    TOKEN_PROGRAM_ID
  );
  return {
    quoteToken,
    underlyingToken,
  };
}
Example #12
Source File: serum.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
async function setupMarket({
  provider,
  program,
  baseMint,
  quoteMint,
  marketLoader,
  optionMarket,
}: {
  provider: Provider;
  program: Program<PsyAmerican>;
  optionMarket: OptionMarketV2;
  baseMint: PublicKey;
  quoteMint: PublicKey;
  marketLoader: MarketLoader;
}): Promise<
  [
    MarketProxy,
    anchor.web3.PublicKey | anchor.BN,
    anchor.web3.PublicKey,
    number
  ]
> {
  const {
    serumMarketKey: marketAPublicKey,
    vaultOwner,
    marketAuthority,
    marketAuthorityBump,
  } = await listMarket({
    provider,
    program,
    quoteMint: quoteMint,
    dexProgramId: DEX_PID,
    feeRateBps: 0,
    optionMarket,
  });
  const MARKET_A_USDC = await marketLoader(marketAPublicKey as PublicKey);
  return [MARKET_A_USDC, vaultOwner, marketAuthority, marketAuthorityBump];
}
Example #13
Source File: serum.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
marketLoader =
  (
    provider: anchor.Provider,
    program: Program<PsyAmerican>,
    optionMarketKey: PublicKey,
    marketAuthorityBump: number
  ) =>
  async (marketKey: PublicKey) => {
    return new MarketProxyBuilder()
      .middleware(
        new OpenOrdersPda({
          proxyProgramId: program.programId,
          dexProgramId: DEX_PID,
        })
      )
      .middleware(new Validation(optionMarketKey, marketAuthorityBump))
      .middleware(new Logger())
      .middleware(new ReferralFees())
      .load({
        connection: provider.connection,
        market: marketKey,
        dexProgramId: DEX_PID,
        proxyProgramId: program.programId,
        options: { commitment: "recent" },
      });
  }
Example #14
Source File: serum.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
initMarket = async (
  provider: Provider,
  /** The PsyOptions anchor.Program */
  program: Program<PsyAmerican>,
  marketLoader: MarketLoader,
  optionMarket: OptionMarketV2,
  pcMint: PublicKey
) => {
  const [MARKET_A_USDC, vaultSigner, marketAuthority, marketAuthorityBump] =
    await setupMarket({
      provider,
      program,
      baseMint: optionMarket.optionMint,
      quoteMint: pcMint,
      marketLoader,
      optionMarket,
    });
  return {
    marketA: MARKET_A_USDC,
    vaultSigner,
    usdc: pcMint,
    marketAuthority,
    marketAuthorityBump,
  };
}
Example #15
Source File: serum.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
listMarket = async ({
  provider,
  program,
  quoteMint,
  dexProgramId,
  feeRateBps,
  optionMarket,
}: {
  provider: Provider;
  program: Program<PsyAmerican>;
  quoteMint: PublicKey;
  dexProgramId: PublicKey;
  feeRateBps: number;
  optionMarket: OptionMarketV2;
}) => {
  // @ts-ignore: TODO: Remove when anchor PR released
  const { wallet } = provider;

  const { bids, asks, eventQueue } = await createFirstSetOfAccounts({
    provider,
    wallet: wallet as anchor.Wallet,
    dexProgramId,
  });

  const { serumMarketKey, vaultOwner, marketAuthority, marketAuthorityBump } =
    await initSerum(
      provider,
      program,
      optionMarket,
      quoteMint,
      eventQueue.publicKey,
      bids.publicKey,
      asks.publicKey,
      dexProgramId
    );

  return { serumMarketKey, vaultOwner, marketAuthority, marketAuthorityBump };
}
Example #16
Source File: Swap.tsx    From swap-ui with Apache License 2.0 6 votes vote down vote up
function unwrapSol(
  provider: Provider,
  wrappedSolAccount: Keypair
): { tx: Transaction; signers: Array<Signer | undefined> } {
  const tx = new Transaction();
  tx.add(
    Token.createCloseAccountInstruction(
      TOKEN_PROGRAM_ID,
      wrappedSolAccount.publicKey,
      provider.wallet.publicKey,
      provider.wallet.publicKey,
      []
    )
  );
  return { tx, signers: [] };
}
Example #17
Source File: helpers.ts    From sdk with MIT License 6 votes vote down vote up
export async function loadAuctionHouseProgram(
	connection: Connection,
	signer: IWalletSigner
) {
	const provider = new Provider(connection, signer, {
		preflightCommitment: "recent",
	})
	const idl = await Program.fetchIdl(AUCTION_HOUSE_PROGRAM_ID, provider)
	return new Program(idl!, AUCTION_HOUSE_PROGRAM_ID, provider)
}
Example #18
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function createTokenAccount(
  provider: Provider,
  mint: PublicKey,
  owner: PublicKey,
): Promise<PublicKey> {
  const vault = Keypair.generate();
  const tx = new Transaction();
  tx.add(...(await createTokenAccountIxs(vault, provider, mint, owner)));
  await provider.send(tx, [vault]);
  return vault.publicKey;
}
Example #19
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export function createProgram(
  provider: Provider,
  cluster: Cluster,
): Program<Zo> {
  if (cluster === Cluster.Devnet) {
    return new Program<Zo>(IDL, ZERO_ONE_DEVNET_PROGRAM_ID, provider);
  } else {
    return new Program<Zo>(IDL, ZERO_ONE_MAINNET_PROGRAM_ID, provider);
  }
}
Example #20
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function getMintInfo(
  provider: Provider,
  pubkey: PublicKey,
): Promise<MintInfo> {
  const data = (await provider.connection.getAccountInfo(pubkey))?.data;
  if (!data) throw Error(`Couldn't load mint data for ${pubkey.toBase58()}`);
  const m = MintLayout.decode(data);
  return {
    mintAuthority: new PublicKey(m.mintAuthority),
    supply: u64.fromBuffer(m.supply),
    decimals: m.decimals,
    isInitialized: !!m.isInitialized,
    freezeAuthority: new PublicKey(m.freezeAuthority),
  };
}
Example #21
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function createMintIxs(
  mint: Keypair,
  provider: Provider,
  authority: PublicKey,
  decimals: number,
  freezeAuthority?: PublicKey,
): Promise<TransactionInstruction[]> {
  return [
    SystemProgram.createAccount({
      fromPubkey: provider.wallet.publicKey,
      newAccountPubkey: mint.publicKey,
      space: MintLayout.span,
      lamports: await Token.getMinBalanceRentForExemptMint(provider.connection),
      programId: TOKEN_PROGRAM_ID,
    }),
    Token.createInitMintInstruction(
      TOKEN_PROGRAM_ID,
      mint.publicKey,
      decimals,
      authority,
      freezeAuthority ?? null,
    ),
  ];
}
Example #22
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function createTokenAccountIxs(
  vault: Keypair,
  provider: Provider,
  mint: PublicKey,
  owner: PublicKey,
): Promise<TransactionInstruction[]> {
  return [
    SystemProgram.createAccount({
      fromPubkey: provider.wallet.publicKey,
      newAccountPubkey: vault.publicKey,
      space: AccountLayout.span,
      lamports: await Token.getMinBalanceRentForExemptAccount(
        provider.connection,
      ),
      programId: TOKEN_PROGRAM_ID,
    }),
    Token.createInitAccountInstruction(
      TOKEN_PROGRAM_ID,
      mint,
      vault.publicKey,
      owner,
    ),
  ];
}
Example #23
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function createMint(
  provider: Provider,
  authority: PublicKey,
  decimals: number,
  freezeAuthority?: PublicKey,
): Promise<PublicKey> {
  const mint = new Keypair();
  const tx = new Transaction();
  tx.add(
    ...(await createMintIxs(
      mint,
      provider,
      authority,
      decimals,
      freezeAuthority,
    )),
  );
  await provider.send(tx, [mint]);
  return mint.publicKey;
}
Example #24
Source File: auth.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Custom React hook to use the authentication program as state.
   * @static
   * @param {Provider} provider
   * @returns {(Program<AuthIdl> | undefined)}
   * @memberof Auth
   */
  static useAuthProgram(provider: Provider): Program<AuthIdl> | undefined {
    return Hooks.usePromise(async () => Auth.connect(provider), [provider])
  }
Example #25
Source File: index.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
export async function mintTo(
  provider: Provider,
  mint: PublicKey,
  dest: PublicKey,
  amount: number,
): Promise<void> {
  const tx = new Transaction();
  tx.add(...createMintToIxs(mint, dest, provider.wallet.publicKey, amount));
  await provider.send(tx, []);
}
Example #26
Source File: state-helpers.ts    From candy-machine-v2 with MIT License 6 votes vote down vote up
export async function getCandyMachineState(
  candyMachineId: web3.PublicKey,
  provider: Provider
) {
  try {
    const idl = await Program.fetchIdl(CANDY_MACHINE_PROGRAM, provider);
    const program = new Program(idl, CANDY_MACHINE_PROGRAM, provider);
    return await getMetadata(program, candyMachineId);
  } catch (error) {
    console.error(error);
  }
}
Example #27
Source File: auth.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * Creates a connection to the authentication program.
   * @static
   * @param {Provider} provider
   * @returns {Promise<Program<AuthIdl>>}
   * @memberof Auth
   */
  static connect(provider: Provider): Promise<Program<AuthIdl>> {
    return connect(Auth.PROGRAM_ID, provider)
  }
Example #28
Source File: mockAccounts.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
export async function mockUSDCMint(provider: Provider): Promise<Keypair> {
	const fakeUSDCMint = anchor.web3.Keypair.generate();
	const createUSDCMintAccountIx = SystemProgram.createAccount({
		fromPubkey: provider.wallet.publicKey,
		newAccountPubkey: fakeUSDCMint.publicKey,
		lamports: await Token.getMinBalanceRentForExemptMint(provider.connection),
		space: MintLayout.span,
		programId: TOKEN_PROGRAM_ID,
	});
	const initCollateralMintIx = Token.createInitMintInstruction(
		TOKEN_PROGRAM_ID,
		fakeUSDCMint.publicKey,
		6,
		provider.wallet.publicKey,
		null
	);

	const fakeUSDCTx = new Transaction();
	fakeUSDCTx.add(createUSDCMintAccountIx);
	fakeUSDCTx.add(initCollateralMintIx);

	const _fakeUSDCTxResult = await sendAndConfirmTransaction(
		provider.connection,
		fakeUSDCTx,
		// @ts-ignore
		[provider.wallet.payer, fakeUSDCMint],
		{
			skipPreflight: false,
			commitment: 'recent',
			preflightCommitment: 'recent',
		}
	);
	return fakeUSDCMint;
}
Example #29
Source File: testHelpers.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
export async function mockUSDCMint(provider: Provider): Promise<Keypair> {
	const fakeUSDCMint = anchor.web3.Keypair.generate();
	const createUSDCMintAccountIx = SystemProgram.createAccount({
		fromPubkey: provider.wallet.publicKey,
		newAccountPubkey: fakeUSDCMint.publicKey,
		lamports: await Token.getMinBalanceRentForExemptMint(provider.connection),
		space: MintLayout.span,
		programId: TOKEN_PROGRAM_ID,
	});
	const initCollateralMintIx = Token.createInitMintInstruction(
		TOKEN_PROGRAM_ID,
		fakeUSDCMint.publicKey,
		6,
		provider.wallet.publicKey,
		null
	);

	const fakeUSDCTx = new Transaction();
	fakeUSDCTx.add(createUSDCMintAccountIx);
	fakeUSDCTx.add(initCollateralMintIx);

	await sendAndConfirmTransaction(
		provider.connection,
		fakeUSDCTx,
		// @ts-ignore
		[provider.wallet.payer, fakeUSDCMint],
		{
			skipPreflight: false,
			commitment: 'recent',
			preflightCommitment: 'recent',
		}
	);
	return fakeUSDCMint;
}