0x0x230x

Untitled

Jan 21st, 2025
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. this.connection = new Connection(
  2. `https://solana-mainnet.g.alchemy.com/v2/${env.ALCHEMY_API_KEY}`,
  3. 'confirmed',
  4. );
  5.  
  6. async preparePrivyTransaction(params: TransactionParams) {
  7. try {
  8. const { blockhash } = await this.connection.getLatestBlockhash(
  9. 'processed',
  10. );
  11. const instructions: TransactionInstruction[] = [];
  12.  
  13. if (params.isNative) {
  14. instructions.push(
  15. SystemProgram.transfer({
  16. fromPubkey: new PublicKey(params.senderAddress),
  17. toPubkey: new PublicKey(params.recipientAddress),
  18. lamports: params.amount,
  19. }),
  20. );
  21. } else if (params.tokenMint) {
  22. const senderTokenAccount = await this.getTokenAccount(
  23. params.senderAddress,
  24. params.tokenMint,
  25. );
  26. if (!senderTokenAccount) {
  27. throw new Error('Sender token account not found');
  28. }
  29.  
  30. const { tokenAccount: recipientTokenAccount, shouldCreate } =
  31. await this.getOrCreateTokenAccount(
  32. params.recipientAddress,
  33. params.tokenMint,
  34. );
  35.  
  36. if (shouldCreate) {
  37. instructions.push(
  38. createAssociatedTokenAccountInstruction(
  39. new PublicKey(params.senderAddress),
  40. recipientTokenAccount,
  41. new PublicKey(params.recipientAddress),
  42. new PublicKey(params.tokenMint),
  43. ),
  44. );
  45. }
  46.  
  47. instructions.push(
  48. createTransferInstruction(
  49. senderTokenAccount,
  50. recipientTokenAccount,
  51. new PublicKey(params.senderAddress),
  52. params.amount,
  53. ),
  54. );
  55. }
  56.  
  57. const messageV0 = new TransactionMessage({
  58. payerKey: new PublicKey(params.senderAddress),
  59. recentBlockhash: blockhash,
  60. instructions,
  61. }).compileToV0Message();
  62.  
  63. return new VersionedTransaction(messageV0);
  64. } catch (error) {
  65. console.error('Error in preparePrivyTransaction:', error);
  66. throw error;
  67. }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment