This repository has been archived by the owner on May 28, 2024. It is now read-only.
forked from joss-aztec/cra4-aztec-sdk-starter
-
Notifications
You must be signed in to change notification settings - Fork 18
/
App.tsx
280 lines (254 loc) · 8.69 KB
/
App.tsx
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import "./App.css";
import { useEffect, useState } from "react";
import { ethers } from "ethers";
import {
AztecSdk,
createAztecSdk,
EthersAdapter,
EthereumProvider,
AztecSdkUser,
GrumpkinAddress,
SchnorrSigner,
EthAddress,
TxSettlementTime,
TxId,
} from "@aztec/sdk";
import { depositEthToAztec, registerAccount, aztecConnect } from "./utils.js";
import { fetchBridgeData } from "./bridge-data.js";
declare var window: any;
const App = () => {
const [hasMetamask, setHasMetamask] = useState(false);
const [ethAccount, setEthAccount] = useState<EthAddress | null>(null);
const [initing, setIniting] = useState(false);
const [sdk, setSdk] = useState<null | AztecSdk>(null);
const [account0, setAccount0] = useState<AztecSdkUser | null>(null);
const [userExists, setUserExists] = useState<boolean>(false);
const [accountPrivateKey, setAccountPrivateKey] = useState<Buffer | null>(
null
);
const [accountPublicKey, setAccountPublicKey] =
useState<GrumpkinAddress | null>(null);
const [spendingSigner, setSpendingSigner] = useState<SchnorrSigner | null>(
null
);
const [alias, setAlias] = useState("");
const [amount, setAmount] = useState(0);
const [txId, setTxId] = useState<TxId | null>(null);
// Metamask Check
useEffect(() => {
if (window.ethereum) {
setHasMetamask(true);
}
window.ethereum.on("accountsChanged", () => window.location.reload());
}, []);
async function connect() {
try {
if (window.ethereum) {
setIniting(true); // Start init status
// Get Metamask provider
const provider = new ethers.providers.Web3Provider(window.ethereum);
const ethereumProvider: EthereumProvider = new EthersAdapter(provider);
// Get Metamask ethAccount
await provider.send("eth_requestAccounts", []);
const mmSigner = provider.getSigner();
const mmAddress = EthAddress.fromString(await mmSigner.getAddress());
setEthAccount(mmAddress);
// Initialize SDK
const sdk = await createAztecSdk(ethereumProvider, {
serverUrl: "http://localhost:8081", // local devnet, run `yarn devnet` to start
pollInterval: 2000,
debug: "bb:*",
});
await sdk.run();
await sdk.awaitSynchronised();
console.log("Aztec SDK initialized:", sdk);
setSdk(sdk);
// Generate user's privacy keypair
// The privacy keypair (also known as account keypair) is used for en-/de-crypting values of the user's spendable funds (i.e. balance) on Aztec
// It can but is not typically used for receiving/spending funds, as the user should be able to share viewing access to his/her Aztec account via sharing his/her privacy private key
const { publicKey: accPubKey, privateKey: accPriKey } =
await sdk.generateAccountKeyPair(mmAddress);
console.log("Privacy Key:", accPriKey);
console.log("Public Key:", accPubKey.toString());
setAccountPrivateKey(accPriKey);
setAccountPublicKey(accPubKey);
if (await sdk.isAccountRegistered(accPubKey)) setUserExists(true);
// Get or generate Aztec SDK local user
let account0 = (await sdk.userExists(accPubKey))
? await sdk.getUser(accPubKey)
: await sdk.addUser(accPriKey);
setAccount0(account0);
// Generate user's spending key & signer
// The spending keypair is used for receiving/spending funds on Aztec
const { privateKey: spePriKey } = await sdk.generateSpendingKeyPair(
mmAddress
);
const schSigner = await sdk?.createSchnorrSigner(spePriKey);
console.log("Signer:", schSigner);
setSpendingSigner(schSigner);
setIniting(false); // End init status
}
} catch (e) {
console.log(e);
}
}
// Registering on Aztec enables the use of intuitive aliases for fund transfers
// It registers an human-readable alias with the user's privacy & spending keypairs
// All future funds transferred to the alias would be viewable with the privacy key and spendable with the spending key respectively
async function registerNewAccount() {
try {
const depositTokenQuantity: bigint = ethers.utils
.parseEther(amount.toString())
.toBigInt();
const txId = await registerAccount(
accountPublicKey!,
alias,
accountPrivateKey!,
spendingSigner!.getPublicKey(),
"eth",
depositTokenQuantity,
TxSettlementTime.INSTANT,
ethAccount!,
sdk!
);
console.log("Registration TXID:", txId.toString());
setTxId(txId);
} catch (e) {
console.log(e); // e.g. Reject TX
}
}
async function depositEth() {
try {
const depositTokenQuantity: bigint = ethers.utils
.parseEther(amount.toString())
.toBigInt();
console.log(ethAccount!, accountPublicKey!, depositTokenQuantity, sdk);
let txId = await depositEthToAztec(
ethAccount!,
accountPublicKey!,
depositTokenQuantity,
TxSettlementTime.INSTANT,
sdk!
);
console.log("Deposit TXID:", txId.toString());
setTxId(txId);
} catch (e) {
console.log(e); // e.g. depositTokenQuantity = 0
}
}
async function bridgeCrvLido() {
try {
const fromAmount: bigint = ethers.utils
.parseEther(amount.toString())
.toBigInt();
let txId = await aztecConnect(
account0!,
spendingSigner!,
2, // Testnet bridge id of CurveStEthBridge
fromAmount,
"ETH",
"WSTETH",
undefined,
undefined,
1e18, // Min acceptable amount of stETH per ETH
TxSettlementTime.INSTANT,
sdk!
);
console.log("Bridge TXID:", txId.toString());
setTxId(txId);
} catch (e) {
console.log(e); // e.g. fromAmount > user's balance
}
}
async function logBalance() {
// Wait for the SDK to read & decrypt notes to get the latest balances
await account0!.awaitSynchronised();
console.log(
"Balance: zkETH -",
sdk!.fromBaseUnits(
await sdk!.getBalance(account0!.id, sdk!.getAssetIdBySymbol("eth"))
),
", wstETH -",
sdk!.fromBaseUnits(await sdk!.getBalance(account0!.id, 2))
);
}
async function logBridges() {
const bridges = await fetchBridgeData();
console.log("Known bridges on local testnet:", bridges);
}
return (
<div className="App">
{hasMetamask ? (
sdk ? (
<div>
{userExists ? <div>Welcome back!</div> : ""}
{spendingSigner && !userExists ? (
<form>
<label>
Alias:
<input
type="text"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</label>
</form>
) : (
""
)}
{spendingSigner ? (
<div>
<form>
<label>
<input
type="number"
step="0.000000000000000001"
min="0.000000000000000001"
value={amount}
onChange={(e) => setAmount(e.target.valueAsNumber)}
/>
ETH
</label>
</form>
{!userExists ? (
<button onClick={() => registerNewAccount()}>
Register Aztec Account
</button>
) : (
""
)}
</div>
) : (
""
)}
{spendingSigner && account0 ? (
<div>
<button onClick={() => depositEth()}>Deposit ETH</button>
<button onClick={() => bridgeCrvLido()}>
Swap ETH to wstETH
</button>
</div>
) : (
""
)}
{accountPrivateKey ? (
<button onClick={() => logBalance()}>Log Balance</button>
) : (
""
)}
<button onClick={() => logBridges()}>Log Bridges</button>
<button onClick={() => console.log("sdk", sdk)}>Log SDK</button>
{txId ? <div>Last TX: {txId.toString()} </div> : ""}
</div>
) : (
<button onClick={() => connect()}>Connect Metamask</button>
)
) : (
// TODO: Fix rendering of this. Not rendered, reason unknown.
"Metamask is not detected. Please make sure it is installed and enabled."
)}
{initing ? <div>Initializing...</div> : ""}
</div>
);
};
export default App;