forked from starknet-io/starknet.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselector.ts
66 lines (60 loc) · 2.18 KB
/
selector.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { keccak } from 'micro-starknet';
import { MASK_250 } from '../constants';
import { BigNumberish } from '../types';
import { addHexPrefix, removeHexPrefix, utf8ToArray } from './encode';
import { hexToBytes, isHex, isStringWholeNumber, toHex, toHexString } from './num';
/**
* Keccak hash BigNumberish value
* @param value BigNumberish
* @returns string - hexadecimal string
*/
export function keccakBn(value: BigNumberish): string {
const hexWithoutPrefix = removeHexPrefix(toHex(BigInt(value)));
const evenHex = hexWithoutPrefix.length % 2 === 0 ? hexWithoutPrefix : `0${hexWithoutPrefix}`;
return addHexPrefix(keccak(hexToBytes(addHexPrefix(evenHex))).toString(16));
}
/**
* Keccak hash string value
* @param value string
* @returns string - hexadecimal string
*/
function keccakHex(value: string): string {
return addHexPrefix(keccak(utf8ToArray(value)).toString(16));
}
/**
* Function to get the starknet keccak hash from a string
*
* [Reference](https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/starknet/public/abi.py#L17-L22)
* @param value - string you want to get the starknetKeccak hash from
* @returns starknet keccak hash as BigNumber
*/
export function starknetKeccak(value: string): bigint {
const hash = BigInt(keccakHex(value));
// eslint-disable-next-line no-bitwise
return hash & MASK_250;
}
/**
* Function to get the hex selector from a given function name
*
* [Reference](https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/starknet/public/abi.py#L25-L26)
* @param funcName - selectors abi function name
* @returns hex selector of given abi function name
*/
export function getSelectorFromName(funcName: string) {
// sometimes BigInteger pads the hex string with zeros, which is not allowed in the starknet api
return toHex(starknetKeccak(funcName));
}
/**
* Function to get hex selector from function name, decimal string or hex string
* @param value hex string | decimal string | string
* @returns Hex selector
*/
export function getSelector(value: string) {
if (isHex(value)) {
return value;
}
if (isStringWholeNumber(value)) {
return toHexString(value);
}
return getSelectorFromName(value);
}