Skip to content

Commit

Permalink
feat: add send token action (#81)
Browse files Browse the repository at this point in the history
* feat: add send token action

* feat: code review fixes
  • Loading branch information
kurpav committed Dec 1, 2021
1 parent c9d5524 commit b5f9d7c
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export * from './redeemBid';
export * from './claimBid';
export * from './instantSale';
export * from './burnToken';
export * from './sendToken';
export * from './shared';
73 changes: 73 additions & 0 deletions src/actions/sendToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { PublicKey } from '@solana/web3.js';
import { ASSOCIATED_TOKEN_PROGRAM_ID, Token, TOKEN_PROGRAM_ID, u64 } from '@solana/spl-token';
import { Wallet } from '../wallet';
import { Connection } from '../Connection';
import { sendTransaction } from './transactions';
import { Transaction } from '../Transaction';
import { Account } from '../Account';
import { CreateAssociatedTokenAccount } from '../programs/shared/transactions/CreateAssociatedTokenAccount';

interface ISendTokenParams {
connection: Connection;
wallet: Wallet;
// token account address
source: PublicKey;
// destination wallet address
destination: PublicKey;
mint: PublicKey;
amount: number | u64;
}

interface ISendTokenResponse {
txId: string;
}

export const sendToken = async ({
connection,
wallet,
source,
destination,
mint,
amount,
}: ISendTokenParams): Promise<ISendTokenResponse> => {
const txs = [];
const destAta = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
mint,
destination,
);
const transactionCtorFields = {
feePayer: wallet.publicKey,
};

try {
// check if the account exists
await Account.load(connection, destAta);
} catch {
txs.push(
new CreateAssociatedTokenAccount(transactionCtorFields, {
associatedTokenAddress: destAta,
splTokenMintAddress: mint,
walletAddress: destination,
}),
);
}

txs.push(
new Transaction(transactionCtorFields).add(
Token.createTransferInstruction(
TOKEN_PROGRAM_ID,
source,
destAta,
wallet.publicKey,
[],
amount,
),
),
);

const txId = await sendTransaction({ connection, wallet, txs });

return { txId };
};

0 comments on commit b5f9d7c

Please sign in to comment.