diff --git a/src/index.ts b/src/index.ts index f80e8fc4..b721cef8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,18 @@ import { logger } from './logger' import { createTsProgram } from './parser' import { invokePuya } from './puya' import type { PuyaPassThroughOptions } from './puya/options' +import { + base32ToUint8Array, + base64ToUint8Array, + bigIntToUint8Array, + hexToUint8Array, + uint8ArrayToBase32, + uint8ArrayToBase64, + uint8ArrayToBigInt, + uint8ArrayToHex, + uint8ArrayToUtf8, + utf8ToUint8Array, +} from './util' export { SourceLocation } from './awst/source-location' export { anyPType, ContractClassPType, FunctionPType, PType } from './awst_build/ptypes' @@ -18,6 +30,20 @@ export { registerPTypes } from './awst_build/ptypes/register' export { typeRegistry } from './awst_build/type-registry' export { TypeResolver } from './awst_build/type-resolver' +export const encodingUtil = { + utf8ToUint8Array, + bigIntToUint8Array, + hexToUint8Array, + base32ToUint8Array, + base64ToUint8Array, + + uint8ArrayToUtf8, + uint8ArrayToHex, + uint8ArrayToBase32, + uint8ArrayToBase64, + uint8ArrayToBigInt, +} + export type CompileResult = { logs: LogEvent[] programDirectory: string diff --git a/src/util/index.ts b/src/util/index.ts index a4455669..35b88bdb 100644 --- a/src/util/index.ts +++ b/src/util/index.ts @@ -53,10 +53,13 @@ export const expandMaybeArray = (maybeArray: T | T[]): T[] => { return Array.isArray(maybeArray) ? maybeArray : [maybeArray] } +export const uint8ArrayToBase64 = (value: Uint8Array): string => Buffer.from(value).toString('base64') + export const hexToUint8Array = (value: string): Uint8Array => { invariant(value.length % 2 === 0, 'Hex string must have even number of characters') return new Uint8Array(new Array(value.length / 2).fill(0).map((_, i) => parseInt(value.slice(i * 2, i * 2 + 1), 16))) } + export const base64ToUint8Array = (value: string): Uint8Array => { return new Uint8Array(Buffer.from(value, 'base64')) } @@ -66,6 +69,16 @@ export const utf8ToUint8Array = (value: string): Uint8Array => { return encoder.encode(value) } +export const uint8ArrayToBigInt = (v: Uint8Array): bigint => { + // Assume big-endian + return Array.from(v) + .toReversed() + .map((byte_value, i): bigint => BigInt(byte_value) << BigInt(i * 8)) + .reduce((a, b) => a + b, 0n) +} + +export const uint8ArrayToHex = (value: Uint8Array): string => Buffer.from(value).toString('hex') + export const uint8ArrayToUtf8 = (value: Uint8Array): string => { const decoder = new TextDecoder() return decoder.decode(value)