/
typed-chain-id.ts
93 lines (78 loc) · 2.17 KB
/
typed-chain-id.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2022-2023 Webb Technologies Inc.
// SPDX-License-Identifier: Apache-2.0
// Each ChainType has its own namespace of ChainIDs.
export enum ChainType {
None = 0x0000,
EVM = 0x0100,
Substrate = 0x0200,
SubstrateDevelopment = 0x0250,
PolkadotRelayChain = 0x0301,
KusamaRelayChain = 0x0302,
PolkadotParachain = 0x0310,
KusamaParachain = 0x0311,
Cosmos = 0x0400,
Solana = 0x0500,
}
export function castToChainType (v: number): ChainType {
switch (v) {
case 0x0100:
return ChainType.EVM;
case 0x0200:
return ChainType.Substrate;
case 0x0301:
return ChainType.PolkadotRelayChain;
case 0x0302:
return ChainType.KusamaRelayChain;
case 0x0310:
return ChainType.PolkadotParachain;
case 0x0311:
return ChainType.KusamaParachain;
case 0x0400:
return ChainType.Cosmos;
case 0x0500:
return ChainType.Solana;
default:
return ChainType.None;
}
}
export type TypedChainId = {
chainType: ChainType;
chainId: number;
}
/**
* @param num - the number to be converted
* @param min - the minimum bytes the array should hold (in the case of requiring empty bytes to match rust values)
* @returns
*/
export const numToByteArray = (num: number, min: number): number[] => {
let arr = [];
while (num > 0) {
arr.push(num % 256);
num = Math.floor(num / 256);
}
arr.reverse();
// maintain minimum number of bytes
while (arr.length < min) {
arr = [0, ...arr];
}
return arr;
};
export const byteArrayToNum = (arr: number[]): number => {
let n = 0;
for (const i of arr) {
n = n * 256 + i;
}
return n;
};
export const calculateTypedChainId = (chainType: ChainType, chainId: number): number => {
const chainTypeArray = numToByteArray(chainType, 2);
const chainIdArray = numToByteArray(chainId, 4);
const fullArray = [...chainTypeArray, ...chainIdArray];
return byteArrayToNum(fullArray);
};
export const parseTypedChainId = (chainIdType: number): TypedChainId => {
const byteArray = numToByteArray(chainIdType, 4);
const chainType = byteArrayToNum(byteArray.slice(0, 2));
const chainId = byteArrayToNum(byteArray.slice(2));
return { chainId, chainType };
};