Create associated token program accounts when sending (#134)

This commit is contained in:
Gary Wang 2021-03-08 17:58:03 +08:00 committed by GitHub
parent c8527e4fe3
commit 2260549d0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 24 deletions

View File

@ -40,7 +40,7 @@ export function useSendTransaction() {
} catch (e) {
closeSnackbar(id);
setSending(false);
console.warn(e.message);
console.warn(e);
enqueueSnackbar(e.message, { variant: 'error' });
if (onError) {
onError(e);

View File

@ -2,7 +2,6 @@ import {
PublicKey,
SystemProgram,
Transaction,
Account,
TransactionInstruction,
SYSVAR_RENT_PUBKEY,
} from '@solana/web3.js';
@ -346,7 +345,15 @@ export async function transferTokens({
memo,
});
}
throw new Error('Destination token account does not exist.');
return await createAndTransferToAccount({
connection,
owner,
sourcePublicKey,
destinationPublicKey,
amount,
memo,
mint,
});
}
// SPL tokens only.
@ -423,7 +430,14 @@ async function createAndTransferToAccount({
memo,
mint,
}) {
const newAccount = new Account();
const [
createAccountInstruction,
newAddress,
] = await createAssociatedTokenAccountIx(
owner.publicKey,
destinationPublicKey,
mint,
);
let transaction = new Transaction();
transaction.add(
assertOwner({
@ -431,35 +445,18 @@ async function createAndTransferToAccount({
owner: SystemProgram.programId,
}),
);
transaction.add(
SystemProgram.createAccount({
fromPubkey: owner.publicKey,
newAccountPubkey: newAccount.publicKey,
lamports: await connection.getMinimumBalanceForRentExemption(
ACCOUNT_LAYOUT.span,
),
space: ACCOUNT_LAYOUT.span,
programId: TOKEN_PROGRAM_ID,
}),
);
transaction.add(
initializeAccount({
account: newAccount.publicKey,
mint,
owner: destinationPublicKey,
}),
);
transaction.add(createAccountInstruction);
const transferBetweenAccountsTxn = createTransferBetweenSplTokenAccountsInstruction(
{
ownerPublicKey: owner.publicKey,
sourcePublicKey,
destinationPublicKey: newAccount.publicKey,
destinationPublicKey: newAddress,
amount,
memo,
},
);
transaction.add(transferBetweenAccountsTxn);
let signers = [newAccount];
let signers = [];
return await signAndSendTransaction(connection, transaction, owner, signers);
}