-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlocal-storage.ts
58 lines (49 loc) · 1.32 KB
/
local-storage.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
import {
DelegationChain,
DelegationIdentity,
Ed25519KeyIdentity,
} from "@dfinity/identity";
import type { SiweIdentityStorage } from "./storage.type";
const STORAGE_KEY = "siweIdentity";
/**
* Loads the SIWE identity from local storage.
*/
export function loadIdentity() {
const storedState = localStorage.getItem(STORAGE_KEY);
if (!storedState) {
throw new Error("No stored identity found.");
}
const s: SiweIdentityStorage = JSON.parse(storedState);
if (!s.address || !s.sessionIdentity || !s.delegationChain) {
throw new Error("Stored state is invalid.");
}
const d = DelegationChain.fromJSON(JSON.stringify(s.delegationChain));
const i = DelegationIdentity.fromDelegation(
Ed25519KeyIdentity.fromJSON(JSON.stringify(s.sessionIdentity)),
d
);
return [s.address, i, d] as const;
}
/**
* Saves the SIWE identity to local storage.
*/
export function saveIdentity(
address: string,
sessionIdentity: Ed25519KeyIdentity,
delegationChain: DelegationChain
) {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
address: address,
sessionIdentity: sessionIdentity.toJSON(),
delegationChain: delegationChain.toJSON(),
})
);
}
/**
* Clears the SIWE identity from local storage.
*/
export function clearIdentity() {
localStorage.removeItem(STORAGE_KEY);
}