@project-serum/anchor#AnchorProvider TypeScript Examples

The following examples show how to use @project-serum/anchor#AnchorProvider. 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: workspace.ts    From tribeca with GNU Affero General Public License v3.0 6 votes vote down vote up
makeSDK = (): TribecaSDK => {
  const anchorProvider = AnchorProvider.env();
  anchor.setProvider(anchorProvider);

  const provider = SolanaProvider.init({
    connection: anchorProvider.connection,
    wallet: anchorProvider.wallet,
    opts: anchorProvider.opts,
  });
  return TribecaSDK.load({
    provider,
  });
}
Example #2
Source File: utils.ts    From saber-periphery with GNU Affero General Public License v3.0 6 votes vote down vote up
initATA = async (
  token: Token,
  owner: Signer,
  mint?: { minter: Signer; mintAmount: number }
): Promise<PublicKey> => {
  const account = await SPLToken.getAssociatedTokenAddress(
    ASSOCIATED_TOKEN_PROGRAM_ID,
    TOKEN_PROGRAM_ID,
    token.mintAccount,
    owner.publicKey
  );

  const tx = new Transaction().add(
    SPLToken.createAssociatedTokenAccountInstruction(
      ASSOCIATED_TOKEN_PROGRAM_ID,
      TOKEN_PROGRAM_ID,
      token.mintAccount,
      account,
      owner.publicKey,
      AnchorProvider.env().wallet.publicKey
    )
  );

  if (mint) {
    tx.add(
      SPLToken.createMintToInstruction(
        TOKEN_PROGRAM_ID,
        token.mintAccount,
        account,
        mint.minter.publicKey,
        [],
        mint.mintAmount
      )
    );
  }
  // mint tokens
  await AnchorProvider.env().sendAndConfirm(
    tx,
    mint ? [mint.minter] : undefined,
    {
      commitment: "confirmed",
    }
  );
  return account;
}
Example #3
Source File: market.spec.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
describe("JetMarket", () => {
  let client: JetClient
  let market: JetMarket

  beforeAll(async () => {
    const wallet = Keypair.generate()
    const provider = new AnchorProvider(new Connection(clusterApiUrl("devnet")), new NodeWallet(wallet), {})
    client = await JetClient.connect(provider, true)
  })

  test("properly loads from an address", async () => {
    market = await JetMarket.load(client, JET_MARKET_ADDRESS_DEVNET)
    expect(market).toBeTruthy()
  })

  test("can be refreshed", async () => {
    await market.refresh()
  })
})
Example #4
Source File: unbondingAccount.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   *
   * @static
   * @param {UnbondingAccount} unbondingAccount
   * @param {StakeAccount} stakeAccount
   * @param {StakePool} stakePool
   * @param {Provider} provider
   * @returns {Promise<TransactionInstruction[]>}
   * @memberof UnbondingAccount
   */
  static async withdrawUnbonded(
    unbondingAccount: UnbondingAccount,
    stakeAccount: StakeAccount,
    stakePool: StakePool,
    provider: AnchorProvider
  ): Promise<TransactionInstruction[]> {
    const ix: TransactionInstruction[] = []
    const tokenReceiver = await AssociatedToken.withCreate(
      ix,
      provider,
      stakeAccount.stakeAccount.owner,
      stakePool.stakePool.tokenMint
    )
    this.withWithdrawUnbonded(ix, unbondingAccount, stakeAccount, stakePool, tokenReceiver, provider.wallet.publicKey)
    return ix
  }
Example #5
Source File: stakeAccount.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   * @static
   * @param {Provider} provider
   * @param {StakePool} stakePool
   * @param {ProgramAccount<Realm>} realm
   * @param {PublicKey} owner
   * @param {PublicKey} collateralTokenAccount
   * @param {BN} amount
   * @returns {Promise<string>}
   * @memberof StakeAccount
   */
  static async addStake(
    provider: AnchorProvider,
    stakePool: StakePool,
    owner: PublicKey,
    collateralTokenAccount: PublicKey,
    amount: BN
  ): Promise<string> {
    const instructions: TransactionInstruction[] = []

    await this.withCreate(instructions, stakePool.program, stakePool.addresses.stakePool, owner, owner)
    await this.withAddStake(instructions, stakePool, owner, owner, collateralTokenAccount, amount)

    return provider.sendAndConfirm(new Transaction().add(...instructions))
  }
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
   * @param {PublicKey} targetAccount
   * @param {PublicKey} tokenMint
   * @param {DistributionCreateParams} params
   * @returns {Promise<string>}
   * @memberof Distribution
   */
  static async create(
    rewardsProgram: Program<RewardsIdl>,
    provider: AnchorProvider,
    targetAccount: PublicKey,
    tokenMint: PublicKey,
    params: DistributionCreateParams
  ): Promise<string> {
    const addresses = this.derive(params.args.seed)
    return rewardsProgram.methods
      .distributionCreate({
        ...params.args,
        targetAccount
      })
      .accounts({
        ...params.accounts,
        distribution: addresses.distribution,
        vault: addresses.vault,
        payerRent: provider.wallet.publicKey,
        tokenMint,
        tokenProgram: TOKEN_PROGRAM_ID,
        systemProgram: SystemProgram.programId,
        rent: SYSVAR_RENT_PUBKEY
      })
      .rpc()
  }
