-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation
Description
If you want to send Wsol, use the updated route.ts in api/tx/create.
import { NETWORK } from "@/utils/endpoints";
import { DEFAULT_WALLET } from "@/utils/globals";
import {
createAssociatedTokenAccountInstruction,
createTransferCheckedInstruction,
getAccount,
getAssociatedTokenAddress,
getMint,
NATIVE_MINT,
} from "@solana/spl-token";
import {
Connection,
LAMPORTS_PER_SOL,
PublicKey,
SystemProgram,
Transaction,
} from "@solana/web3.js";
import { NextRequest, NextResponse } from "next/server";
export type TxCreateData = {
tx: string;
};
export type Input = {
payerAddress: string;
receiverAddress?: string;
amount?: number;
type: "sol" | "token" | "wsol";
tokenAddress?: string;
};
export async function POST(req: NextRequest, res: NextResponse<TxCreateData>) {
const body = await req.json();
const {
payerAddress,
receiverAddress = DEFAULT_WALLET,
amount = 1,
type = "sol",
tokenAddress,
} = body as Input;
const connection = new Connection(NETWORK);
const payer = new PublicKey(payerAddress);
const receiver = new PublicKey(receiverAddress);
let transaction = new Transaction();
if (type === "token" || type === "wsol") {
const splToken = type === "wsol" ? NATIVE_MINT : new PublicKey(tokenAddress!);
const mint = await getMint(connection, splToken);
const payerAta = await getAssociatedTokenAddress(splToken, payer);
const receiverAta = await getAssociatedTokenAddress(splToken, receiver);
try {
await getAccount(connection, receiverAta);
} catch (e) {
// Create ATA for receiver if it doesn't exist
transaction.add(
createAssociatedTokenAccountInstruction(
payer, // Payer of the transaction
receiverAta, // New Associated Token Account
receiver, // Owner of the account
splToken // Mint of WSOL or token
)
);
}
transaction.add(
createTransferCheckedInstruction(
payerAta, // From (payer's ATA)
splToken, // Mint (WSOL or token)
receiverAta, // To (receiver's ATA)
payer, // Authority (payer's public key)
amount * 10 ** mint.decimals, // Amount in minimal units
mint.decimals // Decimals for WSOL or token
)
);
}
if (type === "sol") {
// Add a transfer instruction for SOL
transaction.add(
SystemProgram.transfer({
fromPubkey: payer,
toPubkey: receiver,
lamports: amount * LAMPORTS_PER_SOL,
})
);
}
const blockHash = (await connection.getLatestBlockhash("finalized")).blockhash;
transaction.feePayer = payer;
transaction.recentBlockhash = blockHash;
const serializedTransaction = transaction.serialize({
requireAllSignatures: false,
verifySignatures: true,
});
const transactionBase64 = serializedTransaction.toString("base64");
return NextResponse.json(
{
tx: transactionBase64,
},
{ status: 200 }
);
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation