-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.pas
750 lines (668 loc) · 19.9 KB
/
main.pas
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
unit main;
interface
uses
// Delphi
System.Classes,
System.Rtti,
System.SysUtils,
// FireMonkey
FMX.Controls,
FMX.Controls.Presentation,
FMX.Edit,
FMX.Forms,
FMX.Grid,
FMX.Grid.Style,
FMX.ListBox,
FMX.ScrollBox,
FMX.StdCtrls,
FMX.Types,
// Velthuis' BigNumbers
Velthuis.BigIntegers,
// web3
web3,
web3.eth.types,
// Project
asset;
type
TSetting = (
UniswapPairs, // scan for 30k Uniswap v2 LP tokens if included, otherwise no LP tokens
NFTs // scan for (erc-721 and erc-1155) NFTs using the OpenSea API, otherwise no NFTs.
);
TSettings = set of TSetting;
type
TfrmMain = class(TForm)
lblOwner: TLabel;
edtOwner: TEdit;
cboChain: TComboBox;
btnScan: TButton;
Grid: TGrid;
colCheck: TCheckColumn;
colImage: TImageColumn;
colName: TStringColumn;
colBalance: TFloatColumn;
Header: TPanel;
chkSelectAll: TCheckBox;
edtRecipient: TEdit;
lblRecipient: TLabel;
btnMigrate: TButton;
btnNew: TEditButton;
chkScanForUniswapPairs: TCheckBox;
chkScanForNFTs: TCheckBox;
chkScanForERC20s: TCheckBox;
procedure btnMigrateClick(Sender: TObject);
procedure btnNewClick(Sender: TObject);
procedure btnScanClick(Sender: TObject);
procedure cboChainChange(Sender: TObject);
procedure chkScanForChange(Sender: TObject);
procedure chkSelectAllChange(Sender: TObject);
procedure GridGetValue(Sender: TObject; const ACol, ARow: Integer;
var Value: TValue);
procedure GridSetValue(Sender: TObject; const ACol, ARow: Integer;
const Value: TValue);
private
FAssets: TAssets;
FLocked: Integer;
function Cancelled: Boolean;
function Chain: TChain;
procedure Clear;
function GetClient: IResult<IWeb3>;
procedure Count(aSettings: TSettings; callback: TProc<BigInteger, IError>);
class function Ethereum: IWeb3;
procedure Generate;
procedure Init;
procedure Lock;
function Locked: Boolean;
procedure Migrate;
procedure Owner(callback: TProc<TAddress, IError>);
procedure Recipient(callback: TProc<TAddress, IError>);
procedure Scan(aSettings: TSettings);
function Settings: TSettings;
class procedure Queue(P: TThreadProcedure);
class procedure Synchronize(P: TThreadProcedure);
procedure Unlock;
procedure Update;
public
constructor Create(aOwner: TComponent); override;
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
uses
// Delphi
System.Net.HttpClient,
System.UITypes,
// FireMonkey
FMX.BehaviorManager,
FMX.Dialogs,
FMX.Platform,
// web3
web3.error,
web3.eth,
web3.eth.infura,
web3.eth.opensea,
web3.eth.tokenlists,
web3.http,
// Project
progress;
{$I migratooor.api.key}
const
UNISWAP_PAIR_TOKENS = 'https://raw.githubusercontent.com/jab416171/uniswap-pairtokens/master/uniswap_pair_tokens.json';
//------------------------------- event handlers -------------------------------
procedure TfrmMain.btnMigrateClick(Sender: TObject);
begin
Self.Migrate;
end;
procedure TfrmMain.btnNewClick(Sender: TObject);
begin
Self.Generate;
end;
procedure TfrmMain.btnScanClick(Sender: TObject);
begin
Self.Scan(Self.Settings);
end;
procedure TfrmMain.cboChainChange(Sender: TObject);
begin
Self.Lock;
try
chkScanForERC20s.Text := 'Scan for (calculating...) ERC-20 tokens';
web3.eth.tokenlists.count(Chain, procedure(cnt: BigInteger; err: IError)
begin
Self.Queue(procedure
begin
chkScanForERC20s.Text := Format('Scan for %s known ERC-20 tokens', [cnt.ToString]);
end);
end);
chkScanForNFTs.Enabled := Chain = web3.Ethereum;
chkScanForNFTs.IsChecked := chkScanForNFTs.Enabled;
chkScanForUniswapPairs.Enabled := Chain = web3.Ethereum;
if not chkScanForUniswapPairs.Enabled then
chkScanForUniswapPairs.IsChecked := False;
finally
Self.Unlock;
end;
end;
procedure TfrmMain.chkScanForChange(Sender: TObject);
begin
if not Self.Locked then Self.Scan(Self.Settings);
end;
procedure TfrmMain.chkSelectAllChange(Sender: TObject);
begin
for var idx := 0 to FAssets.Length - 1 do
begin
FAssets[idx].Check(chkSelectAll.IsChecked);
colCheck.UpdateCell(idx);
end;
end;
procedure TfrmMain.GridGetValue(Sender: TObject; const ACol, ARow: Integer;
var Value: TValue);
begin
case ACol of
0: Value := FAssets[ARow].Checked;
1: Value := FAssets[ARow].Bitmap;
2: Value := FAssets[ARow].Name;
3: Value := FAssets[ARow].Balance;
end;
end;
procedure TfrmMain.GridSetValue(Sender: TObject; const ACol, ARow: Integer;
const Value: TValue);
begin
if ACol = 0 then FAssets[ARow].Check(Value.AsBoolean);
end;
//---------------------------------- private -----------------------------------
function TfrmMain.Cancelled: Boolean;
begin
const P = progress.Get(Self);
Result := Assigned(P) and P.Cancelled;
if Result and P.Visible then
begin
P.Close;
repeat
TThread.Sleep(100);
until not P.Visible;
end;
end;
function TfrmMain.Chain: TChain;
begin
const I = cboChain.ItemIndex;
if (I > -1) and (I < cboChain.Count) then
begin
const chain = web3.Chain(UInt32(cboChain.Items.Objects[I]));
if chain.isOk then
begin
Result := chain.Value^;
EXIT;
end;
end;
Result := web3.Ethereum;
end;
procedure TfrmMain.Clear;
begin
FAssets := [];
Grid.RowCount := 0;
chkSelectAll.Enabled := False;
chkSelectAll.IsChecked := True;
btnMigrate.Enabled := False;
Self.Invalidate;
end;
function TfrmMain.GetClient: IResult<IWeb3>;
begin
const endpoint = web3.eth.infura.endpoint(Chain, INFURA_PROJECT_ID);
if endpoint.isErr then
begin
Result := TResult<IWeb3>.Err(nil, endpoint.Error);
EXIT;
end;
const client = TWeb3.Create(Chain.SetRPC(HTTPS, endpoint.Value));
// do not approve each and every transaction individually
client.OnSignatureRequest := procedure(
const from, &to : TAddress;
const gasPrice : TWei;
const estimatedGas: BigInteger;
const callback : TSignatureRequestResult)
begin
callback(True, nil);
end;
Result := TResult<IWeb3>.Ok(client);
end;
procedure TfrmMain.Count(aSettings: TSettings; callback: TProc<BigInteger, IError>);
begin
// step #1: count the tokens on this chain that Uniswap knows about
web3.eth.tokenlists.count(Chain, procedure(cnt1: BigInteger; err: IError)
begin
( // step #2: count the Uniswap v2 LP tokens (optional)
procedure(return: TProc<BigInteger, IError>)
begin
if UniswapPairs in aSettings then
web3.eth.tokenlists.count(UNISWAP_PAIR_TOKENS, return)
else
return(0, nil);
end
)(procedure(cnt2: BigInteger; err: IError)
begin
callback(cnt1 + cnt2, err);
end);
end);
end;
class function TfrmMain.Ethereum: IWeb3;
begin
Result := TWeb3.Create(web3.Ethereum.SetRPC(HTTPS, web3.eth.infura.endpoint(web3.Ethereum, INFURA_PROJECT_ID).Value));
end;
procedure TfrmMain.Generate;
begin
const &private = TPrivateKey.Generate;
const &public = &private.GetAddress;
if &public.isErr then
begin
web3.error.show(Chain, &public.Error);
EXIT;
end;
var svc: IFMXClipboardService;
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, svc) then
svc.SetClipboard(&private.ToString);
Self.Synchronize(procedure
begin
edtRecipient.Text := string(&public.Value);
MessageDlg(
'A new wallet has been generated for you.' + #10#10 +
'Your private key has been copied to the clipboard.' + #10#10 +
'Please paste your private key in a safe place (for example: your password manager), then clear the clipboard.',
TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], 0);
end);
end;
procedure TfrmMain.Init;
const
VERSION = {$I migratooor.version};
begin
Self.Caption := Self.Caption + ' v' + VERSION;
Grid.AutoHide := TBehaviorBoolean.False;
cboChain.Items.BeginUpdate;
try
cboChain.Items.AddObject(web3.Ethereum.Name, TObject(web3.Ethereum.Id));
cboChain.Items.AddObject(web3.BNB.Name, TObject(web3.BNB.Id));
cboChain.Items.AddObject(web3.Polygon.Name, TObject(web3.Polygon.Id));
cboChain.Items.AddObject(web3.Optimism.Name, TObject(web3.Optimism.Id));
cboChain.Items.AddObject(web3.Arbitrum.Name, TObject(web3.Arbitrum.Id));
cboChain.Items.AddObject(web3.Fantom.Name, TObject(web3.Fantom.Id));
cboChain.Items.AddObject(web3.Gnosis.Name, TObject(web3.Gnosis.Id));
cboChain.Items.AddObject(web3.PulseChain.Name, TObject(web3.PulseChain.Id));
finally
cboChain.Items.EndUpdate;
end;
cboChain.ItemIndex := 0;
edtOwner.SetFocus;
end;
procedure TfrmMain.Lock;
begin
Inc(FLocked);
end;
function TfrmMain.Locked: Boolean;
begin
Result := FLocked > 0;
end;
procedure TfrmMain.Migrate;
begin
const checked = FAssets.Checked;
if checked = 0 then
begin
web3.error.show('Nothing to do.');
EXIT;
end;
Self.Owner(procedure(aOwner: TAddress; err: IError)
begin
if Assigned(err) then
begin
web3.error.show(web3.Ethereum, err);
EXIT;
end;
aOwner.ToString(Ethereum, procedure(sOwner: string; err: IError)
begin
if Assigned(err) then
begin
web3.error.show(web3.Ethereum, err);
EXIT;
end;
Self.Recipient(procedure(aRecipient: TAddress; err: IError)
begin
if Assigned(err) then
begin
web3.error.show(web3.Ethereum, err);
EXIT;
end;
aRecipient.ToString(Ethereum, procedure(sRecipient: string; err: IError)
begin
if Assigned(err) then
begin
web3.error.show(web3.Ethereum, err);
EXIT;
end;
var answer: Integer;
Self.Synchronize(procedure
begin
answer := MessageDlg(
Format('Are you sure you want to migrate %d tokens from %s to %s on the %s network?', [checked, sOwner, sRecipient, Chain.Name]),
TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0
)
end);
if answer = mrYes then
begin
const client = Self.GetClient;
if client.isErr then
begin
web3.error.show(Chain, client.Error);
EXIT;
end;
const &private = TPrivateKey.Prompt(aOwner);
if &private.isErr then
begin
if Supports(&private.Error, ICancelled) then
{ nothing }
else
web3.error.show(Chain, &private.Error);
EXIT;
end;
FAssets.Enumerate(
// foreach
procedure(idx: Integer; next: TProc)
begin
if not FAssets[idx].Checked then
begin
next;
EXIT;
end;
Self.Queue(procedure
begin
progress.Get(Self).Step('Sending transaction %d of %d. Please wait...', idx, checked);
end);
FAssets[idx].Transfer(client.Value, &private.Value, aRecipient, procedure(hash: TTxHash; err: IError)
begin
if Self.Cancelled then EXIT;
next;
end);
end,
// done
procedure
begin
progress.Get(Self).Close;
end
);
Self.Synchronize(procedure
begin
progress.Get(Self).Prompt(Format('Sending %d transactions. Please wait...', [checked]));
end);
end;
end, True);
end);
end, True);
end);
end;
procedure TfrmMain.Owner(callback: TProc<TAddress, IError>);
begin
if edtOwner.Text.Length = 0 then
callback(TAddress.Zero, nil)
else
TAddress.FromName(Ethereum, edtOwner.Text, callback);
end;
procedure TfrmMain.Recipient(callback: TProc<TAddress, IError>);
begin
TAddress.FromName(Ethereum, edtRecipient.Text, procedure(recipient: TAddress; err: IError)
begin
if Assigned(err) then
begin
callback(TAddress.Zero, err);
EXIT;
end;
if recipient.IsZero then
begin
callback(TAddress.Zero, TError.Create('Recipient address is invalid.'));
EXIT;
end;
callback(recipient, nil);
end);
end;
procedure TfrmMain.Scan(aSettings: TSettings);
begin
Self.Clear;
// step #1: resolve the owner ENS name
Self.Owner(procedure(owner: TAddress; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
web3.error.show(Chain, err);
EXIT;
end;
// step #2: count the total number of tokens we can scan
Self.Count(aSettings, procedure(cnt: BigInteger; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
web3.error.show(Chain, err);
EXIT;
end;
// step #3: get the tokens on this chain that Uniswap knows about
web3.eth.tokenlists.tokens(Chain, procedure(tokens: TTokens; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
web3.error.show(Chain, err);
EXIT;
end;
const client = Self.GetClient;
if client.isErr then
begin
web3.error.show(Chain, client.Error);
EXIT;
end;
var num := 0;
tokens.Enumerate(
// foreach
procedure(idx: Integer; next: TProc)
begin
Inc(num, 1);
Self.Queue(procedure
begin
progress.Get(Self).Step('Scanning for %d/%d tokens in your wallet. Please wait...', num, cnt.AsInteger);
end);
tokens[idx].Balance(client.Value, owner, procedure(balance: BigInteger; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
next;
EXIT;
end;
if balance.IsPositive then
begin
FAssets := FAssets + [asset.Create(tokens[idx], balance)];
Self.Queue(procedure
begin
Grid.RowCount := FAssets.Length;
Self.Update;
end);
end;
next;
end);
end,
// done
procedure
begin
( // step #4: scan for (erc-721 and erc-1155) NFTs (optional)
procedure(callback: TProc)
begin
if NFTs in aSettings then
begin
web3.eth.opensea.NFTs(Chain, OPENSEA_API_KEY, owner, procedure(tokens: TNFTs; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
web3.error.show(Chain, err);
EXIT;
end;
tokens.Enumerate(
// foreach
procedure(idx: Integer; next: TProc)
begin
FAssets := FAssets + [asset.Create(tokens[idx])];
Self.Queue(procedure
begin
Grid.RowCount := FAssets.Length;
Self.Update;
end);
next;
end,
// done
callback
);
end);
EXIT;
end;
callback;
end
)(procedure
begin
( // step #5: scan for 30k Uniswap v2 LP tokens (optional)
procedure(callback: TProc)
begin
if UniswapPairs in aSettings then
begin
web3.eth.tokenlists.tokens(UNISWAP_PAIR_TOKENS, procedure(tokens: TTokens; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
web3.error.show(Chain, err);
EXIT;
end;
tokens.Enumerate(
// foreach
procedure(idx: Integer; next: TProc)
begin
Inc(num, 1);
Self.Queue(procedure
begin
progress.Get(Self).Step('Scanning for %d/%d tokens in your wallet. Please wait...', num, cnt.AsInteger);
end);
tokens[idx].Balance(client.Value, owner, procedure(balance: BigInteger; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
next;
EXIT;
end;
if balance.IsPositive then
begin
FAssets := FAssets + [asset.Create(tokens[idx], balance)];
Self.Queue(procedure
begin
Grid.RowCount := FAssets.Length;
Self.Update;
end);
end;
next;
end);
end,
// done
callback
);
end);
EXIT;
end;
callback;
end
)(procedure
begin
// step #6: download and display the token icon
FAssets.Enumerate(
// foreach
procedure(idx: Integer; next: TProc)
begin
if FAssets[idx].Logo.IsEmpty then
begin
next;
EXIT;
end;
web3.http.get(FAssets[idx].Logo, [], procedure(img: IHttpResponse; err: IError)
begin
if Self.Cancelled then EXIT;
if Assigned(err) then
begin
next;
EXIT;
end;
try
FAssets[idx].Bitmap.LoadFromStream(img.ContentStream);
except end;
Queue(procedure
begin
colImage.UpdateCell(idx);
end);
next;
end);
end,
// done
procedure
begin
progress.Get(Self).Close;
end
);
end
);
end
);
end
);
end);
end);
end);
progress.Get(Self).Prompt('Scanning for tokens in your wallet. Please wait...');
end;
function TfrmMain.Settings: TSettings;
begin
Result := [];
if (Chain = web3.Ethereum) and chkScanForUniswapPairs.IsChecked then
Result := Result + [UniswapPairs];
if (Chain = web3.Ethereum) and chkScanForNFTs.IsChecked then
Result := Result + [NFTs];
end;
class procedure TfrmMain.Queue(P: TThreadProcedure);
begin
if TThread.CurrentThread.ThreadID = MainThreadId then
P
else
TThread.Queue(nil, procedure
begin
P
end);
end;
class procedure TfrmMain.Synchronize(P: TThreadProcedure);
begin
if TThread.CurrentThread.ThreadID = MainThreadId then
P
else
TThread.Synchronize(nil, procedure
begin
P
end);
end;
procedure TfrmMain.Unlock;
begin
if FLocked > 0 then Dec(FLocked);
end;
procedure TfrmMain.Update;
begin
chkSelectAll.Enabled := Self.FAssets.Length > 0;
btnMigrate.Enabled := Self.FAssets.Length > 0;
Self.Invalidate;
end;
//---------------------------------- public -----------------------------------
constructor TfrmMain.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
Init;
end;
end.