|
1 | 1 | import { randomUUID } from "node:crypto"; |
2 | 2 | import type { Address, Hex } from "viem"; |
3 | 3 | import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; |
| 4 | +import { err, ok, type Result } from "./result.js"; |
4 | 5 |
|
5 | 6 | export type NodeId = string & { readonly __brand: "nodeId" }; |
6 | 7 |
|
7 | | -export type Identity = { |
8 | | - readonly nodeId: NodeId; |
9 | | - readonly publicAddress: Address; |
10 | | - readonly privateKey: Hex; |
11 | | -}; |
| 8 | +export class Identity { |
| 9 | + readonly #nodeId: NodeId; |
| 10 | + readonly #publicAddress: Address; |
| 11 | + readonly #privateKey: Hex; |
12 | 12 |
|
13 | | -export function createNodeId(): NodeId { |
14 | | - return randomUUID() as NodeId; |
15 | | -} |
| 13 | + private constructor(nodeId: NodeId, publicAddress: Address, privateKey: Hex) { |
| 14 | + this.#nodeId = nodeId; |
| 15 | + this.#publicAddress = publicAddress; |
| 16 | + this.#privateKey = privateKey; |
| 17 | + } |
| 18 | + |
| 19 | + static create(nodeId: NodeId): Result<Identity, "failed_to_create_identity"> { |
| 20 | + try { |
| 21 | + const privateKey = generatePrivateKey(); |
| 22 | + const account = privateKeyToAccount(privateKey); |
| 23 | + |
| 24 | + return ok(new Identity(nodeId, account.address, privateKey)); |
| 25 | + } catch { |
| 26 | + return err("failed_to_create_identity"); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + get nodeId(): NodeId { |
| 31 | + return this.#nodeId; |
| 32 | + } |
16 | 33 |
|
17 | | -export function createIdentity(): Identity { |
18 | | - const privateKey = generatePrivateKey(); |
19 | | - const account = privateKeyToAccount(privateKey); |
| 34 | + get publicAddress(): Address { |
| 35 | + return this.#publicAddress; |
| 36 | + } |
20 | 37 |
|
21 | | - return { |
22 | | - nodeId: createNodeId(), |
23 | | - publicAddress: account.address, |
24 | | - privateKey, |
25 | | - }; |
| 38 | + async signMessage(message: string): Promise<Hex> { |
| 39 | + const account = privateKeyToAccount(this.#privateKey); |
| 40 | + |
| 41 | + return account.signMessage({ message }); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +export function createNodeId(): NodeId { |
| 46 | + return randomUUID() as NodeId; |
26 | 47 | } |
0 commit comments