/
createAssociatedTokenAccount.ts
45 lines (41 loc) · 1.75 KB
/
createAssociatedTokenAccount.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { ConfirmOptions, Connection, PublicKey, Signer } from '@solana/web3.js';
import { sendAndConfirmTransaction, Transaction } from '@solana/web3.js';
import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID } from '../constants.js';
import { createAssociatedTokenAccountInstruction } from '../instructions/associatedTokenAccount.js';
import { getAssociatedTokenAddressSync } from '../state/mint.js';
/**
* Create and initialize a new associated token account
*
* @param connection Connection to use
* @param payer Payer of the transaction and initialization fees
* @param mint Mint for the account
* @param owner Owner of the new account
* @param confirmOptions Options for confirming the transaction
* @param programId SPL Token program account
* @param associatedTokenProgramId SPL Associated Token program account
*
* @return Address of the new associated token account
*/
export async function createAssociatedTokenAccount(
connection: Connection,
payer: Signer,
mint: PublicKey,
owner: PublicKey,
confirmOptions?: ConfirmOptions,
programId = TOKEN_PROGRAM_ID,
associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID
): Promise<PublicKey> {
const associatedToken = getAssociatedTokenAddressSync(mint, owner, false, programId, associatedTokenProgramId);
const transaction = new Transaction().add(
createAssociatedTokenAccountInstruction(
payer.publicKey,
associatedToken,
owner,
mint,
programId,
associatedTokenProgramId
)
);
await sendAndConfirmTransaction(connection, transaction, [payer], confirmOptions);
return associatedToken;
}