Example #7
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
   * @param {StakePool} distributionTarget
   * @param {DistributionCreateParams} params
   * @memberof Distribution
   */
  static async createForStakePool(
    rewardsProgram: Program<RewardsIdl>,
    provider: AnchorProvider,
    distributionTarget: StakePool,
    params: DistributionCreateParams
  ) {
    const stakePoolVault = distributionTarget.addresses.stakePoolVault
    const tokenMint = distributionTarget.stakePool.tokenMint
    await this.create(rewardsProgram, provider, stakePoolVault, tokenMint, params)
  }
Example #8
Source File: tokenFaucet.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   * @static
   * @param {Provider} provider
   * @param {PublicKey} faucet
   * @param {PublicKey} user
   * @param {PublicKey} mint
   * @returns {Promise<string>}
   * @memberof TokenFaucet
   */
  static async airdropToken(
    provider: AnchorProvider,
    faucet: PublicKey,
    user: PublicKey,
    mint: PublicKey
  ): Promise<string> {
    const instructions: TransactionInstruction[] = []

    // Check for user token account
    // If it doesn't exist add instructions to create it
    const address = await AssociatedToken.withCreate(instructions, provider, user, mint)

    // Create airdrop instructions
    await this.withAirdrop(instructions, mint, faucet, address)

    // Execute airdrop
    return provider.sendAndConfirm(new Transaction().add(...instructions))
  }
Example #9
Source File: associatedToken.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * add unWrap SOL IX
   * @param {TransactionInstruction[]} instructions
   * @param {Provider} provider
   * @param {owner} owner
   * @param {tokenAccount} tokenAccount
   * @param {mint} mint
   * @param {amount} amount
   */
  static async withUnwrapIfNative(
    instructions: TransactionInstruction[],
    provider: AnchorProvider,
    owner: PublicKey, //user pubkey
    tokenAccount: PublicKey,
    mint: PublicKey,
    amount: BN
  ): Promise<void> {
    if (mint.equals(NATIVE_MINT)) {
      //create a new ata if ata doesn't not exist
      const ata = await this.withCreate(instructions, provider, owner, mint)
      //IX to transfer wSOL to ATA
      const transferIx = createTransferInstruction(tokenAccount, ata, owner, BigInt(amount.toString()))
      //add transfer IX
      instructions.push(transferIx)
      //add close account IX
      await this.withClose(instructions, owner, mint, owner)
    }
  }
Example #10
Source File: associatedToken.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Add wrap SOL IX
   * @param instructions
   * @param provider
   * @param owner
   * @param mint
   * @param amount
   */
  static async withWrapIfNativeMint(
    instructions: TransactionInstruction[],
    provider: AnchorProvider,
    owner: PublicKey,
    mint: PublicKey,
    amount: BN
  ): Promise<void> {
    //only run if mint is wrapped sol mint
    if (mint.equals(NATIVE_MINT)) {
      //this will add instructions to create ata if ata does not exist, if exist, we will get the ata address
      const ata = await this.withCreate(instructions, provider, owner, mint)
      //IX to transfer sol to ATA
      const transferIx = SystemProgram.transfer({
        fromPubkey: owner,
        lamports: bnToNumber(amount),
        toPubkey: ata
      })
      const syncNativeIX = createSyncNativeInstruction(ata)
      instructions.push(transferIx, syncNativeIX)
    }
  }
