-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathFlowEVMBridgeUtils.cdc
1301 lines (1183 loc) · 54.6 KB
/
FlowEVMBridgeUtils.cdc
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
import "NonFungibleToken"
import "FungibleToken"
import "MetadataViews"
import "FungibleTokenMetadataViews"
import "ViewResolver"
import "FlowToken"
import "FlowStorageFees"
import "EVM"
import "SerializeMetadata"
import "FlowEVMBridgeConfig"
import "CrossVMNFT"
import "IBridgePermissions"
/// This contract serves as a source of utility methods leveraged by FlowEVMBridge contracts
//
access(all)
contract FlowEVMBridgeUtils {
/// Address of the bridge factory Solidity contract
access(self)
var bridgeFactoryEVMAddress: EVM.EVMAddress
/// Delimeter used to derive contract names
access(self)
let delimiter: String
/// Mapping containing contract name prefixes
access(self)
let contractNamePrefixes: {Type: {String: String}}
/****************
Constructs
*****************/
/// Struct used to preserve and pass around multiple values relating to Cadence asset onboarding
///
access(all) struct CadenceOnboardingValues {
access(all) let contractAddress: Address
access(all) let name: String
access(all) let symbol: String
access(all) let identifier: String
access(all) let contractURI: String
init(
contractAddress: Address,
name: String,
symbol: String,
identifier: String,
contractURI: String
) {
self.contractAddress = contractAddress
self.name = name
self.symbol = symbol
self.identifier = identifier
self.contractURI = contractURI
}
}
/// Struct used to preserve and pass around multiple values preventing the need to make multiple EVM calls
/// during EVM asset onboarding
///
access(all) struct EVMOnboardingValues {
access(all) let evmContractAddress: EVM.EVMAddress
access(all) let name: String
access(all) let symbol: String
access(all) let decimals: UInt8?
access(all) let contractURI: String?
access(all) let cadenceContractName: String
access(all) let isERC721: Bool
init(
evmContractAddress: EVM.EVMAddress,
name: String,
symbol: String,
decimals: UInt8?,
contractURI: String?,
cadenceContractName: String,
isERC721: Bool
) {
self.evmContractAddress = evmContractAddress
self.name = name
self.symbol = symbol
self.decimals = decimals
self.contractURI = contractURI
self.cadenceContractName = cadenceContractName
self.isERC721 = isERC721
}
}
/**************************
Public Bridge Utils
**************************/
/// Retrieves the bridge factory contract address
///
/// @returns The EVMAddress of the bridge factory contract in EVM
///
access(all)
view fun getBridgeFactoryEVMAddress(): EVM.EVMAddress {
return self.bridgeFactoryEVMAddress
}
/// Calculates the fee bridge fee based on the given storage usage + the current base fee.
///
/// @param used: The amount of storage used by the asset
///
/// @return The calculated fee amount
///
access(all)
view fun calculateBridgeFee(bytes used: UInt64): UFix64 {
let megabytesUsed = FlowStorageFees.convertUInt64StorageBytesToUFix64Megabytes(used)
let storageFee = FlowStorageFees.storageCapacityToFlow(megabytesUsed)
return storageFee + FlowEVMBridgeConfig.baseFee
}
/// Returns whether the given type is allowed to be bridged as defined by the IBridgePermissions contract interface.
/// If the type's defining contract does not implement IBridgePermissions, the method returns true as the bridge
/// operates permissionlessly by default. Otherwise, the result of {IBridgePermissions}.allowsBridging() is returned
///
/// @param type: The Type of the asset to check
///
/// @return true if the type is allowed to be bridged, false otherwise
///
access(all)
view fun typeAllowsBridging(_ type: Type): Bool {
let contractAddress = self.getContractAddress(fromType: type)
?? panic("Could not construct contract address from type identifier: ".concat(type.identifier))
let contractName = self.getContractName(fromType: type)
?? panic("Could not construct contract name from type identifier: ".concat(type.identifier))
if let bridgePermissions = getAccount(contractAddress).contracts.borrow<&{IBridgePermissions}>(name: contractName) {
return bridgePermissions.allowsBridging()
}
return true
}
/// Returns whether the given address has opted out of enabling bridging for its defined assets
///
/// @param address: The EVM contract address to check
///
/// @return false if the address has opted out of enabling bridging, true otherwise
///
access(all)
fun evmAddressAllowsBridging(_ address: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "allowsBridging()",
targetEVMAddress: address,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
// Contract doesn't support the method - proceed permissionlessly
if callResult.status != EVM.Status.successful {
return true
}
// Contract is IBridgePermissions - return the result
let decodedResult = EVM.decodeABI(types: [Type<Bool>()], data: callResult.data) as! [AnyStruct]
return (decodedResult.length == 1 && decodedResult[0] as! Bool) == true ? true : false
}
/// Identifies if an asset is Cadence- or EVM-native, defined by whether a bridge contract defines it or not
///
/// @param type: The Type of the asset to check
///
/// @return True if the asset is Cadence-native, false if it is EVM-native
///
access(all)
view fun isCadenceNative(type: Type): Bool {
let definingAddress = self.getContractAddress(fromType: type)
?? panic("Could not construct address from type identifier: ".concat(type.identifier))
return definingAddress != self.account.address
}
/// Identifies if an asset is Cadence- or EVM-native, defined by whether a bridge-owned contract defines it or not.
/// Reverts on EVM call failure.
///
/// @param type: The Type of the asset to check
///
/// @return True if the asset is EVM-native, false if it is Cadence-native
///
access(all)
fun isEVMNative(evmContractAddress: EVM.EVMAddress): Bool {
return self.isEVMContractBridgeOwned(evmContractAddress: evmContractAddress) == false
}
/// Determines if the given EVM contract address was deployed by the bridge by querying the factory contract
/// Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to check
///
/// @return True if the contract was deployed by the bridge, false otherwise
///
access(all)
fun isEVMContractBridgeOwned(evmContractAddress: EVM.EVMAddress): Bool {
// Ask the bridge factory if the given contract address was deployed by the bridge
let callResult = self.call(
signature: "isBridgeDeployed(address)",
targetEVMAddress: self.bridgeFactoryEVMAddress,
args: [evmContractAddress],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to bridge factory failed")
let decodedResult = EVM.decodeABI(types: [Type<Bool>()], data: callResult.data)
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! Bool
}
/// Identifies if an asset is ERC721. Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to check
///
/// @return True if the asset is an ERC721, false otherwise
///
access(all)
fun isERC721(evmContractAddress: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "isERC721(address)",
targetEVMAddress: self.bridgeFactoryEVMAddress,
args: [evmContractAddress],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to bridge factory failed")
let decodedResult = EVM.decodeABI(types: [Type<Bool>()], data: callResult.data)
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! Bool
}
/// Identifies if an asset is ERC20 as far as is possible without true EVM type introspection. Reverts on EVM call
/// failure.
///
/// @param evmContractAddress: The EVM contract address to check
///
/// @return true if the asset is an ERC20, false otherwise
///
access(all)
fun isERC20(evmContractAddress: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "isERC20(address)",
targetEVMAddress: self.bridgeFactoryEVMAddress,
args: [evmContractAddress],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to bridge factory failed")
let decodedResult = EVM.decodeABI(types: [Type<Bool>()], data: callResult.data)
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! Bool
}
/// Returns whether the contract address is either an ERC721 or ERC20 exclusively. Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to check
///
/// @return True if the contract is either an ERC721 or ERC20, false otherwise
///
access(all)
fun isValidEVMAsset(evmContractAddress: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "isValidAsset(address)",
targetEVMAddress: self.bridgeFactoryEVMAddress,
args: [evmContractAddress],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
let decodedResult = EVM.decodeABI(types: [Type<Bool>()], data: callResult.data)
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! Bool
}
/// Returns whether the given type is either an NFT or FT exclusively
///
/// @param type: The Type of the asset to check
///
/// @return True if the type is either an NFT or FT, false otherwise
///
access(all)
view fun isValidCadenceAsset(type: Type): Bool {
let isCadenceNFT = type.isSubtype(of: Type<@{NonFungibleToken.NFT}>())
let isCadenceFungibleToken = type.isSubtype(of: Type<@{FungibleToken.Vault}>())
return isCadenceNFT != isCadenceFungibleToken
}
/// Retrieves the bridge contract's COA EVMAddress
///
/// @returns The EVMAddress of the bridge contract's COA orchestrating actions in FlowEVM
///
access(all)
view fun getBridgeCOAEVMAddress(): EVM.EVMAddress {
return self.borrowCOA().address()
}
/// Retrieves the relevant information for onboarding a Cadence asset to the bridge. This method is used to
/// retrieve the name, symbol, contract address, and contract URI for a given Cadence asset type. These values
/// are used to then deploy a corresponding EVM contract. If EVMBridgedMetadata is supported by the asset's
/// defining contract, the values are retrieved from that view. Otherwise, the values are derived from other
/// common metadata views.
///
/// @param forAssetType: The Type of the asset to retrieve onboarding values for
///
/// @return The CadenceOnboardingValues struct containing the asset's name, symbol, identifier, contract address,
/// and contract URI
///
access(all)
fun getCadenceOnboardingValues(forAssetType: Type): CadenceOnboardingValues {
pre {
self.isValidCadenceAsset(type: forAssetType): "This type is not a supported Flow asset type."
}
// If not an NFT, assumed to be fungible token.
let isNFT = forAssetType.isSubtype(of: Type<@{NonFungibleToken.NFT}>())
// Retrieve the Cadence type's defining contract name, address, & its identifier
var name = self.getContractName(fromType: forAssetType)
?? panic("Could not contract name from type: ".concat(forAssetType.identifier))
let identifier = forAssetType.identifier
let cadenceAddress = self.getContractAddress(fromType: forAssetType)
?? panic("Could not derive contract address for token type: ".concat(identifier))
// Initialize asset symbol which will be assigned later
// based on presence of asset-defined metadata
var symbol: String? = nil
// Borrow the ViewResolver to attempt to resolve the EVMBridgedMetadata view
let viewResolver = getAccount(cadenceAddress).contracts.borrow<&{ViewResolver}>(name: name)!
var contractURI = ""
// Try to resolve the EVMBridgedMetadata
let bridgedMetadata = viewResolver.resolveContractView(
resourceType: forAssetType,
viewType: Type<MetadataViews.EVMBridgedMetadata>()
) as! MetadataViews.EVMBridgedMetadata?
// Default to project-defined URI if available
if bridgedMetadata != nil {
name = bridgedMetadata!.name
symbol = bridgedMetadata!.symbol
contractURI = bridgedMetadata!.uri.uri()
} else {
if isNFT {
// Otherwise, serialize collection-level NFTCollectionDisplay
if let collectionDisplay = viewResolver.resolveContractView(
resourceType: forAssetType,
viewType: Type<MetadataViews.NFTCollectionDisplay>()
) as! MetadataViews.NFTCollectionDisplay? {
name = collectionDisplay.name
let serializedDisplay = SerializeMetadata.serializeFromDisplays(nftDisplay: nil, collectionDisplay: collectionDisplay)!
contractURI = "data:application/json;utf8,{".concat(serializedDisplay).concat("}")
}
if symbol == nil {
symbol = SerializeMetadata.deriveSymbol(fromString: name)
}
} else {
let ftDisplay = viewResolver.resolveContractView(
resourceType: forAssetType,
viewType: Type<FungibleTokenMetadataViews.FTDisplay>()
) as! FungibleTokenMetadataViews.FTDisplay?
if ftDisplay != nil {
name = ftDisplay!.name
symbol = ftDisplay!.symbol
}
if contractURI.length == 0 && ftDisplay != nil {
let serializedDisplay = SerializeMetadata.serializeFTDisplay(ftDisplay!)
contractURI = "data:application/json;utf8,{".concat(serializedDisplay).concat("}")
}
}
}
return CadenceOnboardingValues(
contractAddress: cadenceAddress,
name: name,
symbol: symbol!,
identifier: identifier,
contractURI: contractURI
)
}
/// Retrieves identifying information about an EVM contract related to bridge onboarding.
///
/// @param evmContractAddress: The EVM contract address to retrieve onboarding values for
///
/// @return The EVMOnboardingValues struct containing the asset's name, symbol, decimals, contractURI, and
/// Cadence contract name as well as whether the asset is an ERC721
///
access(all)
fun getEVMOnboardingValues(evmContractAddress: EVM.EVMAddress): EVMOnboardingValues {
// Retrieve the EVM contract's name, symbol, and contractURI
let name: String = self.getName(evmContractAddress: evmContractAddress)
let symbol: String = self.getSymbol(evmContractAddress: evmContractAddress)
let contractURI = self.getContractURI(evmContractAddress: evmContractAddress)
// Default to 18 decimals for ERC20s
var decimals: UInt8 = FlowEVMBridgeConfig.defaultDecimals
// Derive Cadence contract name
let isERC721: Bool = self.isERC721(evmContractAddress: evmContractAddress)
var cadenceContractName: String = ""
if isERC721 {
// Assert the contract is not mixed asset
let isERC20 = self.isERC20(evmContractAddress: evmContractAddress)
assert(!isERC20, message: "Contract is mixed asset and is not currently supported by the bridge")
// Derive the contract name from the ERC721 contract
cadenceContractName = self.deriveBridgedNFTContractName(from: evmContractAddress)
} else {
// Otherwise, treat as ERC20
let isERC20 = self.isERC20(evmContractAddress: evmContractAddress)
assert(
isERC20,
message: "Contract ".concat(evmContractAddress.toString()).concat("defines an asset that is not currently supported by the bridge")
)
cadenceContractName = self.deriveBridgedTokenContractName(from: evmContractAddress)
decimals = self.getTokenDecimals(evmContractAddress: evmContractAddress)
}
return EVMOnboardingValues(
evmContractAddress: evmContractAddress,
name: name,
symbol: symbol,
decimals: decimals,
contractURI: contractURI,
cadenceContractName: cadenceContractName,
isERC721: isERC721
)
}
/************************
EVM Call Wrappers
************************/
/// Retrieves the NFT/FT name from the given EVM contract address - applies for both ERC20 & ERC721.
/// Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to retrieve the name from
///
/// @return the name of the asset
///
access(all)
fun getName(evmContractAddress: EVM.EVMAddress): String {
let callResult = self.call(
signature: "name()",
targetEVMAddress: evmContractAddress,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call for EVM asset name failed")
let decodedResult = EVM.decodeABI(types: [Type<String>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! String
}
/// Retrieves the NFT/FT symbol from the given EVM contract address - applies for both ERC20 & ERC721
/// Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to retrieve the symbol from
///
/// @return the symbol of the asset
///
access(all)
fun getSymbol(evmContractAddress: EVM.EVMAddress): String {
let callResult = self.call(
signature: "symbol()",
targetEVMAddress: evmContractAddress,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call for EVM asset symbol failed")
let decodedResult = EVM.decodeABI(types: [Type<String>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! String
}
/// Retrieves the tokenURI for the given NFT ID from the given EVM contract address. Reverts on EVM call failure.
/// Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to retrieve the tokenURI from
/// @param id: The ID of the NFT for which to retrieve the tokenURI value
///
/// @return the tokenURI of the ERC721
///
access(all)
fun getTokenURI(evmContractAddress: EVM.EVMAddress, id: UInt256): String {
let callResult = self.call(
signature: "tokenURI(uint256)",
targetEVMAddress: evmContractAddress,
args: [id],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to EVM for tokenURI failed")
let decodedResult = EVM.decodeABI(types: [Type<String>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! String
}
/// Retrieves the contract URI from the given EVM contract address. Returns nil on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to retrieve the contractURI from
///
/// @return the contract's contractURI
///
access(all)
fun getContractURI(evmContractAddress: EVM.EVMAddress): String? {
let callResult = self.call(
signature: "contractURI()",
targetEVMAddress: evmContractAddress,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
if callResult.status != EVM.Status.successful {
return nil
}
let decodedResult = EVM.decodeABI(types: [Type<String>()], data: callResult.data) as! [AnyStruct]
return decodedResult.length == 1 ? decodedResult[0] as! String : nil
}
/// Retrieves the number of decimals for a given ERC20 contract address. Reverts on EVM call failure.
///
/// @param evmContractAddress: The ERC20 contract address to retrieve the token decimals from
///
/// @return the token decimals of the ERC20
///
access(all)
fun getTokenDecimals(evmContractAddress: EVM.EVMAddress): UInt8 {
let callResult = self.call(
signature: "decimals()",
targetEVMAddress: evmContractAddress,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call for EVM asset decimals failed")
let decodedResult = EVM.decodeABI(types: [Type<UInt8>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! UInt8
}
/// Determines if the provided owner address is either the owner or approved for the NFT in the ERC721 contract
/// Reverts on EVM call failure.
///
/// @param ofNFT: The ID of the NFT to query
/// @param owner: The owner address to query
/// @param evmContractAddress: The ERC721 contract address to query
///
/// @return true if the owner is either the owner or approved for the NFT, false otherwise
///
access(all)
fun isOwnerOrApproved(ofNFT: UInt256, owner: EVM.EVMAddress, evmContractAddress: EVM.EVMAddress): Bool {
return self.isOwner(ofNFT: ofNFT, owner: owner, evmContractAddress: evmContractAddress) ||
self.isApproved(ofNFT: ofNFT, owner: owner, evmContractAddress: evmContractAddress)
}
/// Returns whether the given owner is the owner of the given NFT. Reverts on EVM call failure.
///
/// @param ofNFT: The ID of the NFT to query
/// @param owner: The owner address to query
/// @param evmContractAddress: The ERC721 contract address to query
///
/// @return true if the owner is in fact the owner of the NFT, false otherwise
///
access(all)
fun isOwner(ofNFT: UInt256, owner: EVM.EVMAddress, evmContractAddress: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "ownerOf(uint256)",
targetEVMAddress: evmContractAddress,
args: [ofNFT],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to ERC721.ownerOf(uint256) failed")
let decodedCallResult = EVM.decodeABI(types: [Type<EVM.EVMAddress>()], data: callResult.data)
if decodedCallResult.length == 1 {
let actualOwner = decodedCallResult[0] as! EVM.EVMAddress
return actualOwner.equals(owner)
}
return false
}
/// Returns whether the given owner is approved for the given NFT. Reverts on EVM call failure.
///
/// @param ofNFT: The ID of the NFT to query
/// @param owner: The owner address to query
/// @param evmContractAddress: The ERC721 contract address to query
///
/// @return true if the owner is in fact approved for the NFT, false otherwise
///
access(all)
fun isApproved(ofNFT: UInt256, owner: EVM.EVMAddress, evmContractAddress: EVM.EVMAddress): Bool {
let callResult = self.call(
signature: "getApproved(uint256)",
targetEVMAddress: evmContractAddress,
args: [ofNFT],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to ERC721.getApproved(uint256) failed")
let decodedCallResult = EVM.decodeABI(types: [Type<EVM.EVMAddress>()], data: callResult.data)
if decodedCallResult.length == 1 {
let actualApproved = decodedCallResult[0] as! EVM.EVMAddress
return actualApproved.equals(owner)
}
return false
}
/// Returns whether the given ERC721 exists, assuming the ERC721 contract implements the `exists` method. While this
/// method is not part of the ERC721 standard, it is implemented in the bridge-deployed ERC721 implementation.
/// Reverts on EVM call failure.
///
/// @param erc721Address: The EVM contract address of the ERC721 token
/// @param id: The ID of the ERC721 token to check
///
/// @return true if the ERC721 token exists, false otherwise
///
access(all)
fun erc721Exists(erc721Address: EVM.EVMAddress, id: UInt256): Bool {
let existsResponse = EVM.decodeABI(
types: [Type<Bool>()],
data: self.call(
signature: "exists(uint256)",
targetEVMAddress: erc721Address,
args: [id],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
).data,
)
assert(existsResponse.length == 1, message: "Invalid response length")
return existsResponse[0] as! Bool
}
/// Returns the ERC20 balance of the owner at the given ERC20 contract address. Reverts on EVM call failure.
///
/// @param owner: The owner address to query
/// @param evmContractAddress: The ERC20 contract address to query
///
/// @return The UInt256 balance of the owner at the ERC20 contract address. Callers may wish to convert the return
/// value to a UFix64 via convertERC20AmountToCadenceAmount, though note there may be a loss of precision.
///
access(all)
fun balanceOf(owner: EVM.EVMAddress, evmContractAddress: EVM.EVMAddress): UInt256 {
let callResult = self.call(
signature: "balanceOf(address)",
targetEVMAddress: evmContractAddress,
args: [owner],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to ERC20.balanceOf(address) failed")
let decodedResult = EVM.decodeABI(types: [Type<UInt256>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! UInt256
}
/// Determines if the owner has sufficient funds to bridge the given amount at the ERC20 contract address
/// Reverts on EVM call failure.
///
/// @param amount: The amount to check if the owner has enough balance to cover
/// @param owner: The owner address to query
/// @param evmContractAddress: The ERC20 contract address to query
///
/// @return true if the owner's balance >= amount, false otherwise
///
access(all)
fun hasSufficientBalance(amount: UInt256, owner: EVM.EVMAddress, evmContractAddress: EVM.EVMAddress): Bool {
return self.balanceOf(owner: owner, evmContractAddress: evmContractAddress) >= amount
}
/// Retrieves the total supply of the ERC20 contract at the given EVM contract address. Reverts on EVM call failure.
///
/// @param evmContractAddress: The EVM contract address to retrieve the total supply from
///
/// @return the total supply of the ERC20
///
access(all)
fun totalSupply(evmContractAddress: EVM.EVMAddress): UInt256 {
let callResult = self.call(
signature: "totalSupply()",
targetEVMAddress: evmContractAddress,
args: [],
gasLimit: FlowEVMBridgeConfig.gasLimit,
value: 0.0
)
assert(callResult.status == EVM.Status.successful, message: "Call to ERC20.totalSupply() failed")
let decodedResult = EVM.decodeABI(types: [Type<UInt256>()], data: callResult.data) as! [AnyStruct]
assert(decodedResult.length == 1, message: "Invalid response length")
return decodedResult[0] as! UInt256
}
/// Converts the given amount of ERC20 tokens to the equivalent amount in FLOW tokens based on the ERC20s decimals
/// value. Note that may be some loss of decimal precision as UFix64 supports precision for 8 decimal places.
/// Reverts on EVM call failure.
///
/// @param amount: The amount of ERC20 tokens to convert
/// @param erc20Address: The EVM contract address of the ERC20 token
///
/// @return the equivalent amount in FLOW tokens as a UFix64
///
access(all)
fun convertERC20AmountToCadenceAmount(_ amount: UInt256, erc20Address: EVM.EVMAddress): UFix64 {
return self.uint256ToUFix64(
value: amount,
decimals: self.getTokenDecimals(evmContractAddress: erc20Address)
)
}
/// Converts the given amount of Cadence fungible tokens to the equivalent amount in ERC20 tokens based on the
/// ERC20s decimals. Note that there may be some loss of decimal precision as UFix64 supports precision for 8
/// decimal places. Reverts on EVM call failure.
///
/// @param amount: The amount of Cadence fungible tokens to convert
/// @param erc20Address: The EVM contract address of the ERC20 token
///
/// @return the equivalent amount in ERC20 tokens as a UInt256
///
access(all)
fun convertCadenceAmountToERC20Amount(_ amount: UFix64, erc20Address: EVM.EVMAddress): UInt256 {
return self.ufix64ToUInt256(value: amount, decimals: self.getTokenDecimals(evmContractAddress: erc20Address))
}
/************************
Derivation Utils
************************/
/// Derives the StoragePath where the escrow locker is stored for a given Type of asset & returns. The given type
/// must be of an asset supported by the bridge.
///
/// @param fromType: The type of the asset the escrow locker is being derived for
///
/// @return The StoragePath associated with the type's escrow Locker, or nil if the type is not supported
///
access(all)
view fun deriveEscrowStoragePath(fromType: Type): StoragePath? {
if !self.isValidCadenceAsset(type: fromType) {
return nil
}
var prefix = ""
if fromType.isSubtype(of: Type<@{NonFungibleToken.NFT}>()) {
prefix = "flowEVMBridgeNFTEscrow"
} else if fromType.isSubtype(of: Type<@{FungibleToken.Vault}>()) {
prefix = "flowEVMBridgeTokenEscrow"
}
assert(prefix.length > 1, message: "Invalid prefix")
if let splitIdentifier = self.splitObjectIdentifier(identifier: fromType.identifier) {
let sourceContractAddress = Address.fromString("0x".concat(splitIdentifier[1]))!
let sourceContractName = splitIdentifier[2]
let resourceName = splitIdentifier[3]
return StoragePath(
identifier: prefix.concat(self.delimiter)
.concat(sourceContractAddress.toString()).concat(self.delimiter)
.concat(sourceContractName).concat(self.delimiter)
.concat(resourceName)
) ?? nil
}
return nil
}
/// Derives the Cadence contract name for a given EVM NFT of the form
/// EVMVMBridgedNFT_<0xCONTRACT_ADDRESS>
///
/// @param from evmContract: The EVM contract address to derive the Cadence NFT contract name for
///
/// @return The derived Cadence FT contract name
///
access(all)
view fun deriveBridgedNFTContractName(from evmContract: EVM.EVMAddress): String {
return self.contractNamePrefixes[Type<@{NonFungibleToken.NFT}>()]!["bridged"]!
.concat(self.delimiter)
.concat(evmContract.toString())
}
/// Derives the Cadence contract name for a given EVM fungible token of the form
/// EVMVMBridgedToken_<0xCONTRACT_ADDRESS>
///
/// @param from evmContract: The EVM contract address to derive the Cadence FT contract name for
///
/// @return The derived Cadence FT contract name
///
access(all)
view fun deriveBridgedTokenContractName(from evmContract: EVM.EVMAddress): String {
return self.contractNamePrefixes[Type<@{FungibleToken.Vault}>()]!["bridged"]!
.concat(self.delimiter)
.concat(evmContract.toString())
}
/****************
Math Utils
****************/
/// Raises the base to the power of the exponent
///
access(all)
view fun pow(base: UInt256, exponent: UInt8): UInt256 {
if exponent == 0 {
return 1
}
var r = base
var exp: UInt8 = 1
while exp < exponent {
r = r * base
exp = exp + 1
}
return r
}
/// Raises the fixed point base to the power of the exponent
///
access(all)
view fun ufixPow(base: UFix64, exponent: UInt8): UFix64 {
if exponent == 0 {
return 1.0
}
var r = base
var exp: UInt8 = 1
while exp < exponent {
r = r * base
exp = exp + 1
}
return r
}
/// Converts a UFix64 to a UInt256
//
access(all)
view fun ufix64ToUInt256(value: UFix64, decimals: UInt8): UInt256 {
// Default to 10e8 scale, catching instances where decimals are less than default and scale appropriately
let ufixScaleExp: UInt8 = decimals < 8 ? decimals : 8
var ufixScale = self.ufixPow(base: 10.0, exponent: ufixScaleExp)
// Separate the fractional and integer parts of the UFix64
let integer = UInt256(value)
var fractional = (value % 1.0) * ufixScale
// Calculate the multiplier for integer and fractional parts
var integerMultiplier: UInt256 = self.pow(base:10, exponent: decimals)
let fractionalMultiplierExp: UInt8 = decimals < 8 ? 0 : decimals - 8
var fractionalMultiplier: UInt256 = self.pow(base:10, exponent: fractionalMultiplierExp)
// Scale and sum the parts
return integer * integerMultiplier + UInt256(fractional) * fractionalMultiplier
}
/// Converts a UInt256 to a UFix64
///
access(all)
view fun uint256ToUFix64(value: UInt256, decimals: UInt8): UFix64 {
// Calculate scale factors for the integer and fractional parts
let absoluteScaleFactor = self.pow(base: 10, exponent: decimals)
// Separate the integer and fractional parts of the value
let scaledValue = value / absoluteScaleFactor
var fractional = value % absoluteScaleFactor
// Scale the fractional part
let scaledFractional = self.uint256FractionalToScaledUFix64Decimals(value: fractional, decimals: decimals)
// Ensure the parts do not exceed the max UFix64 value before conversion
assert(
scaledValue <= UInt256(UFix64.max),
message: "Scaled integer value ".concat(value.toString()).concat(" exceeds max UFix64 value")
)
/// Check for the max value that can be converted to a UFix64 without overflowing
assert(
scaledValue == UInt256(UFix64.max) ? scaledFractional < 0.09551616 : true,
message: "Scaled integer value ".concat(value.toString()).concat(" exceeds max UFix64 value")
)
return UFix64(scaledValue) + scaledFractional
}
/// Converts a UInt256 fractional value with the given decimal places to a scaled UFix64. Note that UFix64 has
/// decimal precision of 8 places so converted values may lose precision and be rounded down.
///
access(all)
view fun uint256FractionalToScaledUFix64Decimals(value: UInt256, decimals: UInt8): UFix64 {
pre {
self.getNumberOfDigits(value) <= decimals: "Fractional digits exceed the defined decimal places"
}
post {
result < 1.0: "Resulting scaled fractional exceeds 1.0"
}
var fractional = value
// Truncate fractional to the first 8 decimal places which is the max precision for UFix64
if decimals >= 8 {
fractional = fractional / self.pow(base: 10, exponent: decimals - 8)
}
// Return early if the truncated fractional part is now 0
if fractional == 0 {
return 0.0
}
// Scale the fractional part
let fractionalMultiplier = self.ufixPow(base: 0.1, exponent: decimals < 8 ? decimals : 8)
return UFix64(fractional) * fractionalMultiplier
}
/// Returns the value as a UInt64 if it fits, otherwise panics
///
access(all)
view fun uint256ToUInt64(value: UInt256): UInt64 {
return value <= UInt256(UInt64.max) ? UInt64(value) : panic("Value too large to fit into UInt64")
}
/// Returns the number of digits in the given UInt256
///
access(all)
view fun getNumberOfDigits(_ value: UInt256): UInt8 {
var tmp = value
var digits: UInt8 = 0
while tmp > 0 {
tmp = tmp / 10
digits = digits + 1
}
return digits
}
/***************************
Type Identifier Utils
***************************/
/// Returns the contract address from the given Type's identifier
///
/// @param fromType: The Type to extract the contract address from
///
/// @return The defining contract's Address, or nil if the identifier does not have an associated Address
///
access(all)
view fun getContractAddress(fromType: Type): Address? {
// Split identifier of format A.<CONTRACT_ADDRESS>.<CONTRACT_NAME>.<OBJECT_NAME>
if let identifierSplit = self.splitObjectIdentifier(identifier: fromType.identifier) {
return Address.fromString("0x".concat(identifierSplit[1]))
}
return nil
}
/// Returns the contract name from the given Type's identifier
///
/// @param fromType: The Type to extract the contract name from
///
/// @return The defining contract's name, or nil if the identifier does not have an associated contract name
///
access(all)
view fun getContractName(fromType: Type): String? {
// Split identifier of format A.<CONTRACT_ADDRESS>.<CONTRACT_NAME>.<OBJECT_NAME>
if let identifierSplit = self.splitObjectIdentifier(identifier: fromType.identifier) {
return identifierSplit[2]
}
return nil
}
/// Returns the object's name from the given Type's identifier
///
/// @param fromType: The Type to extract the object name from
///
/// @return The object's name, or nil if the identifier does identify an object
///
access(all)
view fun getObjectName(fromType: Type): String? {
// Split identifier of format A.<CONTRACT_ADDRESS>.<CONTRACT_NAME>.<OBJECT_NAME>
if let identifierSplit = self.splitObjectIdentifier(identifier: fromType.identifier) {
return identifierSplit[3]
}
return nil
}
/// Splits the given identifier into its constituent parts defined by a delimiter of '".'"
///
/// @param identifier: The identifier to split
///
/// @return An array of the identifier's constituent parts, or nil if the identifier does not have 4 parts
///
access(all)
view fun splitObjectIdentifier(identifier: String): [String]? {
let identifierSplit = identifier.split(separator: ".")
return identifierSplit.length != 4 ? nil : identifierSplit
}
/// Builds a composite type from the given identifier parts
///
/// @param address: The defining contract address
/// @param contractName: The defining contract name
/// @param resourceName: The resource name
///
access(all)
view fun buildCompositeType(address: Address, contractName: String, resourceName: String): Type? {
let addressStr = address.toString()
let subtract0x = addressStr.slice(from: 2, upTo: addressStr.length)
let identifier = "A".concat(".").concat(subtract0x).concat(".").concat(contractName).concat(".").concat(resourceName)
return CompositeType(identifier)