@solana/spl-token#TOKEN_PROGRAM_ID TypeScript Examples

The following examples show how to use @solana/spl-token#TOKEN_PROGRAM_ID. 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: utils.ts    From metaplex with Apache License 2.0 7 votes vote down vote up
getAtaForMint = async (
  mint: anchor.web3.PublicKey,
  buyer: anchor.web3.PublicKey,
): Promise<[anchor.web3.PublicKey, number]> => {
  return await anchor.web3.PublicKey.findProgramAddress(
    [buyer.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
    SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID,
  );
}
Example #2
Source File: MarginWeb3.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
/**
   * Deposits a given amount of collateral into the Margin account. Raw implementation of the instruction.
   * @param tokenAccount The user's token account where tokens will be subtracted from.
   * @param vault The state vault where tokens will be deposited into.
   * @param amount The amount of tokens to deposit, in native quantity. (ex: lamports for SOL, satoshis for BTC)
   * @param repayOnly If true, will only deposit up to the amount borrowed. If true, amount parameter can be set to an arbitrarily large number to ensure that any outstanding borrow is fully repaid.
   */
  async depositRaw(
    tokenAccount: PublicKey,
    vault: PublicKey,
    amount: BN,
    repayOnly: boolean,
  ) {
    return await this.program.rpc.deposit(repayOnly, amount, {
      accounts: {
        state: this.state.pubkey,
        stateSigner: this.state.signer,
        cache: this.state.cache.pubkey,
        authority: this.wallet.publicKey,
        margin: this.pubkey,
        tokenAccount,
        vault,
        tokenProgram: TOKEN_PROGRAM_ID,
      },
    });
  }
Example #3
Source File: mint.ts    From candy-machine-v2 with MIT License 6 votes vote down vote up
getAtaForMint = async (
  mint: anchor.web3.PublicKey,
  buyer: anchor.web3.PublicKey
): Promise<[anchor.web3.PublicKey, number]> => {
  return await anchor.web3.PublicKey.findProgramAddress(
    [buyer.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],
    SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID
  );
}
Example #4
Source File: cli.ts    From protocol-v1 with Apache License 2.0 6 votes vote down vote up
commandWithDefaultOption('deposit')
	.argument('<amount>', 'The amount to deposit')
	.action(async (amount, options: OptionValues) => {
		await wrapActionInUserSubscribeUnsubscribe(
			options,
			async (user: ClearingHouseUser) => {
				log.info(`amount: ${amount}`);
				amount = new BN(amount);

				const associatedTokenPublicKey = await Token.getAssociatedTokenAddress(
					ASSOCIATED_TOKEN_PROGRAM_ID,
					TOKEN_PROGRAM_ID,
					user.clearingHouse.getStateAccount().collateralMint,
					user.authority
				);

				await user.clearingHouse.depositCollateral(
					amount,
					associatedTokenPublicKey
				);
			}
		);
	});
Example #5
Source File: accountParser.ts    From jet-engine with GNU Affero General Public License v3.0 6 votes vote down vote up
parseTokenAccount = (info: AccountInfo<Buffer>, address: PublicKey): Account => {
  if (!info) throw new TokenAccountNotFoundError()
  if (!info.owner.equals(TOKEN_PROGRAM_ID)) throw new TokenInvalidAccountOwnerError()
  if (info.data.length != ACCOUNT_SIZE) throw new TokenInvalidAccountSizeError()

  const rawAccount = AccountLayout.decode(info.data)

  return {
    address,
    mint: rawAccount.mint,
    owner: rawAccount.owner,
    amount: rawAccount.amount,
    delegate: rawAccount.delegateOption ? rawAccount.delegate : null,
    delegatedAmount: rawAccount.delegatedAmount,
    isInitialized: rawAccount.state !== AccountState.Uninitialized,
    isFrozen: rawAccount.state === AccountState.Frozen,
    isNative: !!rawAccount.isNativeOption,
    rentExemptReserve: rawAccount.isNativeOption ? rawAccount.isNative : null,
    closeAuthority: rawAccount.closeAuthorityOption ? rawAccount.closeAuthority : null
  }
}
Example #6
Source File: token-program.ts    From kin-node with MIT License 6 votes vote down vote up
/**
     * Decode a initialize account token instruction and retrieve the instruction params.
     */
    static decodeInitializeAccount(instruction: TransactionInstruction): InitializeAccountParams {
        this.checkProgramId(instruction.programId, TOKEN_PROGRAM_ID);
        this.checkKeyLength(instruction.keys, 4);
        this.checkData(instruction.data, 1, Command.InitializeAccount);

        return {
            account: instruction.keys[0].pubkey,
            mint: instruction.keys[1].pubkey,
            owner: instruction.keys[2].pubkey,
        };
    }
Example #7
Source File: candy-machine.ts    From metaplex with Apache License 2.0 6 votes vote down vote up
createAssociatedTokenAccountInstruction = (
  associatedTokenAddress: anchor.web3.PublicKey,
  payer: anchor.web3.PublicKey,
  walletAddress: anchor.web3.PublicKey,
  splTokenMintAddress: anchor.web3.PublicKey,
) => {
  const keys = [
    { pubkey: payer, isSigner: true, isWritable: true },
    { pubkey: associatedTokenAddress, isSigner: false, isWritable: true },
    { pubkey: walletAddress, isSigner: false, isWritable: false },
    { pubkey: splTokenMintAddress, isSigner: false, isWritable: false },
    {
      pubkey: anchor.web3.SystemProgram.programId,
      isSigner: false,
      isWritable: false,
    },
    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },
    {
      pubkey: anchor.web3.SYSVAR_RENT_PUBKEY,
      isSigner: false,
      isWritable: false,
    },
  ];
  return new anchor.web3.TransactionInstruction({
    keys,
    programId: SPL_ASSOCIATED_TOKEN_ACCOUNT_PROGRAM_ID,
    data: Buffer.from([]),
  });
}
Example #8
Source File: initializeMarket.ts    From psyoptions with Apache License 2.0 6 votes vote down vote up
getOrAddAssociatedTokenAccountTx = async (
  associatedAddress: PublicKey,
  token: Token,
  payer: PublicKey,
  owner: PublicKey = FEE_OWNER_KEY,
) => {
  // This is the optimum logic, considering TX fee, client-side computation,
  // RPC roundtrips and guaranteed idempotent.
  // Sadly we can't do this atomically;
  try {
    await token.getAccountInfo(associatedAddress);
    return null;
  } catch (err) {
    // INVALID_ACCOUNT_OWNER can be possible if the associatedAddress has
    // already been received some lamports (= became system accounts).
    // Assuming program derived addressing is safe, this is the only case
    // for the INVALID_ACCOUNT_OWNER in this code-path
    if (
      err.message === 'Failed to find account' ||
      err.message === 'Invalid account owner'
    ) {
      // as this isn't atomic, it's possible others can create associated
      // accounts meanwhile
      return Token.createAssociatedTokenAccountInstruction(
        ASSOCIATED_TOKEN_PROGRAM_ID,
        TOKEN_PROGRAM_ID,
        token.publicKey,
        associatedAddress,
        owner,
        payer,
      );
    } else {
      throw err;
    }
  }
}
Example #9
Source File: createLendingMarket.ts    From port-sdk with MIT License 6 votes vote down vote up
initLendingMarketInstruction = (
  owner: PublicKey,
  quoteCurrency: Buffer,
  lendingMarket: PublicKey,
  lendingProgramId: PublicKey = PORT_LENDING
): TransactionInstruction => {
  const data = Buffer.alloc(DataLayout.span);
  DataLayout.encode(
    {
      instruction: LendingInstruction.InitLendingMarket,
      owner,
      quoteCurrency,
    },
    data
  );

  const keys = [
    getAccess(lendingMarket, AccessType.WRITE),
    getAccess(SYSVAR_RENT_PUBKEY, AccessType.READ),
    getAccess(TOKEN_PROGRAM_ID, AccessType.READ),
  ];

  return new TransactionInstruction({
    keys,
    programId: lendingProgramId,
    data,
  });
}
Example #10
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: [] };
}