-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathchain.ts
52 lines (44 loc) · 1.6 KB
/
chain.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
import type {
Chain,
CustomConversion,
FixedConversion,
Layout,
} from "@wormhole-foundation/sdk-base";
import { chainToChainId, chains, toChain } from "@wormhole-foundation/sdk-base";
const chainItemBase = { binary: "uint", size: 2 } as const;
type DontExpandAllChains<C> =
C extends typeof chains ? Chain : C extends Chain[] ? C[number] : never;
type AllowNull<T, B extends boolean> = B extends true ? T | null : T;
export const chainItem = <
const C extends readonly Chain[] = typeof chains,
const N extends boolean = false,
>(opts?: {
allowedChains?: C;
allowNull?: N;
}) =>
({
...chainItemBase,
custom: {
to: (val: number): AllowNull<DontExpandAllChains<C>, N> => {
if (val === 0) {
if (!opts?.allowNull)
throw new Error("ChainId 0 is not valid for this protocol and action");
return null as AllowNull<DontExpandAllChains<C>, N>;
}
const chain = toChain(val);
const allowedChains = opts?.allowedChains ?? chains;
if (!allowedChains.includes(chain))
throw new Error(`Chain ${chain} not in allowed chains ${allowedChains}`);
return chain as DontExpandAllChains<C>;
},
from: (val: AllowNull<C[number], N>): number => (val == null ? 0 : chainToChainId(val)),
} satisfies CustomConversion<number, AllowNull<C[number], N>>,
}) as const satisfies Layout;
export const fixedChainItem = <const C extends Chain>(chain: C) =>
({
...chainItemBase,
custom: {
to: chain,
from: chainToChainId(chain),
} satisfies FixedConversion<number, C>,
}) as const satisfies Layout;