wordlist.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. // This gets overridden by rollup
  3. const exportWordlist = false;
  4. import { id } from "@ethersproject/hash";
  5. import { defineReadOnly } from "@ethersproject/properties";
  6. import { Logger } from "@ethersproject/logger";
  7. import { version } from "./_version";
  8. export const logger = new Logger(version);
  9. export abstract class Wordlist {
  10. readonly locale: string;
  11. constructor(locale: string) {
  12. logger.checkAbstract(new.target, Wordlist);
  13. defineReadOnly(this, "locale", locale);
  14. }
  15. abstract getWord(index: number): string;
  16. abstract getWordIndex(word: string): number;
  17. // Subclasses may override this
  18. split(mnemonic: string): Array<string> {
  19. return mnemonic.toLowerCase().split(/ +/g)
  20. }
  21. // Subclasses may override this
  22. join(words: Array<string>): string {
  23. return words.join(" ");
  24. }
  25. static check(wordlist: Wordlist): string {
  26. const words = [];
  27. for (let i = 0; i < 2048; i++) {
  28. const word = wordlist.getWord(i);
  29. /* istanbul ignore if */
  30. if (i !== wordlist.getWordIndex(word)) { return "0x"; }
  31. words.push(word);
  32. }
  33. return id(words.join("\n") + "\n");
  34. }
  35. static register(lang: Wordlist, name?: string): void {
  36. if (!name) { name = lang.locale; }
  37. /* istanbul ignore if */
  38. if (exportWordlist) {
  39. try {
  40. const anyGlobal = (window as any)
  41. if (anyGlobal._ethers && anyGlobal._ethers.wordlists) {
  42. if (!anyGlobal._ethers.wordlists[name]) {
  43. defineReadOnly(anyGlobal._ethers.wordlists, name, lang);
  44. }
  45. }
  46. } catch (error) { }
  47. }
  48. }
  49. }