-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsiwe-provider.ts
109 lines (95 loc) · 2.52 KB
/
siwe-provider.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import {
HttpAgent,
type ActorConfig,
type HttpAgentOptions,
Actor,
type DerEncodedPublicKey,
type ActorSubclass,
} from "@dfinity/agent";
import type { IDL } from "@dfinity/candid";
import type { SIWE_IDENTITY_SERVICE } from "./service.interface";
/**
* Creates an anonymous actor for interactions with the Internet Computer.
* This is used primarily for the initial authentication process.
*/
export async function createAnonymousActor({
idlFactory,
canisterId,
httpAgentOptions,
actorOptions,
}: {
idlFactory: IDL.InterfaceFactory;
canisterId: string;
httpAgentOptions?: HttpAgentOptions;
actorOptions?: ActorConfig;
}) {
const shouldFetchRootKey = process.env.DFX_NETWORK !== "ic";
const agent = await HttpAgent.create({
...httpAgentOptions,
shouldFetchRootKey,
});
return Actor.createActor<SIWE_IDENTITY_SERVICE>(idlFactory, {
agent,
canisterId,
...actorOptions,
});
}
export async function callPrepareLogin(
anonymousActor: ActorSubclass<SIWE_IDENTITY_SERVICE>,
address: `0x${string}` | undefined,
) {
if (!anonymousActor || !address) {
throw new Error("Invalid actor or address");
}
const response = await anonymousActor.siwe_prepare_login(address);
if ("Err" in response) {
throw new Error(response.Err);
}
return response.Ok;
}
/**
* Logs in the user by sending a signed SIWE message to the backend.
*/
export async function callLogin(
anonymousActor: ActorSubclass<SIWE_IDENTITY_SERVICE>,
signature: `0x${string}` | undefined,
address: `0x${string}` | undefined,
sessionPublicKey: DerEncodedPublicKey,
nonce: string,
) {
if (!anonymousActor || !signature || !address) {
throw new Error("Invalid actor, data or address");
}
const loginReponse = await anonymousActor.siwe_login(
signature,
address,
new Uint8Array(sessionPublicKey),
nonce,
);
if ("Err" in loginReponse) {
throw new Error(loginReponse.Err);
}
return loginReponse.Ok;
}
/**
* Retrieves a delegation from the backend for the current session.
*/
export async function callGetDelegation(
anonymousActor: ActorSubclass<SIWE_IDENTITY_SERVICE>,
address: `0x${string}` | undefined,
sessionPublicKey: DerEncodedPublicKey,
expiration: bigint,
) {
if (!anonymousActor || !address) {
throw new Error("Invalid actor or address");
}
const response = await anonymousActor.siwe_get_delegation(
address,
new Uint8Array(sessionPublicKey),
expiration,
);
if ("Err" in response) {
throw new Error(response.Err);
}
return response.Ok;
}