//const { VersionedTransaction, Keypair } = require('@solana/web3.js');
//const bs58 = require('bs58');

import {
  VersionedTransaction,
  Keypair,
} from '@solana/web3.js';

import bs58 from 'bs58';



function exitWithError(message) {
  console.error("ERR:", message);
  process.exit(1);
}

(async () => {
  const base64Tx = process.argv[2];
  const privateKeyBase58 = process.argv[3].trim();


  if (!base64Tx) exitWithError("Missing base64 transaction as argument");
  if (!privateKeyBase58) exitWithError("Missing base58 private key as argument");

  let secretKey;
  try {
    //secretKey = bs58alt.decode(privateKeyBase58);
    secretKey = bs58.decode(privateKeyBase58);
    //console.log("Decoded length:", secretKey.length);
  } catch (e) {
    exitWithError("Invalid base58 private key: "+privateKeyBase58);
  }

  let transaction;
  try {
    const txBuffer = Buffer.from(base64Tx, 'base64');
    transaction = VersionedTransaction.deserialize(txBuffer);
  } catch (e) {
    exitWithError("Failed to deserialize transaction: " + e.message);
  }

  try {
    const keypair = Keypair.fromSecretKey(secretKey);
    transaction.sign([keypair]);

    const signedBase64 = Buffer.from(transaction.serialize()).toString('base64');
    console.log(signedBase64);
    process.exit(0);
  } catch (e) {
    exitWithError("Signing failed: " + e.message);
  }
})();