Example #11
Source File: associatedToken.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * If the associated token account does not exist for this mint, add instruction to create the token account.If ATA exists, do nothing.
   * @static
   * @param {TransactionInstruction[]} instructions
   * @param {Provider} provider
   * @param {PublicKey} owner
   * @param {PublicKey} mint
   * @returns {Promise<PublicKey>} returns the public key of the token account
   * @memberof AssociatedToken
   */
  static async withCreate(
    instructions: TransactionInstruction[],
    provider: AnchorProvider,
    owner: PublicKey,
    mint: PublicKey
  ): Promise<PublicKey> {
    const tokenAddress = this.derive(mint, owner)
    const tokenAccount = await this.load(provider.connection, mint, owner)

    if (!tokenAccount) {
      const ix = createAssociatedTokenAccountInstruction(provider.wallet.publicKey, tokenAddress, owner, mint)
      instructions.push(ix)
    }
    return tokenAddress
  }
Example #12
Source File: retryTxSender.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
public constructor(
		provider: AnchorProvider,
		timeout?: number,
		retrySleep?: number,
		additionalConnections = new Array<Connection>()
	) {
		this.provider = provider;
		this.timeout = timeout ?? DEFAULT_TIMEOUT;
		this.retrySleep = retrySleep ?? DEFAULT_RETRY;
		this.additionalConnections = additionalConnections;
	}
Example #13
Source File: switchboardClient.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
async function getSwitchboardProgram(
	env: DriftEnv,
	connection: Connection
): Promise<Program> {
	const DEFAULT_KEYPAIR = Keypair.fromSeed(new Uint8Array(32).fill(1));
	const programId = getSwitchboardPid(env);
	const wallet = new Wallet(DEFAULT_KEYPAIR);
	const provider = new AnchorProvider(connection, wallet, {});

	return new Program(switchboardV2Idl as Idl, programId, provider);
}
Example #14
Source File: mockUSDCFaucet.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
public constructor(
		connection: Connection,
		wallet: IWallet,
		programId: PublicKey,
		opts?: ConfirmOptions
	) {
		this.connection = connection;
		this.wallet = wallet;
		this.opts = opts || AnchorProvider.defaultOptions();
		const provider = new AnchorProvider(connection, wallet, this.opts);
		this.provider = provider;
		this.program = new Program(mockUSDCFaucetIDL as Idl, programId, provider);
	}
Example #15
Source File: utils.ts    From quarry with GNU Affero General Public License v3.0 6 votes vote down vote up
initATA = async (
  token: Token,
  owner: Signer,
  mint?: { minter: Signer; mintAmount: number }
): Promise<PublicKey> => {
  const account = await SPLToken.getAssociatedTokenAddress(
    ASSOCIATED_TOKEN_PROGRAM_ID,
    TOKEN_PROGRAM_ID,
    token.mintAccount,
    owner.publicKey
  );

  const tx = new Transaction().add(
    SPLToken.createAssociatedTokenAccountInstruction(
      ASSOCIATED_TOKEN_PROGRAM_ID,
      TOKEN_PROGRAM_ID,
      token.mintAccount,
      account,
      owner.publicKey,
      AnchorProvider.env().wallet.publicKey
    )
  );

  if (mint) {
    tx.add(
      SPLToken.createMintToInstruction(
        TOKEN_PROGRAM_ID,
        token.mintAccount,
        account,
        mint.minter.publicKey,
        [],
        mint.mintAmount
      )
    );
  }
  // mint tokens
  await AnchorProvider.env().sendAndConfirm(
    tx,
    mint ? [mint.minter] : undefined,
    {
      commitment: "confirmed",
    }
  );
  return account;
}
Example #16
Source File: webSocketAccountSubscriber.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
async subscribe(onChange: (data: T) => void): Promise<void> {
		if (this.listenerId) {
			return;
		}

		this.onChange = onChange;
		await this.fetch();

		this.listenerId = this.program.provider.connection.onAccountChange(
			this.accountPublicKey,
			(accountInfo, context) => {
				this.handleRpcResponse(context, accountInfo);
			},
			(this.program.provider as AnchorProvider).opts.commitment
		);
	}
Example #17
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
export function getPollingClearingHouseConfig(
	connection: Connection,
	wallet: IWallet,
	programID: PublicKey,
	accountLoader: BulkAccountLoader,
	opts: ConfirmOptions = AnchorProvider.defaultOptions(),
	txSenderConfig?: TxSenderConfig
): PollingClearingHouseConfiguration {
	return {
		type: 'polling',
		connection,
		wallet,
		programID,
		accountLoader,
		opts,
		txSenderConfig,
	};
}
Example #18
Source File: admin.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
public static from(
		connection: Connection,
		wallet: IWallet,
		clearingHouseProgramId: PublicKey,
		opts: ConfirmOptions = AnchorProvider.defaultOptions()
	): Admin {
		const config = getWebSocketClearingHouseConfig(
			connection,
			wallet,
			clearingHouseProgramId,
			opts
		);
		return getAdmin(config);
	}
