import bs58 from 'bs58'; import { Connection, Keypair, PublicKey, Transaction, TransactionInstruction, TransactionMessage, VersionedTransaction, } from '@solana/web3.js'; import nacl from 'tweetnacl'; export async function generateLedgerSignature(connection, walletAdapter) { const transaction = await buildAuthTx(connection, walletAdapter) const signed = await walletAdapter.signTransaction(transaction) const paylaod = signed.serialize() const header = new TextEncoder().encode('SLCL-LEDGER-SIG:') const sig = new Uint8Array(paylaod.buffer) const message = new Uint8Array(header.length + sig.length) message.set(header) message.set(sig, header.length) return bs58.encode(message) } export function verifyLedgerSignature(publicKey: PublicKey, paylaod: Uint8Array) { const tx = VersionedTransaction.deserialize(paylaod); const message = tx.message.serialize(); return nacl.sign.detached.verify(message, tx.signatures[0], publicKey.toBytes()) } export function createWalletSignature(handle: string, secretKey: Keypair) { const encoded = bs58.encode(new TextEncoder().encode(`solcial:${handle}`)); return bs58.encode(nacl.sign.detached(new TextEncoder().encode(encoded), secretKey.secretKey)); } const NOOP_PROGRAM_ID = new PublicKey( "noopb9bkMVfRPU8AsbpTUg8AQkHtKwMYZiFUjNRtMmV" ) export async function buildAuthTx(connection: Connection, wallet) { // Create instructions to send, in this case a simple transfer const instructions = [ { programId: NOOP_PROGRAM_ID, keys: [], data: Buffer.from([]), }, ]; // Get the lates block hash to use on our transaction and confirmation const latestBlockhash = await connection.getLatestBlockhash() // Create a new TransactionMessage with version and compile it to legacy const messageLegacy = new TransactionMessage({ payerKey: wallet.publicKey, recentBlockhash: latestBlockhash.blockhash, instructions, }).compileToLegacyMessage(); // Create a new VersionedTransacction which supports legacy and v0 const transation = new VersionedTransaction(messageLegacy) return transation; }