forked from pepae/ShutterAPIHongbao
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet.js
More file actions
197 lines (173 loc) · 7.08 KB
/
wallet.js
File metadata and controls
197 lines (173 loc) · 7.08 KB
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const createWalletButton = document.getElementById("createWallet");
const loadWalletButton = document.getElementById("loadWallet");
const walletOutput = document.getElementById("walletOutput");
const recipientInput = document.getElementById("recipient");
const amountInput = document.getElementById("amount");
const sendFundsButton = document.getElementById("sendFunds");
const transactionOutput = document.getElementById("transactionOutput");
const walletBalanceDiv = document.getElementById("walletBalance");
// Gnosis Chain RPC URL
const GNOSIS_RPC_URL = "https://rpc.gnosis.gateway.fm";
// Helper function to convert ArrayBuffer to a Hexadecimal String
function bufferToHex(buffer) {
return Array.from(new Uint8Array(buffer))
.map(byte => byte.toString(16).padStart(2, '0'))
.join('');
}
/**
* Registers a passkey using WebAuthn and derives the wallet deterministically.
*/
export async function registerPasskey(walletName) {
try {
const challenge = new Uint8Array(32);
window.crypto.getRandomValues(challenge);
const uniqueUserId = new Uint8Array(16);
window.crypto.getRandomValues(uniqueUserId);
const credential = await navigator.credentials.create({
publicKey: {
challenge: challenge,
rp: { name: "Gnosis Wallet", id: "hongbao.shutter.network" },
user: {
id: uniqueUserId,
name: `wallet-${bufferToHex(uniqueUserId)}`,
displayName: walletName || "Unnamed Wallet",
},
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
],
authenticatorSelection: {
residentKey: "required",
userVerification: "required",
authenticatorAttachment: "platform",
},
timeout: 120000,
},
});
if (!credential || !credential.rawId) {
throw new Error("Credential is missing required properties (rawId).");
}
const rawIdHex = bufferToHex(credential.rawId);
const hashedRawId = ethers.keccak256(ethers.toUtf8Bytes(rawIdHex));
const wallet = new ethers.Wallet(hashedRawId);
console.log("Wallet Address:", wallet.address);
return wallet;
} catch (error) {
console.error("Error during WebAuthn registration:", error);
alert(`Failed to register passkey: ${error.message}`);
throw error;
}
}
/**
* Authenticates the user with WebAuthn and derives the wallet deterministically.
*/
export async function authenticateWallet() {
try {
const challenge = new Uint8Array(32);
window.crypto.getRandomValues(challenge);
console.log("Attempting authentication with challenge:", challenge);
const assertion = await navigator.credentials.get({
publicKey: {
challenge: challenge,
userVerification: "required",
},
});
if (!assertion || !assertion.rawId) {
throw new Error("Failed to retrieve assertion or rawId.");
}
const rawIdHex = bufferToHex(assertion.rawId);
const hashedRawId = ethers.keccak256(ethers.toUtf8Bytes(rawIdHex));
const wallet = new ethers.Wallet(hashedRawId);
console.log("Wallet authenticated successfully:", wallet.address);
return wallet;
} catch (error) {
console.error("Error during WebAuthn authentication:", error);
alert(`Failed to authenticate wallet: ${error.message}`);
throw error;
}
}
/**
* Updates the wallet balance.
*/
async function updateWalletBalance(wallet) {
try {
const provider = new ethers.JsonRpcProvider(GNOSIS_RPC_URL);
const balance = await provider.getBalance(wallet.address);
const formattedBalance = ethers.formatEther(balance);
if (walletBalanceDiv) {
walletBalanceDiv.textContent = `Balance: ${formattedBalance} xDAI`;
}
} catch (error) {
console.error("Error fetching wallet balance:", error);
if (walletBalanceDiv) {
walletBalanceDiv.textContent = "Balance: Error fetching balance";
}
}
}
// Add event listeners if elements exist
document.addEventListener("DOMContentLoaded", () => {
if (createWalletButton) {
createWalletButton.addEventListener("click", async () => {
try {
const wallet = await registerPasskey();
if (walletOutput) {
walletOutput.value = `Wallet created successfully!\nAddress: ${wallet.address}`;
}
console.log("Wallet Address:", wallet.address);
updateWalletBalance(wallet);
} catch (error) {
console.error("Error creating wallet:", error);
alert("Failed to create wallet. Ensure your device supports WebAuthn.");
}
});
}
if (loadWalletButton) {
loadWalletButton.addEventListener("click", async () => {
try {
const wallet = await authenticateWallet();
if (walletOutput) {
walletOutput.value = `Wallet loaded successfully!\nAddress: ${wallet.address}`;
}
console.log("Wallet Address:", wallet.address);
updateWalletBalance(wallet);
} catch (error) {
console.error("Error loading wallet:", error);
alert("Failed to load wallet. Ensure you authenticate correctly.");
}
});
}
if (sendFundsButton) {
sendFundsButton.addEventListener("click", async () => {
const recipient = recipientInput?.value.trim();
const amount = parseFloat(amountInput?.value);
if (!ethers.isAddress(recipient)) {
alert("Invalid recipient address!");
return;
}
if (isNaN(amount) || amount <= 0) {
alert("Invalid amount!");
return;
}
try {
const wallet = await authenticateWallet();
const provider = new ethers.JsonRpcProvider(GNOSIS_RPC_URL);
const walletWithProvider = wallet.connect(provider);
const tx = await walletWithProvider.sendTransaction({
to: recipient,
value: ethers.parseEther(amount.toString()),
});
if (transactionOutput) {
transactionOutput.value = `Transaction sent!\nHash: ${tx.hash}`;
}
console.log("Transaction:", tx);
const receipt = await tx.wait();
if (transactionOutput) {
transactionOutput.value += `\nTransaction confirmed in block ${receipt.blockNumber}`;
}
} catch (error) {
console.error("Error sending funds:", error);
alert("Failed to send funds. Check console for details.");
}
});
}
});