UNPKG

@axelar-network/axelarjs-sdk

Version:
65 lines 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateSolanaAddress = validateSolanaAddress; exports.anchorInstructionDiscriminator = anchorInstructionDiscriminator; exports.encodeU32LE = encodeU32LE; exports.encodeU64LE = encodeU64LE; exports.encodeStringBorsh = encodeStringBorsh; exports.concatU8 = concatU8; const web3_js_1 = require("@solana/web3.js"); const utils_1 = require("ethers/lib/utils"); /** * Helper function to validate Solana addresses using PublicKey * @param address - The address string to validate * @param fieldName - The name of the field being validated (for error messages) * @returns The validated PublicKey instance * @throws Error if the address is invalid */ function validateSolanaAddress(address, fieldName) { try { return new web3_js_1.PublicKey(address); } catch (error) { throw new Error(`Invalid ${fieldName}: ${address}. ${error instanceof Error ? error.message : "Unknown error"}`); } } /** * Computes the Anchor instruction discriminator * Equivalent to: * let preimage = format!("global:{}", method_name); * let discriminator = &sha256(preimage.as_bytes())[0..8]; * * @param methodName Anchor instruction name * @returns exactly 8 bytes */ function anchorInstructionDiscriminator(methodName) { const digest = (0, utils_1.arrayify)((0, utils_1.sha256)((0, utils_1.toUtf8Bytes)(`global:${methodName}`))); // 32 bytes return Buffer.from(digest.slice(0, 8)); // first 8 bytes = discriminator } function encodeU32LE(value) { if (!Number.isInteger(value) || value < 0) { throw new Error("encodeU32LE expects a non-negative integer"); } const b = Buffer.alloc(4); b.writeUInt32LE(value, 0); return b; } function encodeU64LE(value) { const big = typeof value === "bigint" ? value : BigInt(value); if (big < BigInt(0)) throw new Error("encodeU64LE expects non-negative"); const b = Buffer.alloc(8); b.writeBigUInt64LE(big, 0); return b; } function encodeStringBorsh(value) { const bytes = Buffer.from(value, "utf8"); return concatU8([encodeU32LE(bytes.length), bytes]); } // Buffer.concat's typing is finicky across @types/node versions: a Buffer<ArrayBufferLike>[] // is not always accepted as Uint8Array<ArrayBufferLike>[] due to Symbol.dispose differences. // Centralize the cast here so call sites stay clean. function concatU8(parts) { return Buffer.concat(parts); } //# sourceMappingURL=solanaHelper.js.map