-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlbpStarter.html
More file actions
1104 lines (1060 loc) · 56.9 KB
/
lbpStarter.html
File metadata and controls
1104 lines (1060 loc) · 56.9 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LBP Starter - Circles Tools</title>
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<style>
body {
margin: 0;
font-family: "DM Sans", sans-serif;
background: #fff7f5;
color: #191568;
line-height: 1.3;
}
header {
background: #191568;
color: #fff;
padding: 20px;
text-align: center;
}
h1 {
margin: 0;
font-weight: 600;
font-size: 1.5rem;
}
p {
margin: 0.5rem 0 0;
font-weight: 400;
}
.container {
max-width: 800px;
margin: 40px auto;
padding: 0 20px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: 600;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-family: inherit;
}
button {
background: #191568;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-weight: 600;
}
button:hover {
background: #4a3bc4;
}
.status {
margin-top: 20px;
padding: 10px;
border-radius: 4px;
display: none;
}
.status.success {
background: #e6ffe6;
color: #006600;
display: block;
}
.status.error {
background: #ffe6e6;
color: #cc0000;
display: block;
}
.connection-status {
margin: 20px 0;
padding: 10px;
border-radius: 4px;
background: #f0f0f0;
}
.connection-status.connected {
background: #e6ffe6;
color: #006600;
}
.connection-status.disconnected {
background: #ffe6e6;
color: #cc0000;
}
.advanced-toggle {
margin: 20px 0;
text-align: center;
}
.advanced-toggle button {
background: none;
color: #191568;
border: 1px solid #191568;
padding: 5px 15px;
}
.advanced-toggle button:hover {
background: #f0f0f0;
}
.advanced-params {
display: none;
border-top: 1px solid #ddd;
padding-top: 20px;
margin-top: 20px;
}
.advanced-params.visible {
display: block;
}
</style>
</head>
<body>
<header>
<h1>LBP Starter</h1>
<p>Create and manage Liquidity Bootstrapping Pools</p>
</header>
<div class="container">
<div id="connectionStatus" class="connection-status disconnected">
Not connected to MetaMask
</div>
<!-- Continue with existing LBP Starter -->
<div style="margin-bottom: 30px; border: 1px solid #ddd; padding: 20px; border-radius: 8px;">
<h3>Continue with Existing LBP Starter</h3>
<form id="existingStarterForm" style="display: flex; gap: 10px; align-items: flex-end;">
<div style="flex: 1;">
<label for="existingStarterAddress">LBP Starter Address:</label>
<input type="text" id="existingStarterAddress" placeholder="0x..." style="width: 100%;">
</div>
<button type="submit">Check Status</button>
</form>
<div id="existingStarterStatus"></div>
</div>
<form id="lbpForm">
<div class="form-group">
<label for="groupAddress">Group Address:</label>
<select id="groupSelect" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; font-family:inherit;"></select>
<input type="text" id="groupAddress" style="display:none; margin-top:8px;" placeholder="Paste group address" />
<div id="groupTokenName" style="margin-top:4px; color:#666; font-size:0.95em;"></div>
</div>
<div class="form-group">
<label for="assetAddress">Asset Address:</label>
<select id="assetSelect" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; font-family:inherit;">
<option value="0xaf204776c7245bf4147c2612bf6e5972ee483701">sDAI</option>
<option value="0x9c58bacc331c9aa871afd802db6379a98e80cedb">GNO</option>
<option value="0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1">WETH</option>
<option value="0x8e5bbbb09ed1ebde8674cda39a0c169401db4252">WBTC</option>
<option value="custom">Custom...</option>
</select>
<input type="text" id="assetAddress" style="display:none; margin-top:8px;" placeholder="Paste ERC20 address" />
<div id="assetName" style="margin-top:4px; color:#666; font-size:0.95em;"></div>
<div id="assetPrice" style="margin-top:4px; color:#666; font-size:0.95em;"></div>
</div>
<div class="form-group">
<label for="groupAmount">Group Amount (CRC):</label>
<input type="number" id="groupAmount" required step="any" value="480">
</div>
<div class="form-group">
<label for="groupPrice">Group Price (USD):</label>
<input type="number" id="groupPrice" required step="any" value="0.02">
</div>
<div class="form-group">
<label for="assetAmount" id="assetAmountLabel">Asset Amount (sDAI):</label>
<input type="number" id="assetAmount" required step="any" value="1000">
</div>
<div class="advanced-toggle">
<button type="button" id="toggleAdvanced">Show Advanced Parameters</button>
</div>
<div class="advanced-params" id="advancedParams">
<div class="form-group">
<label for="groupInitWeight">Group Initial Weight (0-100):</label>
<input type="number" id="groupInitWeight" min="0" max="100" value="80">
</div>
<div class="form-group">
<label for="groupFinalWeight">Group Final Weight (0-100):</label>
<input type="number" id="groupFinalWeight" min="0" max="100" value="20">
</div>
<div class="form-group">
<label for="swapFee">Swap Fee (0-100):</label>
<input type="number" id="swapFee" min="0" max="100" value="1">
</div>
<div class="form-group">
<label for="updateWeightDuration">Update Weight Duration (in seconds):</label>
<input type="number" id="updateWeightDuration" value="86400">
</div>
</div>
<button type="submit">Create LBP Starter</button>
</form>
<div id="status" class="status"></div>
<div id="starterStatus"></div>
</div>
<script src="https://unpkg.com/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<script>
// Wait for ethers to be available
window.addEventListener('load', async function() {
if (typeof ethers === 'undefined') {
console.error('ethers.js failed to load');
return;
}
const LBP_STARTER_ADDRESS = '0x3b36d73506c3e75fcacb27340faa38ade1cbaf0a';
const SDAI_ADDRESS = '0xaf204776c7245bf4147c2612bf6e5972ee483701';
// Connection status handling
const connectionStatus = document.getElementById('connectionStatus');
async function checkConnection() {
if (typeof window.ethereum === 'undefined') {
connectionStatus.textContent = 'MetaMask is not installed';
connectionStatus.className = 'connection-status disconnected';
return false;
}
try {
// Request account access
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
connectionStatus.textContent = `Connected: ${account}`;
connectionStatus.className = 'connection-status connected';
return true;
} catch (error) {
connectionStatus.textContent = 'Failed to connect to MetaMask';
connectionStatus.className = 'connection-status disconnected';
return false;
}
}
// Check connection on page load
await checkConnection();
// Handle account changes
if (window.ethereum) {
window.ethereum.on('accountsChanged', function (accounts) {
if (accounts.length === 0) {
connectionStatus.textContent = 'Not connected to MetaMask';
connectionStatus.className = 'connection-status disconnected';
} else {
connectionStatus.textContent = `Connected: ${accounts[0]}`;
connectionStatus.className = 'connection-status connected';
}
});
}
// Toggle advanced parameters
document.getElementById('toggleAdvanced').addEventListener('click', function() {
const advancedParams = document.getElementById('advancedParams');
const button = this;
if (advancedParams.classList.contains('visible')) {
advancedParams.classList.remove('visible');
button.textContent = 'Show Advanced Parameters';
} else {
advancedParams.classList.add('visible');
button.textContent = 'Hide Advanced Parameters';
}
});
// Helper: format ether
function formatEther(val) {
try { return ethers.utils.formatEther(val); } catch { return val; }
}
// Helper: open CowSwap link
function getCowSwapLink(token, to, amount) {
// sDAI on Gnosis: 0xaf204776c7245bf4147c2612bf6e5972ee483701
// CowSwap: https://swap.cow.fi/#/1/swap
// We'll use Gnosis chain (chainId=100)
// CowSwap expects amount in wei
return `https://swap.cow.fi/#/100/swap/${token}-${to}?sellAmountBeforeFee=${amount}`;
}
// ABI for LBP Starter instance
const LBP_STARTER_INSTANCE_ABI = [
{"inputs":[],"name":"ASSET","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"ASSET_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"GROUP","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"GROUP_AMOUNT","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"balanceAsset","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"balanceGroup","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"groupLBP","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"createGroupLBP","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"}
];
async function checkStarterStatus(starterAddress) {
const statusDiv = document.getElementById('starterStatus') || document.getElementById('existingStarterStatus');
statusDiv.innerHTML = 'Loading...';
try {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const contract = new ethers.Contract(starterAddress, LBP_STARTER_INSTANCE_ABI, signer);
// Fetch all relevant info
const [asset, assetAmount, group, groupAmount, balanceAsset, balanceGroup, groupLBP] = await Promise.all([
contract.ASSET(),
contract.ASSET_AMOUNT(),
contract.GROUP(),
contract.GROUP_AMOUNT(),
contract.balanceAsset(),
contract.balanceGroup(),
contract.groupLBP()
]);
// Update asset dropdown to match the asset in the starter (if present in options)
if (assetSelect) {
let found = false;
for (let i = 0; i < assetSelect.options.length; i++) {
if (assetSelect.options[i].value.toLowerCase() === asset.toLowerCase()) {
assetSelect.value = asset;
assetAddressInput.style.display = 'none';
found = true;
break;
}
}
if (!found) {
assetSelect.value = 'custom';
assetAddressInput.value = asset;
assetAddressInput.style.display = '';
}
updateAssetName();
}
let html = `<b>LBP Starter Status</b><br>`;
html += `<b>Asset:</b> ${asset} <span id='statusAssetName' style='color:#666;'></span><br>`;
html += `<b>Asset Required:</b> ${formatEther(assetAmount)}<br>`;
html += `<b>Asset Sent:</b> ${formatEther(balanceAsset)}<br>`;
html += `<b>Group:</b> ${group}<br>`;
html += `<b>Group Required:</b> ${formatEther(groupAmount)}<br>`;
html += `<b>Group Sent:</b> ${formatEther(balanceGroup)}<br>`;
if (groupLBP && groupLBP !== ethers.constants.AddressZero) {
html += `<div style='margin-top:10px; color:green;'><b>LBP Created!</b><br>LBP Address: ${groupLBP}</div>`;
statusDiv.innerHTML = html;
// Show asset name in status
fetchAndShowAssetName(asset, 'statusAssetName', false);
return;
}
// What is missing?
let missing = [];
if (balanceAsset.lt(assetAmount)) missing.push('asset');
if (balanceGroup.lt(groupAmount)) missing.push('group');
if (missing.length === 0) {
html += `<div style='margin-top:10px;'><button id='createLBPBtn'>Create LBP</button></div>`;
} else {
if (missing.includes('asset')) {
html += `<div style='margin-top:10px;'><b>Send Asset (e.g. sDAI):</b><br>`;
html += `<button id='sendAssetBtn'>Send from Wallet</button></div>`;
}
if (missing.includes('group')) {
// Calculate missing CRC in whole units
const missingCRC = groupAmount.sub(balanceGroup);
const missingCRCWhole = ethers.utils.formatUnits(missingCRC, 18).replace(/\.0+$/, '');
html += `<div style='margin-top:10px;'><b>Send Group Token:</b><br>`;
html += `<a href='https://app.gnosis.io/transfer/${starterAddress}/crc/${missingCRCWhole}' target='_blank'>Send via Gnosis</a>`;
html += `</div>`;
}
}
statusDiv.innerHTML = html;
// Show asset name in status
fetchAndShowAssetName(asset, 'statusAssetName', false);
// Add event listeners for buttons
const createLBPBtn = document.getElementById('createLBPBtn');
if (createLBPBtn) {
createLBPBtn.onclick = async function() {
statusDiv.innerHTML += '<br>Sending transaction...';
try {
const tx = await contract.createGroupLBP();
await tx.wait();
statusDiv.innerHTML += '<br>LBP created! Reload status.';
} catch (e) {
statusDiv.innerHTML += `<br>Error: ${e.message}`;
}
};
}
const sendAssetBtn = document.getElementById('sendAssetBtn');
if (sendAssetBtn) {
sendAssetBtn.onclick = async function() {
statusDiv.innerHTML += '<br>Sending asset...';
try {
// ERC20 ABI
const erc20 = new ethers.Contract(asset, ["function transfer(address to, uint256 amount) public returns (bool)"], signer);
const tx = await erc20.transfer(starterAddress, assetAmount.sub(balanceAsset));
await tx.wait();
statusDiv.innerHTML += '<br>Asset sent! Reload status.';
} catch (e) {
statusDiv.innerHTML += `<br>Error: ${e.message}`;
}
};
}
const sendGroupBtn = document.getElementById('sendGroupBtn');
if (sendGroupBtn) {
sendGroupBtn.onclick = async function() {
statusDiv.innerHTML += '<br>Sending group token...';
try {
// ERC20 ABI
const erc20 = new ethers.Contract(group, ["function transfer(address to, uint256 amount) public returns (bool)"], signer);
const tx = await erc20.transfer(starterAddress, groupAmount.sub(balanceGroup));
await tx.wait();
statusDiv.innerHTML += '<br>Group token sent! Reload status.';
} catch (e) {
statusDiv.innerHTML += `<br>Error: ${e.message}`;
}
};
}
} catch (e) {
statusDiv.innerHTML = `<span style='color:red;'>Error: ${e.message}</span>`;
}
}
// Existing starter form
document.getElementById('existingStarterForm').addEventListener('submit', async (e) => {
e.preventDefault();
const addr = document.getElementById('existingStarterAddress').value.trim();
if (!ethers.utils.isAddress(addr)) {
document.getElementById('existingStarterStatus').innerHTML = '<span style="color:red;">Invalid address</span>';
return;
}
await checkStarterStatus(addr);
});
// After creation, show starter status
async function showNewStarterStatus(newStarterAddress) {
document.getElementById('starterStatus').innerHTML = '';
await checkStarterStatus(newStarterAddress);
}
document.getElementById('lbpForm').addEventListener('submit', async (e) => {
e.preventDefault();
const status = document.getElementById('status');
document.getElementById('starterStatus').innerHTML = '';
try {
// Check if MetaMask is installed
if (typeof window.ethereum === 'undefined') {
throw new Error('Please install MetaMask to use this feature');
}
// Get form values
const groupAddress = getCurrentGroupAddress();
const assetAddress = getCurrentAssetAddress();
const groupAmount = document.getElementById('groupAmount').value;
const assetAmount = document.getElementById('assetAmount').value;
// Create contract instance
const contractABI = [
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "InvalidAmount",
"type": "error"
},
{
"inputs": [],
"name": "InvalidFinalWeight",
"type": "error"
},
{
"inputs": [],
"name": "InvalidInitWeight",
"type": "error"
},
{
"inputs": [],
"name": "InvalidSwapFee",
"type": "error"
},
{
"inputs": [],
"name": "OnlyBaseGroupsAreSupported",
"type": "error"
},
{
"inputs": [],
"name": "OnlyStarter",
"type": "error"
},
{
"inputs": [],
"name": "OnlyTwoTokenLBPSupported",
"type": "error"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "creator",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "group",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "lbp",
"type": "address"
}
],
"name": "GroupLBPCreated",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "address",
"name": "creator",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "group",
"type": "address"
},
{
"indexed": true,
"internalType": "address",
"name": "asset",
"type": "address"
},
{
"indexed": false,
"internalType": "address",
"name": "lbpStarter",
"type": "address"
},
{
"indexed": false,
"internalType": "uint256",
"name": "groupAmount",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "assetAmount",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "groupInitWeight",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "groupFinalWeight",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "swapFee",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "updateWeightDuration",
"type": "uint256"
}
],
"name": "LBPStarterCreated",
"type": "event"
},
{
"inputs": [],
"name": "BALANCER_WEIGHTED_MATH",
"outputs": [
{
"internalType": "contract IExternalWeightedMath",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "BASE_GROUP_FACTORY",
"outputs": [
{
"internalType": "contract IBaseGroupFactory",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "HUB_V2",
"outputs": [
{
"internalType": "contract IHub",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "LBP_FACTORY",
"outputs": [
{
"internalType": "contract INoProtocolFeeLiquidityBootstrappingPoolFactory",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "VAULT",
"outputs": [
{
"internalType": "address",
"name": "",
"type": "address"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "group",
"type": "address"
},
{
"internalType": "address",
"name": "asset",
"type": "address"
},
{
"internalType": "uint256",
"name": "groupAmount",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "assetAmount",
"type": "uint256"
}
],
"name": "createLBPStarter",
"outputs": [
{
"internalType": "address",
"name": "lbpStarter",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"internalType": "address",
"name": "group",
"type": "address"
},
{
"internalType": "address",
"name": "asset",
"type": "address"
},
{
"internalType": "uint256",
"name": "groupAmount",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "assetAmount",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "groupInitWeight",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "groupFinalWeight",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "swapFee",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "updateWeightDuration",
"type": "uint256"
}
],
"name": "createLBPStarter",
"outputs": [
{
"internalType": "address",
"name": "lbpStarter",
"type": "address"
}
],
"stateMutability": "nonpayable",
"type": "function"
}
];
console.log('Creating contract instance...');
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
console.log('Provider and signer created');
const contract = new ethers.Contract(LBP_STARTER_ADDRESS, contractABI, signer);
console.log('Contract instance created:', contract);
console.log('Available functions:', Object.keys(contract.functions));
let tx;
if (document.getElementById('advancedParams').classList.contains('visible')) {
// Advanced parameters
const groupInitWeight = document.getElementById('groupInitWeight').value;
const groupFinalWeight = document.getElementById('groupFinalWeight').value;
const swapFee = document.getElementById('swapFee').value;
const updateWeightDuration = document.getElementById('updateWeightDuration').value;
console.log('Calling createLBPStarter with advanced parameters...');
tx = await contract['createLBPStarter(address,address,uint256,uint256,uint256,uint256,uint256,uint256)'](
groupAddress,
assetAddress,
ethers.utils.parseEther(groupAmount),
ethers.utils.parseEther(assetAmount),
groupInitWeight,
groupFinalWeight,
swapFee,
updateWeightDuration
);
} else {
// Simple parameters
console.log('Calling createLBPStarter with simple parameters...');
tx = await contract['createLBPStarter(address,address,uint256,uint256)'](
groupAddress,
assetAddress,
ethers.utils.parseEther(groupAmount),
ethers.utils.parseEther(assetAmount)
);
}
status.textContent = 'Transaction sent! Waiting for confirmation...';
status.className = 'status success';
const receipt = await tx.wait();
// Find the LBPStarterCreated event
const event = receipt.events.find(e => e.event === 'LBPStarterCreated');
if (event) {
const lbpStarterAddress = event.args.lbpStarter;
status.textContent = `LBP Starter created successfully! Address: ${lbpStarterAddress}`;
status.className = 'status success';
await showNewStarterStatus(lbpStarterAddress);
} else {
status.textContent = 'Transaction successful but no LBPStarterCreated event found';
}
} catch (error) {
status.textContent = `Error: ${error.message}`;
status.className = 'status error';
}
});
// --- Group Price and Asset Amount Sync Logic ---
const groupAmountInput = document.getElementById('groupAmount');
const groupPriceInput = document.getElementById('groupPrice');
const assetAmountInput = document.getElementById('assetAmount');
let lastEdited = null; // 'groupPrice' or 'assetAmount'
let assetPriceInWxDAI = null; // in wxDAI
let wxDAIPriceUSD = null; // in USD
// Fetch wxDAI price in USD from Coingecko
async function fetchWxDAIPriceUSD() {
try {
const res = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=wrapped-xdai&vs_currencies=usd');
const data = await res.json();
wxDAIPriceUSD = data['wrapped-xdai']?.usd || 0;
} catch (e) {
wxDAIPriceUSD = 0;
}
}
await fetchWxDAIPriceUSD();
// Helper: get asset price in USD
function getAssetPriceUSD() {
if (!assetPriceInWxDAI || !wxDAIPriceUSD) return null;
return assetPriceInWxDAI * wxDAIPriceUSD;
}
// Update asset amount based on group amount and group price
function updateAssetAmountFromGroupPrice() {
const groupAmount = parseFloat(groupAmountInput.value) || 0;
const groupPrice = parseFloat(groupPriceInput.value) || 0;
const assetPriceUSD = getAssetPriceUSD();
if (!assetPriceUSD || assetPriceUSD === 0) return;
// 1% of asset value = groupAmount * groupPrice
// assetAmount * assetPriceUSD * 0.01 = groupAmount * groupPrice
// assetAmount = (groupAmount * groupPrice) / (assetPriceUSD * 0.01)
const assetAmount = (groupAmount * groupPrice) / (assetPriceUSD * 0.01);
assetAmountInput.value = assetAmount ? assetAmount.toFixed(6) : '';
}
// Update group price based on asset amount
function updateGroupPriceFromAssetAmount() {
const groupAmount = parseFloat(groupAmountInput.value) || 0;
const assetAmount = parseFloat(assetAmountInput.value) || 0;
const assetPriceUSD = getAssetPriceUSD();
if (!assetPriceUSD || assetPriceUSD === 0 || groupAmount === 0) return;
// assetAmount * assetPriceUSD * 0.01 = groupAmount * groupPrice
// groupPrice = (assetAmount * assetPriceUSD * 0.01) / groupAmount
const groupPrice = (assetAmount * assetPriceUSD * 0.01) / groupAmount;
groupPriceInput.value = groupPrice ? groupPrice.toFixed(6) : '';
}
// When group price changes
groupPriceInput.addEventListener('input', function() {
lastEdited = 'groupPrice';
updateAssetAmountFromGroupPrice();
});
// When asset amount changes
assetAmountInput.addEventListener('input', function() {
lastEdited = 'assetAmount';
updateGroupPriceFromAssetAmount();
});
// When group amount changes
groupAmountInput.addEventListener('input', function() {
if (lastEdited === 'assetAmount') {
updateGroupPriceFromAssetAmount();
} else {
updateAssetAmountFromGroupPrice();
}
});
// When asset price or wxDAI price changes, recalculate
async function recalcOnPriceUpdate() {
await fetchWxDAIPriceUSD();
if (lastEdited === 'assetAmount') {
updateGroupPriceFromAssetAmount();
} else {
updateAssetAmountFromGroupPrice();
}
}
// Patch fetchAssetPriceInWxDAI to update assetPriceInWxDAI and recalc
fetchAssetPriceInWxDAI = async function(assetAddress) {
const wxDAI = '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d';
if (!ethers.utils.isAddress(assetAddress)) {
document.getElementById('assetPrice').textContent = '';
assetPriceInWxDAI = null;
return;
}
if (assetAddress.toLowerCase() === wxDAI.toLowerCase()) {
document.getElementById('assetPrice').textContent = '1 wxDAI = 1 wxDAI';
assetPriceInWxDAI = 1;
await recalcOnPriceUpdate();
return;
}
try {
const query = `{ sorGetSwapPaths( chain: GNOSIS, swapAmount: "0.1", swapType: EXACT_IN, tokenIn: "${assetAddress}", tokenOut: "${wxDAI}" ) { returnAmount } }`;
const response = await fetch("https://api-v3.balancer.fi/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query })
});
const data = await response.json();
if (data.data?.sorGetSwapPaths?.returnAmount) {
// The API returns the price for 0.1 asset, so multiply by 10 for 1 asset
const price = Number(data.data.sorGetSwapPaths.returnAmount) * 10;
assetPriceInWxDAI = price;
document.getElementById('assetPrice').textContent = `1 asset ≈ ${price.toFixed(6)} wxDAI`;
await recalcOnPriceUpdate();
return;
}
document.getElementById('assetPrice').textContent = 'Price not available.';
assetPriceInWxDAI = null;
await recalcOnPriceUpdate();
} catch (e) {
document.getElementById('assetPrice').textContent = 'Price not available.';
assetPriceInWxDAI = null;
await recalcOnPriceUpdate();
}
};
// Asset dropdown logic
const assetSelect = document.getElementById('assetSelect');
const assetAddressInput = document.getElementById('assetAddress');
function getCurrentAssetAddress() {
if (assetSelect.value === 'custom') {
return assetAddressInput.value;
} else {
return assetSelect.value;
}
}
function updateAssetName() {
const assetAddr = getCurrentAssetAddress();
fetchAndShowAssetName(assetAddr, 'assetName', true);
fetchAssetPriceInWxDAI(assetAddr);
}
// Show/hide custom input
assetSelect.addEventListener('change', function() {
if (assetSelect.value === 'custom') {
assetAddressInput.style.display = '';
assetAddressInput.required = true;
} else {
assetAddressInput.style.display = 'none';
assetAddressInput.required = false;
}
updateAssetName();
});
assetAddressInput.addEventListener('input', updateAssetName);
assetSelect.value = '0xaf204776c7245bf4147c2612bf6e5972ee483701'; // default to sDAI
updateAssetName();
// GROUP DROPDOWN LOGIC
const groupSelect = document.getElementById('groupSelect');
const groupAddressInput = document.getElementById('groupAddress');
function getCurrentGroupAddress() {
if (groupSelect.value === 'custom') {
return groupAddressInput.value;
} else {
return groupSelect.value;
}
}
function updateGroupTokenName() {
fetchAndShowGroupTokenName(getCurrentGroupAddress());
}
groupSelect.addEventListener('change', function() {
if (groupSelect.value === 'custom') {
groupAddressInput.style.display = '';
groupAddressInput.required = true;
} else {
groupAddressInput.style.display = 'none';
groupAddressInput.required = false;
}
updateGroupTokenName();
});
groupAddressInput.addEventListener('input', updateGroupTokenName);
// Fetch default groups (like in groupChecker.html)
async function fetchDefaultGroups() {
const rpcEndpoint = "https://rpc.aboutcircles.com/";
const requestBody = {
jsonrpc: "2.0",
id: 1,
method: "circles_query",
params: [
{
Namespace: "V_CrcV2",
Table: "TrustRelations",
Columns: [],
Filter: [
{
Type: "FilterPredicate",
FilterType: "Equals",
Column: "truster",
Value: "0x0afd8899bca011bb95611409f09c8efbf6b169cf",
},
],
},
],
};
try {
const response = await fetch(rpcEndpoint, {
method: "POST",