|
1 | 1 | import { gzip } from 'pako'; |
2 | 2 | import Json from 'json-bigint'; |
| 3 | +import { keccak256 } from 'ethereum-cryptography/keccak'; |
3 | 4 | import { CompressedProgram, Program } from './types'; |
4 | 5 | import { CONTRACT_ADDRESS_LOWER_BOUND, CONTRACT_ADDRESS_UPPER_BOUND } from './constants'; |
5 | 6 |
|
6 | 7 | export const isBrowser = typeof window !== 'undefined'; |
7 | 8 |
|
| 9 | +export const arrayBufferToString = (array: ArrayBuffer): string => |
| 10 | + String.fromCharCode.apply(null, array as any); |
| 11 | + |
| 12 | +export const stringToUint8Array = (str: string): Uint8Array => new TextEncoder().encode(str); |
| 13 | + |
8 | 14 | export const btoaUniversal = (b: ArrayBuffer): string => |
9 | | - isBrowser ? btoa(String.fromCharCode.apply(null, b as any)) : Buffer.from(b).toString('base64'); |
| 15 | + isBrowser ? btoa(arrayBufferToString(b)) : Buffer.from(b).toString('base64'); |
10 | 16 |
|
11 | 17 | export function randomIntFromInterval(min: number, max: number) { |
12 | 18 | return Math.floor(Math.random() * (max - min + 1) + min); |
@@ -42,3 +48,31 @@ export function compressProgram(jsonProgram: Program | string): CompressedProgra |
42 | 48 | const base64 = btoaUniversal(compressedProgram); |
43 | 49 | return base64; |
44 | 50 | } |
| 51 | + |
| 52 | +function buf2hex(buffer: Uint8Array) { |
| 53 | + return [...buffer].map((x) => x.toString(16).padStart(2, '0')).join(''); |
| 54 | +} |
| 55 | + |
| 56 | +const keccakHex = (value: string): string => buf2hex(keccak256(stringToUint8Array(value))); |
| 57 | + |
| 58 | +/** |
| 59 | + * Function to get the starknet keccak hash from a string |
| 60 | + * |
| 61 | + * [Reference](https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/starknet/public/abi.py#L17-L22) |
| 62 | + * @param value - string you want to get the starknetKeccak hash from |
| 63 | + * @returns starknet keccak hash as hex string |
| 64 | + */ |
| 65 | +export function starknetKeccak(value: string): string { |
| 66 | + return `0x${keccakHex(value).substr(2)}`; |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * Function to get the hex selector from a given function name |
| 71 | + * |
| 72 | + * [Reference](https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/starknet/public/abi.py#L25-L26) |
| 73 | + * @param funcName - selectors abi function name |
| 74 | + * @returns hex selector of given abi function name |
| 75 | + */ |
| 76 | +export function getSelectorFromName(funcName: string) { |
| 77 | + return starknetKeccak(funcName); |
| 78 | +} |
0 commit comments