import * as anchor from "@coral-xyz/anchor";
import { readFileSync } from "fs";
import { VersionedTransaction, Keypair, Connection } from "@solana/web3.js";
import { convertFromDecimalBN, loadKeypairFromFile } from "../utils/helpers";
/**
 * Executes a restake transaction using Solana Blinks.
 *
 * @param providerUrl - Solana RPC provider (e.g., Helius, Alchemy).
 * @param keyPairPath - Path to the keypair JSON file.
 * @param amount - Amount of SOL to restake.
 */
export async function blink_restake(
    providerUrl: string,
    keyPairPath: string,
    amount: string
) 
{
    const connection = new Connection(providerUrl, "confirmed");
    const keypair = new anchor.Wallet(
        Keypair.fromSecretKey(
            new Uint8Array(JSON.parse(readFileSync(keyPairPath).toString()))
        )
    );
    const provider = new anchor.AnchorProvider(connection, keypair, {});
    anchor.setProvider(provider);
    const balance = await connection.getBalance(provider.publicKey);
    if (new anchor.BN(balance).lt(convertFromDecimalBN(amount, 9))) {
        throw new Error(`Insufficient balance`);
    }
    try {
        const data = await getServerSignedTx(provider.publicKey, amount);
        const wallet = loadKeypairFromFile(keyPairPath);
        const txDataBuffer  = Buffer.from(data['transaction'], 'base64');
        let transaction = VersionedTransaction.deserialize(Uint8Array.from(txDataBuffer));
        transaction.sign([wallet]);
        const tx = await connection.sendRawTransaction(transaction.serialize(), {
            preflightCommitment: connection.commitment
        });
        console.log('New transaction signature:', tx);
    } catch(e) {
        console.error('Transaction execution error:', e);
        throw new Error(e);
    }
}