import { PublicKey } from "@solana/web3.js"; import { PROGRAM_ID } from "../constants.js"; /** * User profile state structure */ export interface UserProfile { owner: PublicKey; nickname: string; bump: number; } /** * Derive the user profile PDA for a wallet * * @param wallet - User's wallet public key * @returns User profile PDA public key * * @example * ```typescript * const profilePda = getUserProfileAddress(wallet.publicKey); * const accountInfo = await connection.getAccountInfo(profilePda); * ``` */ export function getUserProfileAddress(wallet: PublicKey): PublicKey { const [pda] = PublicKey.findProgramAddressSync( [Buffer.from("user_profile"), wallet.toBuffer()], PROGRAM_ID ); return pda; } /** * Derive the user profile PDA with bump * * @param wallet - User's wallet public key * @returns Tuple of [PDA, bump] */ export function getUserProfileAddressWithBump(wallet: PublicKey): [PublicKey, number] { return PublicKey.findProgramAddressSync( [Buffer.from("user_profile"), wallet.toBuffer()], PROGRAM_ID ); } /** * Parse a UserProfile account from raw buffer data * * @param data - Raw account data buffer (excluding 8-byte discriminator) * @returns Parsed UserProfile object * @throws Error if buffer is too small * * @example * ```typescript * const profilePda = getUserProfileAddress(wallet); * const accountInfo = await connection.getAccountInfo(profilePda); * if (accountInfo) { * const profile = parseUserProfileAccount(accountInfo.data.slice(8)); * } * ``` */ export function parseUserProfileAccount(data: Uint8Array): UserProfile { const buffer = Buffer.from(data); const MIN_SIZE = 32 + 4 + 1; // owner + string length + bump if (buffer.length < MIN_SIZE) { throw new Error( `Buffer too small for UserProfile: expected at least ${MIN_SIZE} bytes, got ${buffer.length}` ); } let offset = 0; // owner: Pubkey (32 bytes) const owner = new PublicKey(buffer.slice(offset, offset + 32)); offset += 32; // nickname: String (4-byte length prefix + UTF-8 bytes) const nicknameLength = buffer.readUInt32LE(offset); offset += 4; const nickname = buffer.slice(offset, offset + nicknameLength).toString("utf-8"); offset += nicknameLength; // bump: u8 const bump = buffer.readUInt8(offset); return { owner, nickname, bump, }; }