ethers.js/packages/wordlists/src.ts/wordlist.ts

60 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2019-05-14 18:25:46 -04:00
"use strict";
// This gets overridden by rollup
const exportWordlist = false;
2019-05-14 18:25:46 -04:00
import { id } from "@ethersproject/hash";
import { defineReadOnly } from "@ethersproject/properties";
2019-08-01 18:04:06 -04:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
2019-11-23 21:20:23 +09:00
export const logger = new Logger(version);
2019-05-14 18:25:46 -04:00
export abstract class Wordlist {
readonly locale: string;
constructor(locale: string) {
2019-08-01 18:04:06 -04:00
logger.checkAbstract(new.target, Wordlist);
2019-05-14 18:25:46 -04:00
defineReadOnly(this, "locale", locale);
}
abstract getWord(index: number): string;
abstract getWordIndex(word: string): number;
// Subclasses may override this
split(mnemonic: string): Array<string> {
return mnemonic.toLowerCase().split(/ +/g)
}
// Subclasses may override this
join(words: Array<string>): string {
return words.join(" ");
}
2019-11-23 21:20:23 +09:00
static check(wordlist: Wordlist): string {
const words = [];
for (let i = 0; i < 2048; i++) {
const word = wordlist.getWord(i);
if (i !== wordlist.getWordIndex(word)) { return "0x"; }
words.push(word);
}
return id(words.join("\n") + "\n");
}
static register(lang: Wordlist, name?: string): void {
if (!name) { name = lang.locale; }
if (exportWordlist) {
2019-11-24 19:13:37 +09:00
try {
const anyGlobal = (window as any)
if (anyGlobal._ethers && anyGlobal._ethers.wordlists) {
if (!anyGlobal._ethers.wordlists[name]) {
defineReadOnly(anyGlobal._ethers.wordlists, name, lang);
}
2019-11-23 21:20:23 +09:00
}
2019-11-24 19:13:37 +09:00
} catch (error) { }
2019-05-14 18:25:46 -04:00
}
}
2019-11-23 21:20:23 +09:00
2019-05-14 18:25:46 -04:00
}
2019-11-23 21:20:23 +09:00