Skip to content

Instantly share code, notes, and snippets.

@davidmurdoch
Last active September 10, 2020 17:06
Show Gist options
  • Save davidmurdoch/0f8fb6bc80e76dab45e3f871fe5a649c to your computer and use it in GitHub Desktop.
Save davidmurdoch/0f8fb6bc80e76dab45e3f871fe5a649c to your computer and use it in GitHub Desktop.
Typesafe Ethereum Transaction hash
type Cast<T, U> = T extends U ? T : U;
type Prop<T, K> = K extends keyof T ? T[K] : never;
type HexChars = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f";
type HexPairs = `${HexChars}${HexChars}`;
type Hex<S extends string> =
S extends "" ? [] :
S extends `${HexPairs}${infer R}` ? S extends `${infer C}${R}`
? [C, ...(Hex<R> extends infer X ? Cast<X, string[]> : never)]
: never : never;
// @ts-ignore: Type instantiation is excessively deep and possibly infinite. (2589)
declare function test<
S extends string,
O extends {hex: S},
Raw1 extends (O["hex"] extends `0x${infer I0}${infer I1}${infer I2}${infer I3}${infer I4}${infer I5}${infer I6}${infer I7}${infer I8}${infer I9}${infer I10}${infer I11}${infer I12}${infer I13}${infer I14}${infer I15}${infer I16}${infer I17}${infer I18}${infer I19}${infer I20}${infer I21}${infer _}` ? `${I0}${I1}${I2}${I3}${I4}${I5}${I6}${I7}${I8}${I9}${I10}${I11}${I12}${I13}${I14}${I15}${I16}${I17}${I18}${I19}${I20}${I21}` : never),
Raw2 extends (O["hex"] extends `0x${Raw1}${infer I0}${infer I1}${infer I2}${infer I3}${infer I4}${infer I5}${infer I6}${infer I7}${infer I8}${infer I9}${infer I10}${infer I11}${infer I12}${infer I13}${infer I14}${infer I15}${infer I16}${infer I17}${infer I18}${infer I19}${infer I20}${infer I21}${infer _}` ? `${I0}${I1}${I2}${I3}${I4}${I5}${I6}${I7}${I8}${I9}${I10}${I11}${I12}${I13}${I14}${I15}${I16}${I17}${I18}${I19}${I20}${I21}` : never),
_Raw extends `${Raw1}${Raw2}`,
Raw3 extends (O["hex"] extends `0x${_Raw}${infer I0}${infer I1}${infer I2}${infer I3}${infer I4}${infer I5}${infer I6}${infer I7}${infer I8}${infer I9}${infer I10}${infer I11}${infer I12}${infer I13}${infer I14}${infer I15}${infer I16}${infer I17}${infer I18}${infer I19}` ? `${I0}${I1}${I2}${I3}${I4}${I5}${I6}${I7}${I8}${I9}${I10}${I11}${I12}${I13}${I14}${I15}${I16}${I17}${I18}${I19}` : never),
AsHex1 extends Hex<Raw1>,
AsHex2 extends Hex<Raw2>,
AsHex3 extends Hex<Raw3>,
L1 extends Prop<AsHex1, "length">,
L2 extends Prop<AsHex2, "length">,
L3 extends Prop<AsHex3, "length">,
>(opts: L1 extends 11 ? L2 extends 11 ? L3 extends 10 ? O : never : never : never): `${Raw1}${Raw2}${Raw3}`;
const a = test({hex: "0x855ae991c56f75dd079a5a52b216c232465977623277dd9645b5eadc7c77cd3B"});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment