-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroadhog.js
97 lines (85 loc) · 2.78 KB
/
roadhog.js
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
import { SiweMessage } from "siwe";
import { BrowserProvider, JsonRpcSigner } from "ethers";
import * as solanaWeb3 from "@solana/web3.js";
import bs58 from "bs58";
const ENDPOINT = "http://localhost:3000";
const getNonce = async (walletAddress, networkType) => {
const nonceResponse = await fetch(
`${ENDPOINT}/auth/nonce?address=${walletAddress}&type=${networkType}`,
);
const { nonce } = await nonceResponse.json();
return nonce;
};
export async function signIn(type) {
let address, signature, message;
message = {
domain: window.location.host,
statement: "Sign in to zk-Lokomotive",
uri: window.location.origin,
version: "1",
};
if (type === "ethereum") {
await window.ethereum.request({ method: "eth_requestAccounts" });
const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
address = await signer.getAddress();
const nonce = await getNonce(address, type);
message = new SiweMessage({ ...message, address, chainId: 1, nonce });
message = message.prepareMessage();
signature = await signer.signMessage(message);
} else if (type === "solana") {
const provider = window.solana;
await provider.connect();
address = provider.publicKey.toString();
const nonce = await getNonce(address, type);
const encodedMessage = new TextEncoder().encode(
JSON.stringify({ ...message, address, nonce, chainId: 900 }),
);
const signatureBytes = await provider.signMessage(encodedMessage, "utf8");
signature = bs58.encode(signatureBytes.signature);
} else {
console.error(
'roadhog/signIn: parameter type can be "ethereum" or "solana"',
);
return;
}
try {
const response = await fetch(`${ENDPOINT}/auth/verify`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message,
walletAddress: address,
signature,
}),
});
if (!response.ok) {
throw new Error((await response.json()).error);
}
const { authToken } = await response.json();
localStorage.setItem("authToken", authToken);
localStorage.setItem("networkType", type);
return { success: true, authToken, address };
} catch (error) {
console.error("Authentication error:", error);
return { success: false, error: error.message };
}
}
export async function signOff() {
const authToken = localStorage.getItem("authToken");
const response = await fetch(`${ENDPOINT}/auth/signoff`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
},
});
if (!response.ok) {
throw new Error((await response.json()).error);
} else {
localStorage.removeItem("authToken");
return true;
}
}