import { log } from "console"; import { ASSOCIATED_TOKEN_ACCOUNT_PROGRAM, TOKEN_PROGRAM } from "./Constants"; import { decodeBase58, encodeBase58 } from "./Encoding"; var shajs = require('sha.js') import {ed25519} from '@noble//curves/ed25519'; import {sha256} from '@noble/hashes/sha256'; const MAX_SEED_LENGTH = 32; export function verifyAddressHelper(address: string): boolean { try{ let decoded= decodeBase58(address); if(decoded.length != 32) return false; return true; }catch(Error){ return false; } } export function generateAssociatedTokenAddressHelper(owner: string, mint: string): string{ let seeds = [decodeBase58(owner), TOKEN_PROGRAM, decodeBase58(mint)]; let nonce = 255; let address; while(nonce != 0){ try{ const seedsWithNonce = seeds.concat(Buffer.from([nonce])); address = createProgramAddress(seedsWithNonce, ASSOCIATED_TOKEN_ACCOUNT_PROGRAM) }catch (err){ if (err instanceof TypeError) { throw err; } nonce--; continue; } return address; } throw new Error(`Unable to find a viable program address nonce`); } function createProgramAddress(seeds: Array, programId: Buffer): string{ let buffer = Buffer.alloc(0); seeds.forEach(function (seed) { if (seed.length > MAX_SEED_LENGTH) { throw new TypeError(`Max seed length exceeded`); } buffer = Buffer.concat([buffer, seed]); }); buffer = Buffer.concat([ buffer, programId, Buffer.from('ProgramDerivedAddress'), ]); let publicKeyBytes = sha256(buffer); if (isOnCurve(publicKeyBytes)) { throw new Error(`Invalid seeds, address must fall off the curve`); } return encodeBase58(Buffer.from(publicKeyBytes)); } export function isOnCurve(publicKey: Uint8Array): boolean { try { ed25519.ExtendedPoint.fromHex(publicKey); return true; } catch { return false; } }