0x0x230x

Untitled

Jan 21st, 2025
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. interface TransactionParams {
  2. senderAddress: string;
  3. recipientAddress: string;
  4. tokenMint?: string;
  5. amount: bigint;
  6. isNative: boolean;
  7. }
  8.  
  9. async preparePrivyTransaction(params: TransactionParams) {
  10. try {
  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.  
  27. if (!senderTokenAccount) {
  28. throw new Error('Sender token account not found');
  29. }
  30.  
  31. const { tokenAccount: recipientTokenAccount, shouldCreate } =
  32. await this.getOrCreateTokenAccount(
  33. params.recipientAddress,
  34. params.tokenMint,
  35. );
  36.  
  37. if (shouldCreate) {
  38. instructions.push(
  39. createAssociatedTokenAccountInstruction(
  40. new PublicKey(params.senderAddress),
  41. recipientTokenAccount,
  42. new PublicKey(params.recipientAddress),
  43. new PublicKey(params.tokenMint),
  44. ),
  45. );
  46. }
  47.  
  48. console.log('amount', params.amount);
  49.  
  50. instructions.push(
  51. createTransferInstruction(
  52. senderTokenAccount,
  53. recipientTokenAccount,
  54. new PublicKey(params.senderAddress),
  55. params.amount,
  56. ),
  57. );
  58. }
  59.  
  60. const { blockhash } = await this.connection.getLatestBlockhash({
  61. commitment: 'recent',
  62. });
  63.  
  64. const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
  65. microLamports: 50000,
  66. });
  67.  
  68. const increasedUnitsIx = ComputeBudgetProgram.setComputeUnitLimit({
  69. units: 20000,
  70. });
  71.  
  72. const allInstructions = [
  73. priorityFeeIx,
  74. increasedUnitsIx,
  75. ...instructions,
  76. ];
  77.  
  78. const messageV0 = new TransactionMessage({
  79. payerKey: new PublicKey(params.senderAddress),
  80. recentBlockhash: blockhash,
  81. instructions: allInstructions,
  82. }).compileToV0Message();
  83.  
  84. return new VersionedTransaction(messageV0);
  85. } catch (error) {
  86. console.error('Error in preparePrivyTransaction:', error);
  87. throw error;
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment