@project-serum/anchor#BN TypeScript Examples

The following examples show how to use @project-serum/anchor#BN. 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: State.ts    From zo-client with Apache License 2.0 7 votes vote down vote up
/**
   * Called by the keepers regularly to cache the oracle prices.
   * @param mockPrices Only used for testing purposes. An array of user-set prices.
   */
  async cacheOracle(mockPrices?: BN[]) {
    const oracles = this.cache.data.oracles;
    return await this.program.rpc.cacheOracle(
      oracles.map((x) => x.symbol),
      mockPrices ?? null,
      {
        accounts: {
          signer: this.wallet.publicKey,
          cache: this.cache.pubkey,
        },
        remainingAccounts: oracles
          .flatMap((x) => x.sources)
          .map((x) => ({
            isSigner: false,
            isWritable: false,
            pubkey: x.key,
          })),
      },
    );
  }
Example #2
Source File: util.ts    From jet-engine with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
   * TODO:
   * @param {Uint8Array} b
   * @param {number} [offset]
   * @returns {BN}
   * @memberof SignedNumberField
   */
  decode(b: Uint8Array, offset?: number): BN {
    const start = offset == undefined ? 0 : offset
    const data = b.slice(start, start + this.span)
    return new BN(data, undefined, "le").fromTwos(this.span * 8)
  }
Example #3
Source File: units.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
// price number is bigUSD / bigAsset
// lots is USD lots / Asset lots
export function priceNumberToLots(
  price: number,
  baseDecimals: number,
  baseLotSize: BN,
  quoteDecimals: number,
  quoteLotSize: BN,
): BN {
  return new BN(
    Math.round(
      (price * Math.pow(10, quoteDecimals) * baseLotSize.toNumber()) /
        (Math.pow(10, baseDecimals) * quoteLotSize.toNumber()),
    ),
  );
}
Example #4
Source File: sdk.ts    From tribeca with GNU Affero General Public License v3.0 6 votes vote down vote up
async createSimpleElectorate({
    proposalThreshold,
    governor,
    govTokenMint,
    baseKP = Keypair.generate(),
  }: {
    proposalThreshold: BN;
    baseKP?: Keypair;
    governor: PublicKey;
    govTokenMint: PublicKey;
  }): Promise<PendingElectorate> {
    const [electorate, bump] = await findSimpleElectorateAddress(
      baseKP.publicKey
    );
    return {
      electorate,
      tx: new TransactionEnvelope(
        this.provider,
        [
          this.programs.SimpleVoter.instruction.initializeElectorate(
            bump,
            proposalThreshold,
            {
              accounts: {
                base: baseKP.publicKey,
                governor,
                electorate,
                govTokenMint,
                payer: this.provider.wallet.publicKey,
                systemProgram: SystemProgram.programId,
              },
            }
          ),
        ],
        [baseKP]
      ),
    };
  }
Example #5
Source File: admin.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
public async initializeMarket(
		marketIndex: BN,
		priceOracle: PublicKey,
		baseAssetReserve: BN,
		quoteAssetReserve: BN,
		periodicity: BN,
		pegMultiplier: BN = PEG_PRECISION,
		oracleSource: OracleSource = OracleSource.PYTH,
		marginRatioInitial = 2000,
		marginRatioPartial = 625,
		marginRatioMaintenance = 500
	): Promise<TransactionSignature> {
		if (this.getMarketsAccount().markets[marketIndex.toNumber()].initialized) {
			throw Error(`MarketIndex ${marketIndex.toNumber()} already initialized`);
		}

		const initializeMarketTx = await this.program.transaction.initializeMarket(
			marketIndex,
			baseAssetReserve,
			quoteAssetReserve,
			periodicity,
			pegMultiplier,
			oracleSource,
			marginRatioInitial,
			marginRatioPartial,
			marginRatioMaintenance,
			{
				accounts: {
					state: await this.getStatePublicKey(),
					admin: this.wallet.publicKey,
					oracle: priceOracle,
					markets: this.getStateAccount().markets,
				},
			}
		);
		return await this.txSender.send(initializeMarketTx, [], this.opts);
	}
Example #6
Source File: accountParser.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
   * TODO:
   * @param {Uint8Array} b
   * @param {number} [offset]
   * @returns {BN}
   * @memberof NumberField
   */
  decode(b: Uint8Array, offset?: number): BN {
    const start = offset ?? 0
    const data = b.slice(start, start + this.span)
    return new BN(data, undefined, "le")
  }
Example #7
Source File: types.ts    From metaplex with Apache License 2.0 6 votes vote down vote up
constructor(args: {
    name: string;
    symbol: string;
    uri: string;
    sellerFeeBasisPoints: number;
    creators: Creator[] | null;
    maxNumberOfLines: BN;
    isMutable: boolean;
    maxSupply: BN;
    retainAuthority: boolean;
  }) {
    this.name = args.name;
    this.symbol = args.symbol;
    this.uri = args.uri;
    this.sellerFeeBasisPoints = args.sellerFeeBasisPoints;
    this.creators = args.creators;
    this.maxNumberOfLines = args.maxNumberOfLines;
    this.isMutable = args.isMutable;
    this.maxSupply = args.maxSupply;
    this.retainAuthority = args.retainAuthority;
  }
Example #8
Source File: helpers.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
exerciseOptionTx = async (
  program: anchor.Program<PsyAmerican>,
  size: anchor.BN,
  optionMarket: PublicKey,
  optionTokenKey: PublicKey,
  exerciser: Keypair,
  optionAuthority: Keypair,
  exerciserOptionTokenSrc: PublicKey,
  underlyingAssetPoolKey: PublicKey,
  underlyingAssetDestKey: PublicKey,
  quoteAssetPoolKey: PublicKey,
  quoteAssetSrcKey: PublicKey,
  remainingAccounts: AccountMeta[],
  opts: { feeOwner?: PublicKey } = {}
) => {
  await program.rpc.exerciseOption(size, {
    accounts: {
      userAuthority: exerciser.publicKey,
      optionAuthority: optionAuthority.publicKey,
      optionMarket,
      optionMint: optionTokenKey,
      exerciserOptionTokenSrc: exerciserOptionTokenSrc,
      underlyingAssetPool: underlyingAssetPoolKey,
      underlyingAssetDest: underlyingAssetDestKey,
      quoteAssetPool: quoteAssetPoolKey,
      quoteAssetSrc: quoteAssetSrcKey,
      feeOwner: opts.feeOwner || FEE_OWNER_KEY,
      tokenProgram: TOKEN_PROGRAM_ID,
      systemProgram: SystemProgram.programId,
      clock: SYSVAR_CLOCK_PUBKEY,
    },
    remainingAccounts: remainingAccounts,
    signers: [exerciser],
  });
}