Attempting to transfer a custom SPL token using the solana-wallet adapter is proving to be challenging due to difficulty in obtaining the wallet's secret key for signing the transaction.
Although I have reviewed resources on writing the transfer code, I am struggling to acquire the Signer with the solana-wallet adapter:
How can you transfer SOL using the web3.js sdk for Solana?
How to transfer custom token by '@solana/web3.js'
The examples available involve hardcoding the secret key which is not viable when utilizing a wallet extension.
Referring to the issue on the webadapter repository https://github.com/solana-labs/wallet-adapter/issues/120, it is advised 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
However, encountering challenges in finding relevant examples or documentation for carrying out 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)}</>
}