-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathreplenishMyCRC.html
More file actions
495 lines (434 loc) · 16.1 KB
/
replenishMyCRC.html
File metadata and controls
495 lines (434 loc) · 16.1 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Replenish My CRC</title>
<script src="https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 2rem;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
button {
background: #191568;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
padding: 10px;
width: 100%;
max-width: 400px;
margin: 5px 0;
}
button:hover {
background: #4a39cc;
}
button:disabled {
background: #ccc;
cursor: not-allowed;
}
.section {
margin-bottom: 20px;
padding: 15px;
border: 1px solid #eee;
border-radius: 4px;
}
.error {
color: red;
margin: 10px 0;
}
.success {
color: green;
margin: 10px 0;
}
#amountControls {
display: none;
}
.slider-container {
margin: 20px 0;
}
input[type="range"] {
width: 100%;
max-width: 400px;
}
input[type="number"] {
padding: 8px;
margin: 5px 0;
width: 100%;
max-width: 382px; /* 400px - 2*padding */
}
pre {
background: #f5f5f5;
padding: 10px;
overflow-x: auto;
border-radius: 4px;
}
.info {
background: #f0f9ff;
border-left: 4px solid #3b82f6;
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<h1>Replenish my CRC</h1>
Tool to replenish your balance of your own CRC.
<div class="section">
<h2>1. Connect Wallet</h2>
<button id="connectButton">Connect Wallet</button>
<div id="walletStatus"></div>
</div>
<div class="section">
<h2>2. Check max replenishable amount</h2>
<div class="info">
This will check the maximum amount you can transfer to
yourself using your own tokens.
</div>
<button id="checkPathButton">Check</button>
<div id="maxFlowResult"></div>
</div>
<div id="amountControls" class="section">
<h2>3. Select amount to replenish</h2>
<div class="slider-container">
<input
type="range"
id="amountSlider"
min="0"
max="100"
step="0.000001"
/>
<input type="number" id="amountInput" step="0.000001"/>
<div id="amountDisplay"></div>
</div>
<button id="executeButton">Replenish</button>
<div id="executionStatus"></div>
<pre id="calldata"></pre>
</div>
</div>
<script>
// Constants
const API_ENDPOINT = "https://rpc.aboutcircles.com/";
const CIRCLES_HUB_ADDRESS =
"0xc12C1E50ABB450d6205Ea2C3Fa861b3B834d13e8";
// Just the operateFlowMatrix function ABI
const CIRCLES_HUB_ABI = [
{
inputs: [
{
internalType: "address[]",
name: "_flowVertices",
type: "address[]",
},
{
components: [
{
internalType: "uint16",
name: "streamSinkId",
type: "uint16",
},
{
internalType: "uint192",
name: "amount",
type: "uint192",
},
],
internalType: "struct TypeDefinitions.FlowEdge[]",
name: "_flow",
type: "tuple[]",
},
{
components: [
{
internalType: "uint16",
name: "sourceCoordinate",
type: "uint16",
},
{
internalType: "uint16[]",
name: "flowEdgeIds",
type: "uint16[]",
},
{
internalType: "bytes",
name: "data",
type: "bytes",
},
],
internalType: "struct TypeDefinitions.Stream[]",
name: "_streams",
type: "tuple[]",
},
{
internalType: "bytes",
name: "_packedCoordinates",
type: "bytes",
},
],
name: "operateFlowMatrix",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
];
let provider, signer, hubContract;
let maxFlow = "0";
let currentAddress = null;
// Helper function to format Wei to ETH
function formatWei(wei) {
return ethers.utils.formatUnits(wei, 18);
}
// Helper function to parse ETH to Wei
function parseEth(eth) {
return ethers.utils.parseUnits(eth.toString(), 18);
}
// Connect wallet function
async function connectWallet() {
try {
if (typeof window.ethereum === "undefined") {
throw new Error("Please install MetaMask");
}
provider = new ethers.providers.Web3Provider(
window.ethereum,
);
await provider.send("eth_requestAccounts", []);
signer = provider.getSigner();
currentAddress = await signer.getAddress();
document.getElementById("walletStatus").innerHTML =
`<div class="success">Connected: ${currentAddress}</div>`;
hubContract = new ethers.Contract(
CIRCLES_HUB_ADDRESS,
CIRCLES_HUB_ABI,
signer,
);
} catch (error) {
document.getElementById("walletStatus").innerHTML =
`<div class="error">Error: ${error.message}</div>`;
}
}
// Find path function
async function findPath(amount = null) {
if (!currentAddress) {
return null; // Silent return if no wallet is connected
}
const params = {
Source: currentAddress,
Sink: currentAddress, // Send to self
TargetFlow: amount || parseEth("100000000000").toString(), // Use large number for max flow check
WithWrap: true,
ToTokens: [currentAddress], // Specify connected address as return token
};
const response = await fetch(API_ENDPOINT, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
jsonrpc: "2.0",
id: 0,
method: "circlesV2_findPath",
params: [params],
}),
});
const data = await response.json();
if (data.error) {
throw new Error(data.error.message);
}
return data.result;
}
// Helper to pack coordinates array into bytes
function packCoordinates(coordinates) {
let packedBuffer = "0x";
coordinates.forEach((coord) => {
let hex = coord.toString(16).padStart(4, "0");
packedBuffer += hex;
});
return packedBuffer;
}
/**
* Build the four arguments expected by Hub.operateFlowMatrix()
* from a Pathfinder result.
*
* @param {object} pathData – result of circlesV2_findPath
* @param {string} from – source avatar (connected wallet)
* @param {string} to – sink avatar (usually = from)
* @param {string} value – target flow (dec / hex string)
*
* @returns {{
* _flowVertices: string[],
* _flow: { streamSinkId: number, amount: string|bigint }[],
* _streams: { sourceCoordinate: number, flowEdgeIds: number[], data: Uint8Array }[],
* _packedCoordinates: Uint8Array,
* sourceCoordinate: number
* }}
*/
function generateFlowMatrixParams(pathData, from, to, value) {
// ────── guards ───────────────────────────────────────────────────────
if (!pathData || !Array.isArray(pathData.transfers) || !pathData.transfers.length)
throw new Error('Pathfinder returned no transfers');
from = from.toLowerCase();
to = to.toLowerCase();
const expectedValue = BigInt(value);
// ────── 1. normalise transfers + collect all addresses ───────────────
const addrs = new Set([from, to]);
const transfers = pathData.transfers.map(t => {
const norm = {
from: t.from.toLowerCase(),
to: t.to.toLowerCase(),
tokenOwner: t.tokenOwner.toLowerCase(),
value: t.value // string
};
addrs.add(norm.from);
addrs.add(norm.to);
addrs.add(norm.tokenOwner);
return norm;
});
// ────── 2. strictly-ascending vertices (numeric compare) ─────────────
const flowVertices = [...addrs].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : 1));
// lookup[address] → coordinate
const lookUpMap = Object.create(null);
flowVertices.forEach((addr, idx) => (lookUpMap[addr] = idx));
// ────── 3. flow edges, mark edges that reach the sink ────────────────
const flowEdges = transfers.map(t => ({
streamSinkId: (t.to === to) ? 1 : 0, // only edges that end in 'to' get 1
amount: BigInt(t.value) // uint192 fits in JS BigInt
}));
// ensure *at least* one edge is terminal
if (!flowEdges.some(e => e.streamSinkId === 1)) {
const lastIdx = transfers.map(t => t.to).lastIndexOf(to);
(lastIdx >= 0 ? flowEdges[lastIdx] : flowEdges[flowEdges.length - 1]).streamSinkId = 1;
}
// verify sum( terminal amounts ) == value requested
const terminalSum = flowEdges
.filter(e => e.streamSinkId === 1)
.reduce((s, e) => s + e.amount, 0n);
if (terminalSum !== expectedValue)
throw new Error(`terminal amount ${terminalSum} ≠ requested ${expectedValue}`);
// ────── 4. one Stream referencing all terminal edges ─────────────────
const flowEdgeIds = flowEdges
.map((e, idx) => (e.streamSinkId === 1 ? idx : -1))
.filter(idx => idx !== -1);
const stream = {
sourceCoordinate: lookUpMap[from],
flowEdgeIds: flowEdgeIds,
data: new Uint8Array() // no user-data
};
// ────── 5. coordinate triples (tokenId, src, dst) ────────────────────
const coords = [];
transfers.forEach(t => {
coords.push(
lookUpMap[t.tokenOwner],
lookUpMap[t.from],
lookUpMap[t.to]
);
});
// pack uint16[] → Uint8Array big-endian
const packed = new Uint8Array(coords.length * 2);
coords.forEach((c, i) => {
packed[2 * i] = c >> 8;
packed[2 * i + 1] = c & 0xff;
});
// ────── 6. return exactly what operateFlowMatrix expects ─────────────
return {
_flowVertices: flowVertices,
_flow: flowEdges,
_streams: [stream],
_packedCoordinates: packed,
sourceCoordinate: lookUpMap[from] // optional convenience
};
}
// Event Listeners
document
.getElementById("connectButton")
.addEventListener("click", connectWallet);
document
.getElementById("checkPathButton")
.addEventListener("click", async () => {
if (!currentAddress) {
document.getElementById("maxFlowResult").innerHTML =
`<div class="error">Please connect your wallet first</div>`;
return;
}
try {
const result = await findPath();
maxFlow = result.maxFlow;
const maxFlowEth = formatWei(maxFlow);
document.getElementById("maxFlowResult").innerHTML =
`<div class="success">Maximum available: ${maxFlowEth} CRC</div>`;
// Show and setup amount controls
const amountControls =
document.getElementById("amountControls");
amountControls.style.display = "block";
const slider = document.getElementById("amountSlider");
const input = document.getElementById("amountInput");
slider.max = maxFlowEth;
slider.value = maxFlowEth;
input.value = maxFlowEth;
document.getElementById("amountDisplay").textContent =
`Selected: ${maxFlowEth} CRC`;
} catch (error) {
document.getElementById("maxFlowResult").innerHTML =
`<div class="error">Error: ${error.message}</div>`;
}
});
// Sync slider and input
document
.getElementById("amountSlider")
.addEventListener("input", (e) => {
const value = e.target.value;
document.getElementById("amountInput").value = value;
document.getElementById("amountDisplay").textContent =
`Selected: ${value} CRC`;
});
document
.getElementById("amountInput")
.addEventListener("input", (e) => {
const value = Math.min(e.target.value, formatWei(maxFlow));
document.getElementById("amountSlider").value = value;
document.getElementById("amountDisplay").textContent =
`Selected: ${value} CRC`;
});
document
.getElementById("executeButton")
.addEventListener("click", async () => {
if (!currentAddress) {
document.getElementById("executionStatus").innerHTML =
`<div class="error">Please connect your wallet first</div>`;
return;
}
try {
const amount = parseEth(
document.getElementById("amountInput").value,
);
const pathData = await findPath(amount.toString());
const params = generateFlowMatrixParams(pathData, currentAddress, currentAddress, amount.toString());
// document.getElementById("calldata").textContent =
// JSON.stringify(params, null, 2);
const tx = await hubContract.operateFlowMatrix(
params._flowVertices,
params._flow,
params._streams,
params._packedCoordinates,
);
document.getElementById("executionStatus").innerHTML =
`<div class="success">Transaction submitted: ${tx.hash}</div>`;
const receipt = await tx.wait();
document.getElementById("executionStatus").innerHTML +=
`<div class="success">Transaction confirmed!</div>`;
} catch (error) {
document.getElementById("executionStatus").innerHTML =
`<div class="error">Error: ${error.message}</div>`;
}
});
</script>
</body>
</html>