Example #19
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
export function getWebSocketClearingHouseConfig(
	connection: Connection,
	wallet: IWallet,
	programID: PublicKey,
	opts: ConfirmOptions = AnchorProvider.defaultOptions(),
	txSenderConfig?: TxSenderConfig
): WebSocketClearingHouseConfiguration {
	return {
		type: 'websocket',
		connection,
		wallet,
		programID,
		opts,
		txSenderConfig,
	};
}
Example #20
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
/**
	 * @deprecated You should use the getClearingHouse factory method instead
	 * @param connection
	 * @param wallet
	 * @param clearingHouseProgramId
	 * @param opts
	 * @returns
	 */
	public static from(
		connection: Connection,
		wallet: IWallet,
		clearingHouseProgramId: PublicKey,
		opts: ConfirmOptions = AnchorProvider.defaultOptions()
	): ClearingHouse {
		const config = getWebSocketClearingHouseConfig(
			connection,
			wallet,
			clearingHouseProgramId,
			opts
		);
		return getClearingHouse(config);
	}
Example #21
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
/**
	 * Update the wallet to use for clearing house transactions and linked user account
	 * @param newWallet
	 */
	public updateWallet(newWallet: IWallet): void {
		const newProvider = new AnchorProvider(
			this.connection,
			newWallet,
			this.opts
		);
		const newProgram = new Program(
			clearingHouseIDL as Idl,
			this.program.programId,
			newProvider
		);

		// Update provider for txSender with new wallet details
		this.txSender.provider = newProvider;

		this.wallet = newWallet;
		this.provider = newProvider;
		this.program = newProgram;
		this.userAccountPublicKey = undefined;
		this.userAccount = undefined;
		this.userOrdersAccountPublicKey = undefined;
		this.userOrdersExist = undefined;
	}
Example #22
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
provider: AnchorProvider;
Example #23
Source File: workspace.ts    From arrow with GNU Affero General Public License v3.0 5 votes vote down vote up
anchorProvider = AnchorProvider.env()
Example #24
Source File: client.spec.ts    From jet-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
describe("JetClient", () => {
  let client: JetClient

  beforeAll(async () => {
    const wallet = Keypair.generate()
    const provider = new AnchorProvider(new Connection(clusterApiUrl("devnet")), new NodeWallet(wallet), {})
    client = await JetClient.connect(provider, true)
  })

  describe("can calculate derived account addresses", () => {
    test("using buffer seeds", async () => {
      const derived = await findDerivedAccount(client.program.programId, Buffer.from("test"))
      expect(derived.toBytes()).toHaveLength(32)
    })

    test("using string seeds", async () => {
      const derived = await findDerivedAccount(client.program.programId, "test")
      expect(derived.toBytes()).toHaveLength(32)
    })

    test("using public key seeds", async () => {
      const derived = await findDerivedAccount(
        client.program.programId,
        new PublicKey("9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin")
      )
      expect(derived.toBytes()).toHaveLength(32)
    })

    test("using keypair seeds", async () => {
      const derived = await findDerivedAccount(client.program.programId, Keypair.generate())
      expect(derived.toBytes()).toHaveLength(32)
    })
  })

  test("can fetch all markets", async () => {
    const markets = await JetMarket.allMarkets(client)
    expect(markets.length).toBeGreaterThan(0)
  })

  test("can fetch all obligations using filter", async () => {
    const ownerFilter: MemcmpFilter = {
      memcmp: {
        bytes: new PublicKey("Ayr9Kuhw32F4VB5JhqX3C6dfWwHrsKzBoyEGhjDvXtn2").toBase58(),
        // The 'owner' field
        offset: 8 + 4 + 4 + 32
      }
    }
    const obligations = await client.allObligations([ownerFilter])
    expect(obligations.length).toBeGreaterThan(0)
  })

  test("can fetch all reserves of a market", async () => {
    const market = await JetMarket.load(client, JET_MARKET_ADDRESS_DEVNET)
    const reserves = await JetReserve.loadMultiple(client, market)
    expect(reserves.length).toBeGreaterThan(0)

    const firstReserve = reserves[0]
    expect(firstReserve.data.utilizationRate).toBeGreaterThan(0)
  })
})
Example #25
Source File: webSocketAccountSubscriber.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
async fetch(): Promise<void> {
		const rpcResponse =
			await this.program.provider.connection.getAccountInfoAndContext(
				this.accountPublicKey,
				(this.program.provider as AnchorProvider).opts.commitment
			);
		this.handleRpcResponse(rpcResponse.context, rpcResponse?.value);
	}
