Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface TransactionParams {
- senderAddress: string;
- recipientAddress: string;
- tokenMint?: string;
- amount: bigint;
- isNative: boolean;
- }
- async preparePrivyTransaction(params: TransactionParams) {
- try {
- const instructions: TransactionInstruction[] = [];
- if (params.isNative) {
- instructions.push(
- SystemProgram.transfer({
- fromPubkey: new PublicKey(params.senderAddress),
- toPubkey: new PublicKey(params.recipientAddress),
- lamports: params.amount,
- }),
- );
- } else if (params.tokenMint) {
- const senderTokenAccount = await this.getTokenAccount(
- params.senderAddress,
- params.tokenMint,
- );
- if (!senderTokenAccount) {
- throw new Error('Sender token account not found');
- }
- const { tokenAccount: recipientTokenAccount, shouldCreate } =
- await this.getOrCreateTokenAccount(
- params.recipientAddress,
- params.tokenMint,
- );
- if (shouldCreate) {
- instructions.push(
- createAssociatedTokenAccountInstruction(
- new PublicKey(params.senderAddress),
- recipientTokenAccount,
- new PublicKey(params.recipientAddress),
- new PublicKey(params.tokenMint),
- ),
- );
- }
- console.log('amount', params.amount);
- instructions.push(
- createTransferInstruction(
- senderTokenAccount,
- recipientTokenAccount,
- new PublicKey(params.senderAddress),
- params.amount,
- ),
- );
- }
- const { blockhash } = await this.connection.getLatestBlockhash({
- commitment: 'recent',
- });
- const priorityFeeIx = ComputeBudgetProgram.setComputeUnitPrice({
- microLamports: 50000,
- });
- const increasedUnitsIx = ComputeBudgetProgram.setComputeUnitLimit({
- units: 20000,
- });
- const allInstructions = [
- priorityFeeIx,
- increasedUnitsIx,
- ...instructions,
- ];
- const messageV0 = new TransactionMessage({
- payerKey: new PublicKey(params.senderAddress),
- recentBlockhash: blockhash,
- instructions: allInstructions,
- }).compileToV0Message();
- return new VersionedTransaction(messageV0);
- } catch (error) {
- console.error('Error in preparePrivyTransaction:', error);
- throw error;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment