Create associated token program accounts when sending (#134)
This commit is contained in:
parent
c8527e4fe3
commit
2260549d0f
|
@ -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);
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue