-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.ts
60 lines (47 loc) · 1.75 KB
/
index.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
"use strict";
import { Bytes, concat, hexlify } from "@ethersproject/bytes";
import { nameprep, toUtf8Bytes } from "@ethersproject/strings";
import { keccak256 } from "@ethersproject/keccak256";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
///////////////////////////////
const Zeros = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const Partition = new RegExp("^((.*)\\.)?([^.]+)$");
export function isValidName(name: string): boolean {
try {
const comps = name.split(".");
for (let i = 0; i < comps.length; i++) {
if (nameprep(comps[i]).length === 0) {
throw new Error("empty")
}
}
return true;
} catch (error) { }
return false;
}
export function namehash(name: string): string {
if (typeof(name) !== "string") {
logger.throwArgumentError("invalid address - " + String(name), "name", name);
}
let result: string | Uint8Array = Zeros;
while (name.length) {
const partition = name.match(Partition);
const label = toUtf8Bytes(nameprep(partition[3]));
result = keccak256(concat([result, keccak256(label)]));
name = partition[2] || "";
}
return hexlify(result);
}
export function id(text: string): string {
return keccak256(toUtf8Bytes(text));
}
export const messagePrefix = "\x19Ethereum Signed Message:\n";
export function hashMessage(message: Bytes | string): string {
if (typeof(message) === "string") { message = toUtf8Bytes(message); }
return keccak256(concat([
toUtf8Bytes(messagePrefix),
toUtf8Bytes(String(message.length)),
message
]));
}