Example #26
Source File: clearingHouse.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
export function getAdmin(config: ClearingHouseConfig): Admin {
	const provider = new AnchorProvider(
		config.connection,
		config.wallet,
		config.opts
	);
	const program = new Program(
		clearingHouseIDL as Idl,
		config.programID,
		provider
	);
	let accountSubscriber: ClearingHouseAccountSubscriber;
	if (config.type === 'websocket') {
		accountSubscriber = new WebSocketClearingHouseAccountSubscriber(program);
	} else if (config.type === 'polling') {
		accountSubscriber = new PollingClearingHouseAccountSubscriber(
			program,
			(config as PollingClearingHouseConfiguration).accountLoader
		);
	}

	let txSender: TxSender;
	if (config.txSenderConfig?.type === 'retry') {
		const txSenderConfig = config.txSenderConfig as RetryTxSenderConfig;
		txSender = new RetryTxSender(
			provider,
			txSenderConfig.timeout,
			txSenderConfig.retrySleep,
			txSenderConfig.additionalConnections
		);
	} else {
		txSender = new DefaultTxSender(provider);
	}
	return new Admin(
		config.connection,
		config.wallet,
		program,
		accountSubscriber,
		txSender,
		config.opts
	);
}
Example #27
Source File: user_position.ts    From jet-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
async function getBitcoinPosition() {
  // This users positions will be fetched
  const userAddress = new PublicKey("6XEn2q37nqsYQB5R79nueGi6n3uhgjiDwxoJeAVzWvaS")
  //transaction commitment options
  const options = AnchorProvider.defaultOptions()
  const connection = new Connection("https://api.devnet.solana.com", options)
  // A wallet is not required in this example
  const wallet = undefined as any as Wallet
  const provider = new AnchorProvider(connection, wallet, options)

  // Load the Anchor IDL from RPC
  const client = await JetClient.connect(provider, true)

  // Load devnet market data from RPC
  const market = await JetMarket.load(client, JET_MARKET_ADDRESS_DEVNET)
  // Load all reserves
  const reserves = await JetReserve.loadMultiple(client, market)
  // Load user data
  const user = await JetUser.load(client, market, reserves, userAddress)
  // create obligation
  const obligation = JetObligation.create(
    market,
    user,
    reserves.map(reserve => reserve.data)
  )

  // All these can be condensed to
  const userObligation = await JetObligation.load(client, JET_MARKET_ADDRESS_DEVNET, reserves, userAddress)

  // Locate the bitcoin position and log some information
  const bitcoinMint = new PublicKey("5ym2kCTCcqCHutbQXnPdsGAGFMEVQBQzTQ1CPun9W5A5")
  // Get btc position by filtering out token mint address
  const bitcoinPosition = obligation.positions.find(position => position.reserve.tokenMint.equals(bitcoinMint))
  if (bitcoinPosition) {
    const position: CollateralizedPosition = {
      mint: bitcoinPosition.reserve.tokenMint.toBase58(),
      deposited: bitcoinPosition.collateralBalance.tokens,
      borrowed: bitcoinPosition.loanBalance.tokens,
      borrowApr: bitcoinPosition.reserve.borrowApr,
      depositApy: bitcoinPosition.reserve.depositApy,
      collateralRatio: userObligation.collateralRatio
    }

    console.log(position)
    /**
   {
      mint: '5ym2kCTCcqCHutbQXnPdsGAGFMEVQBQzTQ1CPun9W5A5',
      deposited: 2.000009,
      borrowed: 0.500125,
      borrowApr: 0.00638284671447752,
      depositApy: 0.00012888670151030092,
      collateralRatio: 2.2676541147165414
    }
    */
  }
}
Example #28
Source File: retryTxSender.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
provider: AnchorProvider;
Example #29
Source File: defaultTxSender.ts    From protocol-v1 with Apache License 2.0 5 votes vote down vote up
provider: AnchorProvider;