Skip to content

Commit

Permalink
feat: Export encoding util methods
Browse files Browse the repository at this point in the history
  • Loading branch information
tristanmenzel committed Oct 8, 2024
1 parent 11ffcef commit cdce210
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,39 @@ 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'
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
Expand Down
13 changes: 13 additions & 0 deletions src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,13 @@ export const expandMaybeArray = <T>(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'))
}
Expand All @@ -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)
Expand Down

0 comments on commit cdce210

Please sign in to comment.