Skip to content

Instantly share code, notes, and snippets.

@thearyanag
Created May 17, 2023 06:50
Show Gist options
  • Select an option

  • Save thearyanag/f423a2bb581245c593109ded344f8713 to your computer and use it in GitHub Desktop.

Select an option

Save thearyanag/f423a2bb581245c593109ded344f8713 to your computer and use it in GitHub Desktop.
A web3.js function to transfer NFT from one wallet to another
const {
Connection,
PublicKey,
Keypair,
Transaction,
sendAndConfirmTransaction,
} = require("@solana/web3.js");
const splToken = require("@solana/spl-token");
const base58 = require("bs58");
let connection = new Connection("https://api.mainnet-beta.solana.com");
let privateKeyString = process.env.PRIVATE_KEY;
console.log(privateKeyString);
let secret = new Uint8Array(base58.decode(privateKeyString));
let senderWallet = Keypair.fromSecretKey(secret);
let tokenMintAddress = new PublicKey("BFqBQdT1MdE8fdfHTW3YmTYFaaEdacjJYsgVL5LTswz");
let recipientWallet = new PublicKey(
"8MdXvWgNou9jRVturbfnt3egf1aP9p1AjL8wiJavti7F"
);
/**
* To transfer a token from one wallet to another
* @returns {Promise<{signature: string}>}
*/
async function transfer() {
let my_token_account = await splToken.getOrCreateAssociatedTokenAccount(
connection,
senderWallet,
tokenMintAddress,
senderWallet.publicKey,
false,
'finalized',
null,
splToken.TOKEN_PROGRAM_ID,
splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
)
let reciver_token_account = await splToken.getOrCreateAssociatedTokenAccount(
connection,
senderWallet,
tokenMintAddress,
recipientWallet,
false,
'finalized',
null,
splToken.TOKEN_PROGRAM_ID,
splToken.ASSOCIATED_TOKEN_PROGRAM_ID,
);
console.log('My token account public address: ' + my_token_account.address.toBase58());
console.log('Reciver token account public address: ' + reciver_token_account.address.toBase58());
try {
let tx_hash = await transfer_tokens(
senderWallet,
connection,
1,
reciver_token_account,
my_token_account,
)
return tx_hash
} catch (error) {
console.log(error)
}
console.log('Done!');
}
async function transfer_tokens(wallet, connection, amount, reciver_token_account, from_token_account) {
//if trx takes more when 60 sec to complete you will receive error here
const transfer_trx = await splToken.transfer(
connection,
wallet,
from_token_account.address,
reciver_token_account.address,
wallet,
amount,
[wallet],
false,
splToken.TOKEN_PROGRAM_ID,
)
console.log(transfer_trx)
return {
signature: transfer_trx,
}
}
module.exports = transfer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment