Hello I am trying to transfer a custom SPL token with the solana-wallet adapter.
However i am having trouble getting the wallet’s secret key/signing the transaction.
I’ve looked at these answers for writing the transfer code but i need to get the Singer and i have trouble figuring out how with solana-wallet adapter. These examples hardcode the secret key and since i’m using a wallet extension this is not possible.
How can you transfer SOL using the web3.js sdk for Solana?
How to transfer custom token by ‘@solana/web3.js’
according to this issue on the webadapter repo https://github.com/solana-labs/wallet-adapter/issues/120 you need to:
- Create a @solana/web3.js Transaction object and add instructions to it
- Sign the transaction with the wallet
- Send the transaction over a Connection
But i am having difficulty finding examples or documentation as to how to do step 1 and 2.
const SendTransaction: React.FC<Props> = ({ children }) => {
const { connection } = useConnection()
const { publicKey, sendTransaction } = useWallet()
const onSendSPLTransaction = useCallback(
async (toPubkey: string, amount: number) => {
if (!toPubkey || !amount) return
const toastId = toast.loading('Processing transaction...')
try {
if (!publicKey) throw new WalletNotConnectedError()
const toPublicKey = new PublicKey(toPubkey)
const mint = new PublicKey('Mint address')
const payer = '????' // how to get this Signer
const token = new Token(connection, mint, TOKEN_PROGRAM_ID, payer)
const fromTokenAccount = await token.getOrCreateAssociatedAccountInfo(publicKey)
const toTokenAccount = await token.getOrCreateAssociatedAccountInfo(toPublicKey)
const transaction = new Transaction().add(
Token.createTransferInstruction(
TOKEN_PROGRAM_ID,
fromTokenAccount.address,
toTokenAccount.address,
publicKey,
[],
0
)
)
const signature = await sendTransaction(transaction, connection)
const response = await connection.confirmTransaction(signature, 'processed')
console.log('response', response)
toast.success('Transaction sent', {
id: toastId,
})
} catch (error) {
toast.error(`Transaction failed: ${error.message}`, {
id: toastId,
})
}
},
[publicKey, sendTransaction, connection]
)
return <>{children(onSendSPLTransaction)}</>
}