-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSmartWallet.cs
More file actions
1218 lines (1078 loc) · 54.4 KB
/
SmartWallet.cs
File metadata and controls
1218 lines (1078 loc) · 54.4 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
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
using Nethereum.ABI;
using Nethereum.ABI.EIP712;
using Nethereum.Util;
using Newtonsoft.Json;
using Thirdweb.AccountAbstraction;
namespace Thirdweb;
public enum TokenPaymaster
{
NONE,
BASE_USDC,
CELO_CUSD,
LISK_LSK,
}
public class SmartWallet : IThirdwebWallet
{
public ThirdwebClient Client { get; }
public ThirdwebAccountType AccountType => ThirdwebAccountType.SmartAccount;
public string WalletId => "smart";
public bool IsDeploying { get; private set; }
public BigInteger ActiveChainId { get; private set; }
private readonly IThirdwebWallet _personalAccount;
private ThirdwebContract _factoryContract;
private ThirdwebContract _accountContract;
private ThirdwebContract _entryPointContract;
private string _bundlerUrl;
private string _paymasterUrl;
private bool _isApproving;
private bool _isApproved;
private readonly string _erc20PaymasterAddress;
private readonly string _erc20PaymasterToken;
private readonly BigInteger _erc20PaymasterStorageSlot;
private readonly bool _gasless;
private struct TokenPaymasterConfig
{
public BigInteger ChainId;
public string PaymasterAddress;
public string TokenAddress;
public BigInteger BalanceStorageSlot;
}
private static readonly Dictionary<TokenPaymaster, TokenPaymasterConfig> _tokenPaymasterConfig = new()
{
{
TokenPaymaster.NONE,
new TokenPaymasterConfig()
{
ChainId = 0,
PaymasterAddress = null,
TokenAddress = null,
BalanceStorageSlot = 0,
}
},
{
TokenPaymaster.BASE_USDC,
new TokenPaymasterConfig()
{
ChainId = 8453,
PaymasterAddress = "0x2222f2738BE6bB7aA0Bfe4AEeAf2908172CF5539",
TokenAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
BalanceStorageSlot = 9,
}
},
{
TokenPaymaster.CELO_CUSD,
new TokenPaymasterConfig()
{
ChainId = 42220,
PaymasterAddress = "0x3feA3c5744D715ff46e91C4e5C9a94426DfF2aF9",
TokenAddress = "0x765DE816845861e75A25fCA122bb6898B8B1282a",
BalanceStorageSlot = 9,
}
},
{
TokenPaymaster.LISK_LSK,
new TokenPaymasterConfig()
{
ChainId = 1135,
PaymasterAddress = "0x9eb8cf7fBa5ed9EeDCC97a0d52254cc0e9B1AC25",
TokenAddress = "0xac485391EB2d7D88253a7F1eF18C37f4242D1A24",
BalanceStorageSlot = 9,
}
},
};
private bool UseERC20Paymaster => !string.IsNullOrEmpty(this._erc20PaymasterAddress) && !string.IsNullOrEmpty(this._erc20PaymasterToken);
protected SmartWallet(
IThirdwebWallet personalAccount,
bool gasless,
BigInteger chainId,
string bundlerUrl,
string paymasterUrl,
ThirdwebContract entryPointContract,
ThirdwebContract factoryContract,
ThirdwebContract accountContract,
string erc20PaymasterAddress,
string erc20PaymasterToken,
BigInteger erc20PaymasterStorageSlot
)
{
this.Client = personalAccount.Client;
this._personalAccount = personalAccount;
this._gasless = gasless;
this.ActiveChainId = chainId;
this._bundlerUrl = bundlerUrl;
this._paymasterUrl = paymasterUrl;
this._entryPointContract = entryPointContract;
this._factoryContract = factoryContract;
this._accountContract = accountContract;
this._erc20PaymasterAddress = erc20PaymasterAddress;
this._erc20PaymasterToken = erc20PaymasterToken;
this._erc20PaymasterStorageSlot = erc20PaymasterStorageSlot;
}
#region Creation
/// <summary>
/// Creates a new instance of <see cref="SmartWallet"/>.
/// </summary>
/// <param name="personalWallet">The smart wallet's signer to use.</param>
/// <param name="chainId">The chain ID.</param>
/// <param name="gasless">Whether to sponsor gas for transactions.</param>
/// <param name="factoryAddress">Override the default factory address.</param>
/// <param name="accountAddressOverride">Override the canonical account address that would be found deterministically based on the signer.</param>
/// <param name="entryPoint">Override the default entry point address. We provide Constants for different versions.</param>
/// <param name="bundlerUrl">Override the default thirdweb bundler URL.</param>
/// <param name="paymasterUrl">Override the default thirdweb paymaster URL.</param>
/// <param name="tokenPaymaster">Use an ERC20 paymaster and sponsor gas with ERC20s. If set, factoryAddress and accountAddressOverride are ignored.</param>
/// <returns>A new instance of <see cref="SmartWallet"/>.</returns>
/// <exception cref="InvalidOperationException">Thrown if the personal account is not connected.</exception>
public static async Task<SmartWallet> Create(
IThirdwebWallet personalWallet,
BigInteger chainId,
bool? gasless = null,
string factoryAddress = null,
string accountAddressOverride = null,
string entryPoint = null,
string bundlerUrl = null,
string paymasterUrl = null,
TokenPaymaster tokenPaymaster = TokenPaymaster.NONE
)
{
if (!await personalWallet.IsConnected().ConfigureAwait(false))
{
throw new InvalidOperationException("SmartAccount.Connect: Personal account must be connected.");
}
if (personalWallet is EcosystemWallet ecoWallet)
{
try
{
var ecoDetails = await ecoWallet.GetEcosystemDetails();
if (ecoDetails.SmartAccountOptions.HasValue)
{
gasless ??= ecoDetails.SmartAccountOptions?.SponsorGas;
factoryAddress ??= string.IsNullOrEmpty(ecoDetails.SmartAccountOptions?.AccountFactoryAddress) ? null : ecoDetails.SmartAccountOptions?.AccountFactoryAddress;
}
}
catch
{
// no-op
}
}
entryPoint ??= tokenPaymaster == TokenPaymaster.NONE ? Constants.ENTRYPOINT_ADDRESS_V06 : Constants.ENTRYPOINT_ADDRESS_V07;
var entryPointVersion = Utils.GetEntryPointVersion(entryPoint);
gasless ??= true;
bundlerUrl ??= $"https://{chainId}.bundler.thirdweb.com/v2";
paymasterUrl ??= $"https://{chainId}.bundler.thirdweb.com/v2";
factoryAddress ??= entryPointVersion == 6 ? Constants.DEFAULT_FACTORY_ADDRESS_V06 : Constants.DEFAULT_FACTORY_ADDRESS_V07;
var entryPointAbi = entryPointVersion == 6 ? Constants.ENTRYPOINT_V06_ABI : Constants.ENTRYPOINT_V07_ABI;
var factoryAbi = entryPointVersion == 6 ? Constants.FACTORY_V06_ABI : Constants.FACTORY_V07_ABI;
var entryPointContract = await ThirdwebContract.Create(personalWallet.Client, entryPoint, chainId, entryPointAbi).ConfigureAwait(false);
var factoryContract = await ThirdwebContract.Create(personalWallet.Client, factoryAddress, chainId, factoryAbi).ConfigureAwait(false);
ThirdwebContract accountContract = null;
if (!await Utils.IsZkSync(personalWallet.Client, chainId).ConfigureAwait(false))
{
var accountAbi = entryPointVersion == 6 ? Constants.ACCOUNT_V06_ABI : Constants.ACCOUNT_V07_ABI;
var personalAddress = await personalWallet.GetAddress().ConfigureAwait(false);
var accountAddress = accountAddressOverride ?? await ThirdwebContract.Read<string>(factoryContract, "getAddress", personalAddress, Array.Empty<byte>()).ConfigureAwait(false);
accountContract = await ThirdwebContract.Create(personalWallet.Client, accountAddress, chainId, accountAbi).ConfigureAwait(false);
}
var erc20PmInfo = _tokenPaymasterConfig[tokenPaymaster];
if (tokenPaymaster != TokenPaymaster.NONE)
{
if (entryPointVersion != 7)
{
throw new InvalidOperationException("Token paymasters are only supported in entry point version 7.");
}
if (erc20PmInfo.ChainId != chainId)
{
throw new InvalidOperationException("Token paymaster chain ID does not match the smart account chain ID.");
}
}
var smartWallet = new SmartWallet(
personalWallet,
gasless.Value,
chainId,
bundlerUrl,
paymasterUrl,
entryPointContract,
factoryContract,
accountContract,
erc20PmInfo.PaymasterAddress,
erc20PmInfo.TokenAddress,
erc20PmInfo.BalanceStorageSlot
);
Utils.TrackConnection(smartWallet);
return smartWallet;
}
#endregion
#region Wallet Specific
/// <summary>
/// Returns the signer that was used to connect to this SmartWallet.
/// </summary>
/// <returns>The signer.</returns>
public Task<IThirdwebWallet> GetPersonalWallet()
{
return Task.FromResult(this._personalAccount);
}
/// <summary>
/// Checks if the smart account is deployed on the current chain. A smart account is typically deployed when a personal message is signed or a transaction is sent.
/// </summary>
/// <returns>True if deployed, otherwise false.</returns>
public async Task<bool> IsDeployed()
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
return true;
}
var code = await ThirdwebRPC.GetRpcInstance(this.Client, this.ActiveChainId).SendRequestAsync<string>("eth_getCode", this._accountContract.Address, "latest").ConfigureAwait(false);
return code != "0x";
}
/// <summary>
/// Forces the smart account to deploy on the current chain. This is typically not necessary as the account will deploy automatically when needed.
/// </summary>
public async Task ForceDeploy()
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
return;
}
if (await this.IsDeployed().ConfigureAwait(false))
{
return;
}
if (this.IsDeploying)
{
throw new InvalidOperationException("SmartAccount.ForceDeploy: Account is already deploying.");
}
var input = new ThirdwebTransactionInput(chainId: this.ActiveChainId, data: "0x", to: this._accountContract.Address, value: 0);
var txHash = await this.SendTransaction(input).ConfigureAwait(false);
_ = await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false);
}
/// <summary>
/// Verifies if a signature is valid for a message using EIP-1271 or ERC-6492.
/// </summary>
/// <param name="message">The message to verify.</param>
/// <param name="signature">The signature to verify.</param>
/// <returns>True if the signature is valid, otherwise false.</returns>
public async Task<bool> IsValidSignature(string message, string signature)
{
var isCounterFactual = signature.EndsWith(Constants.ERC_6492_MAGIC_VALUE[2..]);
// ERC-6492
if (isCounterFactual)
{
var erc6492Sig = new ABIEncode().DecodeEncodedComplexType<Erc6492Signature>(signature.HexToBytes().Take(signature.Length - 32).ToArray());
var multicall3 = await ThirdwebContract.Create(this.Client, Constants.MULTICALL3_ADDRESS, this.ActiveChainId).ConfigureAwait(false);
List<Multicall3_Result> result;
try
{
result = await multicall3
.Read<List<Multicall3_Result>>(
method: "aggregate3",
parameters: new object[]
{
new List<Multicall3_Call3>
{
new()
{
Target = erc6492Sig.Create2Factory,
AllowFailure = true,
CallData = erc6492Sig.FactoryCalldata,
},
new()
{
Target = this._accountContract.Address,
AllowFailure = true,
CallData = this._accountContract.CreateCallData("isValidSignature", message.HashPrefixedMessage().HexToBytes(), erc6492Sig.SigToValidate).HexToBytes(),
},
},
}
)
.ConfigureAwait(false);
var success = result[1].Success;
var returnData = result[1].ReturnData.BytesToHex();
if (!success)
{
var revertMsg = new Nethereum.ABI.FunctionEncoding.FunctionCallDecoder().DecodeFunctionErrorMessage(returnData);
throw new Exception($"SmartAccount.IsValidSignature: Call to account contract failed: {revertMsg}");
}
else
{
return returnData == Constants.EIP_1271_MAGIC_VALUE;
}
}
catch
{
return false;
}
}
// EIP-1271
else
{
try
{
var magicValue = await ThirdwebContract
.Read<byte[]>(this._accountContract, "isValidSignature", Encoding.UTF8.GetBytes(message).HashPrefixedMessage(), signature.HexToBytes())
.ConfigureAwait(false);
return magicValue.BytesToHex() == new byte[] { 0x16, 0x26, 0xba, 0x7e }.BytesToHex();
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets all admins for the smart account.
/// </summary>
/// <returns>A list of admin addresses.</returns>
public async Task<List<string>> GetAllAdmins()
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new InvalidOperationException("Account Permissions are not supported in ZkSync");
}
var result = await ThirdwebContract.Read<List<string>>(this._accountContract, "getAllAdmins").ConfigureAwait(false);
return result ?? new List<string>();
}
/// <summary>
/// Gets all active signers for the smart account.
/// </summary>
/// <returns>A list of <see cref="SignerPermissions"/>.</returns>
public async Task<List<SignerPermissions>> GetAllActiveSigners()
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new InvalidOperationException("Account Permissions are not supported in ZkSync");
}
var result = await ThirdwebContract.Read<List<SignerPermissions>>(this._accountContract, "getAllActiveSigners").ConfigureAwait(false);
return result ?? new List<SignerPermissions>();
}
/// <summary>
/// Creates a new session key for a signer to use with the smart account.
/// </summary>
/// <param name="signerAddress">The address of the signer to create a session key for.</param>
/// <param name="approvedTargets">The list of approved targets for the signer. Use a list of a single Constants.ADDRESS_ZERO to enable all contracts.</param>
/// <param name="nativeTokenLimitPerTransactionInWei">The maximum amount of native tokens the signer can send in a single transaction.</param>
/// <param name="permissionStartTimestamp">The timestamp when the permission starts. Can be set to zero.</param>
/// <param name="permissionEndTimestamp">The timestamp when the permission ends. Make use of our Utils to get UNIX timestamps.</param>
/// <param name="reqValidityStartTimestamp">The timestamp when the request validity starts. Can be set to zero.</param>
/// <param name="reqValidityEndTimestamp">The timestamp when the request validity ends. Make use of our Utils to get UNIX timestamps.</param>
public async Task<ThirdwebTransactionReceipt> CreateSessionKey(
string signerAddress,
List<string> approvedTargets = null,
string nativeTokenLimitPerTransactionInWei = null,
string permissionStartTimestamp = null,
string permissionEndTimestamp = null,
string reqValidityStartTimestamp = null,
string reqValidityEndTimestamp = null
)
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new InvalidOperationException("Account Permissions are not supported in ZkSync");
}
var request = new SignerPermissionRequest()
{
Signer = signerAddress,
IsAdmin = 0,
ApprovedTargets = approvedTargets ?? new List<string> { Constants.ADDRESS_ZERO },
NativeTokenLimitPerTransaction = BigInteger.Parse(nativeTokenLimitPerTransactionInWei ?? "0"),
PermissionStartTimestamp = BigInteger.Parse(permissionStartTimestamp ?? "0"),
PermissionEndTimestamp = BigInteger.Parse(permissionEndTimestamp ?? Utils.GetUnixTimeStampIn10Years().ToString()),
ReqValidityStartTimestamp = BigInteger.Parse(reqValidityStartTimestamp ?? "0"),
ReqValidityEndTimestamp = BigInteger.Parse(reqValidityEndTimestamp ?? Utils.GetUnixTimeStampIn10Years().ToString()),
Uid = Guid.NewGuid().ToByteArray(),
};
var signature = await EIP712
.GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress().ConfigureAwait(false), request, this._personalAccount)
.ConfigureAwait(false);
var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes());
var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data);
var txHash = await this.SendTransaction(txInput).ConfigureAwait(false);
return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false);
}
/// <summary>
/// Revokes a session key from a signer.
/// </summary>
/// <param name="signerAddress">The address of the signer to revoke.</param>
/// <returns>The transaction receipt.</returns>
public async Task<ThirdwebTransactionReceipt> RevokeSessionKey(string signerAddress)
{
return await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false)
? throw new InvalidOperationException("Account Permissions are not supported in ZkSync")
: await this.CreateSessionKey(signerAddress, new List<string>(), "0", "0", "0", "0", Utils.GetUnixTimeStampIn10Years().ToString()).ConfigureAwait(false);
}
/// <summary>
/// Adds a new admin to the smart account.
/// </summary>
/// <param name="admin">The address of the admin to add.</param>
/// <returns>The transaction receipt.</returns>
public async Task<ThirdwebTransactionReceipt> AddAdmin(string admin)
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new InvalidOperationException("Account Permissions are not supported in ZkSync");
}
var request = new SignerPermissionRequest()
{
Signer = admin,
IsAdmin = 1,
ApprovedTargets = new List<string>(),
NativeTokenLimitPerTransaction = 0,
PermissionStartTimestamp = Utils.GetUnixTimeStampNow() - 3600,
PermissionEndTimestamp = Utils.GetUnixTimeStampIn10Years(),
ReqValidityStartTimestamp = Utils.GetUnixTimeStampNow() - 3600,
ReqValidityEndTimestamp = Utils.GetUnixTimeStampIn10Years(),
Uid = Guid.NewGuid().ToByteArray(),
};
var signature = await EIP712.GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress(), request, this._personalAccount).ConfigureAwait(false);
var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes());
var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data);
var txHash = await this.SendTransaction(txInput).ConfigureAwait(false);
return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false);
}
/// <summary>
/// Removes an existing admin from the smart account.
/// </summary>
/// <param name="admin">The address of the admin to remove.</param>
/// <returns>The transaction receipt.</returns>
public async Task<ThirdwebTransactionReceipt> RemoveAdmin(string admin)
{
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new InvalidOperationException("Account Permissions are not supported in ZkSync");
}
var request = new SignerPermissionRequest()
{
Signer = admin,
IsAdmin = 2,
ApprovedTargets = new List<string>(),
NativeTokenLimitPerTransaction = 0,
PermissionStartTimestamp = Utils.GetUnixTimeStampNow() - 3600,
PermissionEndTimestamp = Utils.GetUnixTimeStampIn10Years(),
ReqValidityStartTimestamp = Utils.GetUnixTimeStampNow() - 3600,
ReqValidityEndTimestamp = Utils.GetUnixTimeStampIn10Years(),
Uid = Guid.NewGuid().ToByteArray(),
};
var signature = await EIP712
.GenerateSignature_SmartAccount("Account", "1", this.ActiveChainId, await this.GetAddress().ConfigureAwait(false), request, this._personalAccount)
.ConfigureAwait(false);
var data = this._accountContract.CreateCallData("setPermissionsForSigner", request, signature.HexToBytes());
var txInput = new ThirdwebTransactionInput(chainId: this.ActiveChainId, to: this._accountContract.Address, value: 0, data: data);
var txHash = await this.SendTransaction(txInput).ConfigureAwait(false);
return await ThirdwebTransaction.WaitForTransactionReceipt(this.Client, this.ActiveChainId, txHash).ConfigureAwait(false);
}
/// <summary>
/// Estimates the gas cost for a user operation. More accurate than ThirdwebTransaction estimation, but slower.
/// </summary>
/// <param name="transaction">The transaction to estimate.</param>
/// <returns>The estimated gas cost.</returns>
public async Task<BigInteger> EstimateUserOperationGas(ThirdwebTransactionInput transaction)
{
await this.SwitchNetwork(transaction.ChainId.Value).ConfigureAwait(false);
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
throw new Exception("User Operations are not supported in ZkSync");
}
var signedOp = await this.SignUserOp(transaction, null, simulation: true).ConfigureAwait(false);
if (signedOp is UserOperationV6)
{
var castSignedOp = signedOp as UserOperationV6;
var cost = castSignedOp.CallGasLimit + castSignedOp.VerificationGasLimit + castSignedOp.PreVerificationGas;
return cost;
}
else if (signedOp is UserOperationV7)
{
var castSignedOp = signedOp as UserOperationV7;
var cost =
castSignedOp.CallGasLimit + castSignedOp.VerificationGasLimit + castSignedOp.PreVerificationGas + castSignedOp.PaymasterVerificationGasLimit + castSignedOp.PaymasterPostOpGasLimit;
return cost;
}
else
{
throw new Exception("Invalid signed operation type");
}
}
private async Task<(byte[] initCode, string factory, string factoryData)> GetInitCode()
{
if (await this.IsDeployed().ConfigureAwait(false))
{
return (Array.Empty<byte>(), null, null);
}
var personalAccountAddress = await this._personalAccount.GetAddress().ConfigureAwait(false);
var data = this._factoryContract.CreateCallData("createAccount", personalAccountAddress, Array.Empty<byte>());
return (Utils.HexConcat(this._factoryContract.Address, data).HexToBytes(), this._factoryContract.Address, data);
}
private async Task<object> SignUserOp(ThirdwebTransactionInput transactionInput, int? requestId = null, bool simulation = false)
{
requestId ??= 1;
(var initCode, var factory, var factoryData) = await this.GetInitCode().ConfigureAwait(false);
// Approve tokens if ERC20Paymaster
if (this.UseERC20Paymaster && !this._isApproving && !this._isApproved && !simulation)
{
try
{
this._isApproving = true;
var tokenContract = await ThirdwebContract.Create(this.Client, this._erc20PaymasterToken, this.ActiveChainId).ConfigureAwait(false);
var approvedAmount = await tokenContract.ERC20_Allowance(this._accountContract.Address, this._erc20PaymasterAddress).ConfigureAwait(false);
if (approvedAmount == 0)
{
_ = await tokenContract.ERC20_Approve(this, this._erc20PaymasterAddress, BigInteger.Pow(2, 96) - 1).ConfigureAwait(false);
}
this._isApproved = true;
await ThirdwebTask.Delay(1000).ConfigureAwait(false);
(initCode, factory, factoryData) = await this.GetInitCode().ConfigureAwait(false);
}
catch (Exception e)
{
this._isApproved = false;
throw new Exception($"Approving tokens for ERC20Paymaster spending failed: {e.Message}");
}
finally
{
this._isApproving = false;
}
}
// Wait until deployed to avoid double initCode
if (!simulation)
{
if (this.IsDeploying)
{
initCode = Array.Empty<byte>();
factory = null;
factoryData = null;
}
while (this.IsDeploying)
{
await ThirdwebTask.Delay(100).ConfigureAwait(false);
}
this.IsDeploying = initCode.Length > 0;
}
// Create the user operation and its safe (hexified) version
var fees = await ThirdwebBundler.ThirdwebGetUserOperationGasPrice(this.Client, this._bundlerUrl, requestId).ConfigureAwait(false);
var maxFee = fees.MaxFeePerGas.HexToNumber();
var maxPriorityFee = fees.MaxPriorityFeePerGas.HexToNumber();
var entryPointVersion = Utils.GetEntryPointVersion(this._entryPointContract.Address);
#pragma warning disable IDE0078 // Use pattern matching
// function execute(address _target, uint256 _value, bytes calldata _calldata)
var executeInput = this._accountContract.CreateCallData(
"execute",
transactionInput.To,
transactionInput.ChainId.Value == 295 || transactionInput.ChainId.Value == 296 ? transactionInput.Value.Value / BigInteger.Pow(10, 10) : transactionInput.Value.Value,
transactionInput.Data.HexToBytes()
);
#pragma warning restore IDE0078 // Use pattern matching
if (entryPointVersion == 6)
{
var partialUserOp = new UserOperationV6()
{
Sender = this._accountContract.Address,
Nonce = await this.GetNonce().ConfigureAwait(false),
InitCode = initCode,
CallData = executeInput.HexToBytes(),
CallGasLimit = transactionInput.Gas == null ? 0 : 21000 + transactionInput.Gas.Value,
VerificationGasLimit = 0,
PreVerificationGas = 0,
MaxFeePerGas = maxFee,
MaxPriorityFeePerGas = maxPriorityFee,
PaymasterAndData = Array.Empty<byte>(),
Signature = Constants.DUMMY_SIG.HexToBytes(),
};
// Update paymaster data and gas
var pmSponsorResult = await this.GetPaymasterAndData(requestId, EncodeUserOperation(partialUserOp), simulation).ConfigureAwait(false);
partialUserOp.PaymasterAndData = pmSponsorResult.PaymasterAndData.HexToBytes();
if (pmSponsorResult.VerificationGasLimit == null || pmSponsorResult.PreVerificationGas == null)
{
var gasEstimates = await ThirdwebBundler.EthEstimateUserOperationGas(this.Client, this._bundlerUrl, requestId, EncodeUserOperation(partialUserOp), this._entryPointContract.Address);
partialUserOp.CallGasLimit = gasEstimates.CallGasLimit.HexToNumber();
partialUserOp.VerificationGasLimit = gasEstimates.VerificationGasLimit.HexToNumber();
partialUserOp.PreVerificationGas = gasEstimates.PreVerificationGas.HexToNumber();
}
else
{
partialUserOp.CallGasLimit = pmSponsorResult.CallGasLimit.HexToNumber();
partialUserOp.VerificationGasLimit = pmSponsorResult.VerificationGasLimit.HexToNumber();
partialUserOp.PreVerificationGas = pmSponsorResult.PreVerificationGas.HexToNumber();
}
// Hash, sign and encode the user operation
if (!simulation)
{
partialUserOp.Signature = await this.HashAndSignUserOp(partialUserOp, this._entryPointContract).ConfigureAwait(false);
}
return partialUserOp;
}
else
{
var partialUserOp = new UserOperationV7()
{
Sender = this._accountContract.Address,
Nonce = await this.GetNonce().ConfigureAwait(false),
Factory = factory,
FactoryData = factoryData.HexToBytes(),
CallData = executeInput.HexToBytes(),
CallGasLimit = 0,
VerificationGasLimit = 0,
PreVerificationGas = 0,
MaxFeePerGas = maxFee,
MaxPriorityFeePerGas = maxPriorityFee,
Paymaster = null,
PaymasterVerificationGasLimit = 0,
PaymasterPostOpGasLimit = 0,
PaymasterData = Array.Empty<byte>(),
Signature = Constants.DUMMY_SIG.HexToBytes(),
};
// Update Paymaster Data / Estimate gas
var pmSponsorResult = await this.GetPaymasterAndData(requestId, EncodeUserOperation(partialUserOp), simulation).ConfigureAwait(false);
partialUserOp.Paymaster = pmSponsorResult.Paymaster;
partialUserOp.PaymasterData = pmSponsorResult.PaymasterData?.HexToBytes() ?? Array.Empty<byte>();
Dictionary<string, object> stateDict = null;
if (this.UseERC20Paymaster && !this._isApproving)
{
var abiEncoder = new ABIEncode();
var slotBytes = abiEncoder.GetABIEncoded(new ABIValue("address", this._accountContract.Address), new ABIValue("uint256", this._erc20PaymasterStorageSlot));
var desiredBalance = BigInteger.Pow(2, 96) - 1;
var storageDict = new Dictionary<string, string> { { new Sha3Keccack().CalculateHash(slotBytes).BytesToHex(), desiredBalance.NumberToHex().HexToBytes32().BytesToHex() } };
stateDict = new Dictionary<string, object> { { this._erc20PaymasterToken, new { stateDiff = storageDict } } };
}
else
{
partialUserOp.PreVerificationGas = (pmSponsorResult.PreVerificationGas ?? "0x0").HexToNumber();
partialUserOp.VerificationGasLimit = (pmSponsorResult.VerificationGasLimit ?? "0x0").HexToNumber();
partialUserOp.CallGasLimit = (pmSponsorResult.CallGasLimit ?? "0x0").HexToNumber();
partialUserOp.PaymasterVerificationGasLimit = (pmSponsorResult.PaymasterVerificationGasLimit ?? "0x0").HexToNumber();
partialUserOp.PaymasterPostOpGasLimit = (pmSponsorResult.PaymasterPostOpGasLimit ?? "0x0").HexToNumber();
}
if (partialUserOp.PreVerificationGas == 0 || partialUserOp.VerificationGasLimit == 0)
{
var gasEstimates = await ThirdwebBundler
.EthEstimateUserOperationGas(this.Client, this._bundlerUrl, requestId, EncodeUserOperation(partialUserOp), this._entryPointContract.Address, stateDict)
.ConfigureAwait(false);
partialUserOp.CallGasLimit = gasEstimates.CallGasLimit.HexToNumber();
partialUserOp.VerificationGasLimit = gasEstimates.VerificationGasLimit.HexToNumber();
partialUserOp.PreVerificationGas = gasEstimates.PreVerificationGas.HexToNumber();
partialUserOp.PaymasterVerificationGasLimit = gasEstimates.PaymasterVerificationGasLimit.HexToNumber();
partialUserOp.PaymasterPostOpGasLimit = this.UseERC20Paymaster && !this._isApproving ? 500_000 : gasEstimates.PaymasterPostOpGasLimit.HexToNumber();
}
// Hash, sign and encode the user operation
partialUserOp.Signature = await this.HashAndSignUserOp(partialUserOp, this._entryPointContract).ConfigureAwait(false);
return partialUserOp;
}
}
private async Task<string> SendUserOp(object userOperation, int? requestId = null)
{
requestId ??= 1;
// Encode op
object encodedOp;
if (userOperation is UserOperationV6)
{
encodedOp = EncodeUserOperation(userOperation as UserOperationV6);
}
else
{
encodedOp = userOperation is UserOperationV7 ? (object)EncodeUserOperation(userOperation as UserOperationV7) : throw new Exception("Invalid signed operation type");
}
// Send the user operation
var userOpHash = await ThirdwebBundler.EthSendUserOperation(this.Client, this._bundlerUrl, requestId, encodedOp, this._entryPointContract.Address).ConfigureAwait(false);
// Wait for the transaction to be mined
string txHash = null;
using var ct = new CancellationTokenSource(this.Client.FetchTimeoutOptions.GetTimeout(TimeoutType.Other));
try
{
while (txHash == null)
{
ct.Token.ThrowIfCancellationRequested();
var userOpReceipt = await ThirdwebBundler.EthGetUserOperationReceipt(this.Client, this._bundlerUrl, requestId, userOpHash).ConfigureAwait(false);
txHash = userOpReceipt?.Receipt?.TransactionHash;
await ThirdwebTask.Delay(100, ct.Token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
throw new Exception($"User operation timed out with user op hash: {userOpHash}");
}
this.IsDeploying = false;
return txHash;
}
private async Task<BigInteger> GetNonce()
{
var randomBytes = new byte[24];
RandomNumberGenerator.Fill(randomBytes);
BigInteger randomInt192 = new(randomBytes);
randomInt192 = BigInteger.Abs(randomInt192) % (BigInteger.One << 192);
return await ThirdwebContract.Read<BigInteger>(this._entryPointContract, "getNonce", await this.GetAddress().ConfigureAwait(false), randomInt192).ConfigureAwait(false);
}
private async Task<(string, string)> ZkPaymasterData(ThirdwebTransactionInput transactionInput)
{
if (this._gasless)
{
var result = await ThirdwebBundler.ZkPaymasterData(this.Client, this._paymasterUrl, 1, transactionInput).ConfigureAwait(false);
return (result.Paymaster, result.PaymasterInput);
}
else
{
return (null, null);
}
}
private async Task<string> ZkBroadcastTransaction(object transactionInput)
{
var result = await ThirdwebBundler.ZkBroadcastTransaction(this.Client, this._bundlerUrl, 1, transactionInput).ConfigureAwait(false);
return result.TransactionHash;
}
private async Task<PMSponsorOperationResponse> GetPaymasterAndData(object requestId, object userOp, bool simulation)
{
if (this.UseERC20Paymaster && !this._isApproving && !simulation)
{
return new PMSponsorOperationResponse()
{
PaymasterAndData = Utils.HexConcat(this._erc20PaymasterAddress, this._erc20PaymasterToken),
Paymaster = this._erc20PaymasterAddress,
PaymasterData = "0x",
};
}
else
{
return this._gasless
? await ThirdwebBundler.PMSponsorUserOperation(this.Client, this._paymasterUrl, requestId, userOp, this._entryPointContract.Address).ConfigureAwait(false)
: new PMSponsorOperationResponse();
}
}
private async Task<byte[]> HashAndSignUserOp(UserOperationV6 userOp, ThirdwebContract entryPointContract)
{
var userOpHash = await ThirdwebContract.Read<byte[]>(entryPointContract, "getUserOpHash", userOp);
var sig =
this._personalAccount.AccountType == ThirdwebAccountType.ExternalAccount
? await this._personalAccount.PersonalSign(userOpHash.BytesToHex()).ConfigureAwait(false)
: await this._personalAccount.PersonalSign(userOpHash).ConfigureAwait(false);
return sig.HexToBytes();
}
private async Task<byte[]> HashAndSignUserOp(UserOperationV7 userOp, ThirdwebContract entryPointContract)
{
var factoryBytes = userOp.Factory.HexToBytes();
var factoryDataBytes = userOp.FactoryData;
var initCodeBuffer = new byte[factoryBytes.Length + factoryDataBytes.Length];
Buffer.BlockCopy(factoryBytes, 0, initCodeBuffer, 0, factoryBytes.Length);
Buffer.BlockCopy(factoryDataBytes, 0, initCodeBuffer, factoryBytes.Length, factoryDataBytes.Length);
var verificationGasLimitBytes = userOp.VerificationGasLimit.NumberToHex().HexToBytes().PadBytes(16);
var callGasLimitBytes = userOp.CallGasLimit.NumberToHex().HexToBytes().PadBytes(16);
var accountGasLimitsBuffer = new byte[32];
Buffer.BlockCopy(verificationGasLimitBytes, 0, accountGasLimitsBuffer, 0, 16);
Buffer.BlockCopy(callGasLimitBytes, 0, accountGasLimitsBuffer, 16, 16);
var maxPriorityFeePerGasBytes = userOp.MaxPriorityFeePerGas.NumberToHex().HexToBytes().PadBytes(16);
var maxFeePerGasBytes = userOp.MaxFeePerGas.NumberToHex().HexToBytes().PadBytes(16);
var gasFeesBuffer = new byte[32];
Buffer.BlockCopy(maxPriorityFeePerGasBytes, 0, gasFeesBuffer, 0, 16);
Buffer.BlockCopy(maxFeePerGasBytes, 0, gasFeesBuffer, 16, 16);
PackedUserOperation packedOp;
if (userOp.Paymaster is null or Constants.ADDRESS_ZERO or "0x")
{
packedOp = new PackedUserOperation()
{
Sender = userOp.Sender,
Nonce = userOp.Nonce,
InitCode = initCodeBuffer,
CallData = userOp.CallData,
AccountGasLimits = accountGasLimitsBuffer,
PreVerificationGas = userOp.PreVerificationGas,
GasFees = gasFeesBuffer,
PaymasterAndData = Array.Empty<byte>(),
Signature = userOp.Signature,
};
}
else
{
var paymasterBytes = userOp.Paymaster.HexToBytes();
var paymasterVerificationGasLimitBytes = userOp.PaymasterVerificationGasLimit.NumberToHex().HexToBytes().PadBytes(16);
var paymasterPostOpGasLimitBytes = userOp.PaymasterPostOpGasLimit.NumberToHex().HexToBytes().PadBytes(16);
var paymasterDataBytes = userOp.PaymasterData;
var paymasterAndDataBuffer = new byte[20 + 16 + 16 + paymasterDataBytes.Length];
Buffer.BlockCopy(paymasterBytes, 0, paymasterAndDataBuffer, 0, 20);
Buffer.BlockCopy(paymasterVerificationGasLimitBytes, 0, paymasterAndDataBuffer, 20, 16);
Buffer.BlockCopy(paymasterPostOpGasLimitBytes, 0, paymasterAndDataBuffer, 20 + 16, 16);
Buffer.BlockCopy(paymasterDataBytes, 0, paymasterAndDataBuffer, 20 + 16 + 16, paymasterDataBytes.Length);
packedOp = new PackedUserOperation()
{
Sender = userOp.Sender,
Nonce = userOp.Nonce,
InitCode = initCodeBuffer,
CallData = userOp.CallData,
AccountGasLimits = accountGasLimitsBuffer,
PreVerificationGas = userOp.PreVerificationGas,
GasFees = gasFeesBuffer,
PaymasterAndData = paymasterAndDataBuffer,
Signature = userOp.Signature,
};
}
var userOpHash = await ThirdwebContract.Read<byte[]>(entryPointContract, "getUserOpHash", packedOp).ConfigureAwait(false);
var sig =
this._personalAccount.AccountType == ThirdwebAccountType.ExternalAccount
? await this._personalAccount.PersonalSign(userOpHash.BytesToHex()).ConfigureAwait(false)
: await this._personalAccount.PersonalSign(userOpHash).ConfigureAwait(false);
return sig.HexToBytes();
}
private static UserOperationHexifiedV6 EncodeUserOperation(UserOperationV6 userOperation)
{
return new UserOperationHexifiedV6()
{
Sender = userOperation.Sender,
Nonce = userOperation.Nonce.NumberToHex(),
InitCode = userOperation.InitCode.BytesToHex(),
CallData = userOperation.CallData.BytesToHex(),
CallGasLimit = userOperation.CallGasLimit.NumberToHex(),
VerificationGasLimit = userOperation.VerificationGasLimit.NumberToHex(),
PreVerificationGas = userOperation.PreVerificationGas.NumberToHex(),
MaxFeePerGas = userOperation.MaxFeePerGas.NumberToHex(),
MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.NumberToHex(),
PaymasterAndData = userOperation.PaymasterAndData.BytesToHex(),
Signature = userOperation.Signature.BytesToHex(),
};
}
private static UserOperationHexifiedV7 EncodeUserOperation(UserOperationV7 userOperation)
{
return new UserOperationHexifiedV7()
{
Sender = userOperation.Sender,
Nonce = Utils.HexConcat(Constants.ADDRESS_ZERO, userOperation.Nonce.NumberToHex()),
Factory = userOperation.Factory,
FactoryData = userOperation.FactoryData.BytesToHex(),
CallData = userOperation.CallData.BytesToHex(),
CallGasLimit = userOperation.CallGasLimit.NumberToHex(),
VerificationGasLimit = userOperation.VerificationGasLimit.NumberToHex(),
PreVerificationGas = userOperation.PreVerificationGas.NumberToHex(),
MaxFeePerGas = userOperation.MaxFeePerGas.NumberToHex(),
MaxPriorityFeePerGas = userOperation.MaxPriorityFeePerGas.NumberToHex(),
Paymaster = userOperation.Paymaster,
PaymasterVerificationGasLimit = userOperation.PaymasterVerificationGasLimit.NumberToHex(),
PaymasterPostOpGasLimit = userOperation.PaymasterPostOpGasLimit.NumberToHex(),
PaymasterData = userOperation.PaymasterData.BytesToHex(),
Signature = userOperation.Signature.BytesToHex(),
};
}
#endregion
#region IThirdwebWallet
public async Task<string> SendTransaction(ThirdwebTransactionInput transactionInput)
{
if (transactionInput == null)
{
throw new InvalidOperationException("SmartAccount.SendTransaction: Transaction input is required.");
}
await this.SwitchNetwork(transactionInput.ChainId.Value).ConfigureAwait(false);
var transaction = await ThirdwebTransaction
.Create(await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false) ? this._personalAccount : this, transactionInput)
.ConfigureAwait(false);
transaction = await ThirdwebTransaction.Prepare(transaction).ConfigureAwait(false);
transactionInput = transaction.Input;
if (await Utils.IsZkSync(this.Client, this.ActiveChainId).ConfigureAwait(false))
{
if (this._gasless)
{
(var paymaster, var paymasterInput) = await this.ZkPaymasterData(transactionInput).ConfigureAwait(false);
transaction = transaction.SetZkSyncOptions(new ZkSyncOptions(paymaster: paymaster, paymasterInput: paymasterInput));
var zkTx = await ThirdwebTransaction.ConvertToZkSyncTransaction(transaction).ConfigureAwait(false);
var zkTxSigned = await EIP712.GenerateSignature_ZkSyncTransaction("zkSync", "2", transaction.Input.ChainId.Value, zkTx, this).ConfigureAwait(false);
// Match bundler ZkTransactionInput type without recreating
var hash = await this.ZkBroadcastTransaction(
new
{
nonce = zkTx.Nonce.ToString(),
from = zkTx.From,
to = zkTx.To,
gas = zkTx.GasLimit.ToString(),
gasPrice = string.Empty,
value = zkTx.Value.ToString(),
data = Utils.BytesToHex(zkTx.Data),
maxFeePerGas = zkTx.MaxFeePerGas.ToString(),
maxPriorityFeePerGas = zkTx.MaxPriorityFeePerGas.ToString(),
chainId = this.ActiveChainId.ToString(),
signedTransaction = zkTxSigned,
paymaster,