0x0x230x

Untitled

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