/
fungible_asset.move
1155 lines (1030 loc) · 45.9 KB
/
fungible_asset.move
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
/// This defines the fungible asset module that can issue fungible asset of any `Metadata` object. The
/// metadata object can be any object that equipped with `Metadata` resource.
module aptos_framework::fungible_asset {
use aptos_framework::aggregator_v2::{Self, Aggregator};
use aptos_framework::event;
use aptos_framework::function_info::{Self, FunctionInfo};
use aptos_framework::object::{Self, Object, ConstructorRef, DeleteRef, ExtendRef};
use std::string;
use std::features;
use std::error;
use std::option::{Self, Option};
use std::signer;
use std::string::String;
friend aptos_framework::coin;
friend aptos_framework::primary_fungible_store;
friend aptos_framework::dispatchable_fungible_asset;
/// Amount cannot be zero.
const EAMOUNT_CANNOT_BE_ZERO: u64 = 1;
/// The transfer ref and the fungible asset do not match.
const ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 2;
/// Store is disabled from sending and receiving this fungible asset.
const ESTORE_IS_FROZEN: u64 = 3;
/// Insufficient balance to withdraw or transfer.
const EINSUFFICIENT_BALANCE: u64 = 4;
/// The fungible asset's supply has exceeded maximum.
const EMAX_SUPPLY_EXCEEDED: u64 = 5;
/// Fungible asset do not match when merging.
const EFUNGIBLE_ASSET_MISMATCH: u64 = 6;
/// The mint ref and the store do not match.
const EMINT_REF_AND_STORE_MISMATCH: u64 = 7;
/// Account is not the store's owner.
const ENOT_STORE_OWNER: u64 = 8;
/// Transfer ref and store do not match.
const ETRANSFER_REF_AND_STORE_MISMATCH: u64 = 9;
/// Burn ref and store do not match.
const EBURN_REF_AND_STORE_MISMATCH: u64 = 10;
/// Fungible asset and store do not match.
const EFUNGIBLE_ASSET_AND_STORE_MISMATCH: u64 = 11;
/// Cannot destroy non-empty fungible assets.
const EAMOUNT_IS_NOT_ZERO: u64 = 12;
/// Burn ref and fungible asset do not match.
const EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 13;
/// Cannot destroy fungible stores with a non-zero balance.
const EBALANCE_IS_NOT_ZERO: u64 = 14;
/// Name of the fungible asset metadata is too long
const ENAME_TOO_LONG: u64 = 15;
/// Symbol of the fungible asset metadata is too long
const ESYMBOL_TOO_LONG: u64 = 16;
/// Decimals is over the maximum of 32
const EDECIMALS_TOO_LARGE: u64 = 17;
/// Fungibility is only available for non-deletable objects.
const EOBJECT_IS_DELETABLE: u64 = 18;
/// URI for the icon of the fungible asset metadata is too long
const EURI_TOO_LONG: u64 = 19;
/// The fungible asset's supply will be negative which should be impossible.
const ESUPPLY_UNDERFLOW: u64 = 20;
/// Supply resource is not found for a metadata object.
const ESUPPLY_NOT_FOUND: u64 = 21;
/// Flag for Concurrent Supply not enabled
const ECONCURRENT_SUPPLY_NOT_ENABLED: u64 = 22;
/// Flag for the existence of fungible store.
const EFUNGIBLE_STORE_EXISTENCE: u64 = 23;
/// Account is not the owner of metadata object.
const ENOT_METADATA_OWNER: u64 = 24;
/// Provided withdraw function type doesn't meet the signature requirement.
const EWITHDRAW_FUNCTION_SIGNATURE_MISMATCH: u64 = 25;
/// Provided deposit function type doesn't meet the signature requirement.
const EDEPOSIT_FUNCTION_SIGNATURE_MISMATCH: u64 = 26;
/// Provided derived_balance function type doesn't meet the signature requirement.
const EDERIVED_BALANCE_FUNCTION_SIGNATURE_MISMATCH: u64 = 27;
/// Invalid withdraw/deposit on dispatchable token.
const EINVALID_DISPATCHABLE_OPERATIONS: u64 = 28;
/// Trying to re-register dispatch hook on a fungible asset.
const EALREADY_REGISTERED: u64 = 29;
//
// Constants
//
const MAX_NAME_LENGTH: u64 = 32;
const MAX_SYMBOL_LENGTH: u64 = 10;
const MAX_DECIMALS: u8 = 32;
const MAX_URI_LENGTH: u64 = 512;
/// Maximum possible coin supply.
const MAX_U128: u128 = 340282366920938463463374607431768211455;
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
struct Supply has key {
current: u128,
// option::none() means unlimited supply.
maximum: Option<u128>,
}
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
struct ConcurrentSupply has key {
current: Aggregator<u128>,
}
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
/// Metadata of a Fungible asset
struct Metadata has key {
/// Name of the fungible metadata, i.e., "USDT".
name: String,
/// Symbol of the fungible metadata, usually a shorter version of the name.
/// For example, Singapore Dollar is SGD.
symbol: String,
/// Number of decimals used for display purposes.
/// For example, if `decimals` equals `2`, a balance of `505` coins should
/// be displayed to a user as `5.05` (`505 / 10 ** 2`).
decimals: u8,
/// The Uniform Resource Identifier (uri) pointing to an image that can be used as the icon for this fungible
/// asset.
icon_uri: String,
/// The Uniform Resource Identifier (uri) pointing to the website for the fungible asset.
project_uri: String,
}
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
/// The store object that holds fungible assets of a specific type associated with an account.
struct FungibleStore has key {
/// The address of the base metadata object.
metadata: Object<Metadata>,
/// The balance of the fungible metadata.
balance: u64,
/// If true, owner transfer is disabled that only `TransferRef` can move in/out from this store.
frozen: bool,
}
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
struct DispatchFunctionStore has key {
withdraw_function: Option<FunctionInfo>,
deposit_function: Option<FunctionInfo>,
derived_balance_function: Option<FunctionInfo>,
}
/// FungibleAsset can be passed into function for type safety and to guarantee a specific amount.
/// FungibleAsset is ephemeral and cannot be stored directly. It must be deposited back into a store.
struct FungibleAsset {
metadata: Object<Metadata>,
amount: u64,
}
/// MintRef can be used to mint the fungible asset into an account's store.
struct MintRef has drop, store {
metadata: Object<Metadata>
}
/// TransferRef can be used to allow or disallow the owner of fungible assets from transferring the asset
/// and allow the holder of TransferRef to transfer fungible assets from any account.
struct TransferRef has drop, store {
metadata: Object<Metadata>
}
/// BurnRef can be used to burn fungible assets from a given holder account.
struct BurnRef has drop, store {
metadata: Object<Metadata>
}
#[event]
/// Emitted when fungible assets are deposited into a store.
struct Deposit has drop, store {
store: address,
amount: u64,
}
#[event]
/// Emitted when fungible assets are withdrawn from a store.
struct Withdraw has drop, store {
store: address,
amount: u64,
}
#[event]
/// Emitted when a store's frozen status is updated.
struct Frozen has drop, store {
store: address,
frozen: bool,
}
/// Make an existing object fungible by adding the Metadata resource.
/// This returns the capabilities to mint, burn, and transfer.
/// maximum_supply defines the behavior of maximum supply when monitoring:
/// - option::none(): Monitoring unlimited supply
/// (width of the field - MAX_U128 is the implicit maximum supply)
/// if option::some(MAX_U128) is used, it is treated as unlimited supply.
/// - option::some(max): Monitoring fixed supply with `max` as the maximum supply.
public fun add_fungibility(
constructor_ref: &ConstructorRef,
maximum_supply: Option<u128>,
name: String,
symbol: String,
decimals: u8,
icon_uri: String,
project_uri: String,
): Object<Metadata> {
assert!(!object::can_generate_delete_ref(constructor_ref), error::invalid_argument(EOBJECT_IS_DELETABLE));
let metadata_object_signer = &object::generate_signer(constructor_ref);
assert!(string::length(&name) <= MAX_NAME_LENGTH, error::out_of_range(ENAME_TOO_LONG));
assert!(string::length(&symbol) <= MAX_SYMBOL_LENGTH, error::out_of_range(ESYMBOL_TOO_LONG));
assert!(decimals <= MAX_DECIMALS, error::out_of_range(EDECIMALS_TOO_LARGE));
assert!(string::length(&icon_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG));
assert!(string::length(&project_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG));
move_to(metadata_object_signer,
Metadata {
name,
symbol,
decimals,
icon_uri,
project_uri,
}
);
if (features::concurrent_fungible_assets_enabled()) {
let unlimited = option::is_none(&maximum_supply);
move_to(metadata_object_signer, ConcurrentSupply {
current: if (unlimited) {
aggregator_v2::create_unbounded_aggregator()
} else {
aggregator_v2::create_aggregator(option::extract(&mut maximum_supply))
},
});
} else {
move_to(metadata_object_signer, Supply {
current: 0,
maximum: maximum_supply
});
};
object::object_from_constructor_ref<Metadata>(constructor_ref)
}
/// Create a fungible asset store whose transfer rule would be overloaded by the provided function.
public(friend) fun register_dispatch_functions(
constructor_ref: &ConstructorRef,
withdraw_function: Option<FunctionInfo>,
deposit_function: Option<FunctionInfo>,
derived_balance_function: Option<FunctionInfo>,
) {
// Verify that caller type matches callee type so wrongly typed function cannot be registered.
option::for_each_ref(&withdraw_function, |withdraw_function| {
let dispatcher_withdraw_function_info = function_info::new_function_info_from_address(
@aptos_framework,
string::utf8(b"dispatchable_fungible_asset"),
string::utf8(b"dispatchable_withdraw"),
);
assert!(
function_info::check_dispatch_type_compatibility(
&dispatcher_withdraw_function_info,
withdraw_function
),
error::invalid_argument(
EWITHDRAW_FUNCTION_SIGNATURE_MISMATCH
)
);
});
option::for_each_ref(&deposit_function, |deposit_function| {
let dispatcher_deposit_function_info = function_info::new_function_info_from_address(
@aptos_framework,
string::utf8(b"dispatchable_fungible_asset"),
string::utf8(b"dispatchable_deposit"),
);
// Verify that caller type matches callee type so wrongly typed function cannot be registered.
assert!(
function_info::check_dispatch_type_compatibility(
&dispatcher_deposit_function_info,
deposit_function
),
error::invalid_argument(
EDEPOSIT_FUNCTION_SIGNATURE_MISMATCH
)
);
});
option::for_each_ref(&derived_balance_function, |balance_function| {
let dispatcher_derived_balance_function_info = function_info::new_function_info_from_address(
@aptos_framework,
string::utf8(b"dispatchable_fungible_asset"),
string::utf8(b"dispatchable_derived_balance"),
);
// Verify that caller type matches callee type so wrongly typed function cannot be registered.
assert!(
function_info::check_dispatch_type_compatibility(
&dispatcher_derived_balance_function_info,
balance_function
),
error::invalid_argument(
EDERIVED_BALANCE_FUNCTION_SIGNATURE_MISMATCH
)
);
});
// Cannot register hook for APT.
assert!(
object::address_from_constructor_ref(constructor_ref) != @aptos_fungible_asset,
error::invalid_argument(EALREADY_REGISTERED)
);
assert!(
!object::can_generate_delete_ref(constructor_ref),
error::invalid_argument(EOBJECT_IS_DELETABLE)
);
assert!(
!exists<DispatchFunctionStore>(
object::address_from_constructor_ref(constructor_ref)
),
error::already_exists(EALREADY_REGISTERED)
);
let store_obj = &object::generate_signer(constructor_ref);
// Store the overload function hook.
move_to<DispatchFunctionStore>(
store_obj,
DispatchFunctionStore {
withdraw_function,
deposit_function,
derived_balance_function,
}
);
}
/// Creates a mint ref that can be used to mint fungible assets from the given fungible object's constructor ref.
/// This can only be called at object creation time as constructor_ref is only available then.
public fun generate_mint_ref(constructor_ref: &ConstructorRef): MintRef {
let metadata = object::object_from_constructor_ref<Metadata>(constructor_ref);
MintRef { metadata }
}
/// Creates a burn ref that can be used to burn fungible assets from the given fungible object's constructor ref.
/// This can only be called at object creation time as constructor_ref is only available then.
public fun generate_burn_ref(constructor_ref: &ConstructorRef): BurnRef {
let metadata = object::object_from_constructor_ref<Metadata>(constructor_ref);
BurnRef { metadata }
}
/// Creates a transfer ref that can be used to freeze/unfreeze/transfer fungible assets from the given fungible
/// object's constructor ref.
/// This can only be called at object creation time as constructor_ref is only available then.
public fun generate_transfer_ref(constructor_ref: &ConstructorRef): TransferRef {
let metadata = object::object_from_constructor_ref<Metadata>(constructor_ref);
TransferRef { metadata }
}
#[view]
/// Get the current supply from the `metadata` object.
public fun supply<T: key>(metadata: Object<T>): Option<u128> acquires Supply, ConcurrentSupply {
let metadata_address = object::object_address(&metadata);
if (exists<ConcurrentSupply>(metadata_address)) {
let supply = borrow_global<ConcurrentSupply>(metadata_address);
option::some(aggregator_v2::read(&supply.current))
} else if (exists<Supply>(metadata_address)) {
let supply = borrow_global<Supply>(metadata_address);
option::some(supply.current)
} else {
option::none()
}
}
#[view]
/// Get the maximum supply from the `metadata` object.
/// If supply is unlimited (or set explicitly to MAX_U128), none is returned
public fun maximum<T: key>(metadata: Object<T>): Option<u128> acquires Supply, ConcurrentSupply {
let metadata_address = object::object_address(&metadata);
if (exists<ConcurrentSupply>(metadata_address)) {
let supply = borrow_global<ConcurrentSupply>(metadata_address);
let max_value = aggregator_v2::max_value(&supply.current);
if (max_value == MAX_U128) {
option::none()
} else {
option::some(max_value)
}
} else if (exists<Supply>(metadata_address)) {
let supply = borrow_global<Supply>(metadata_address);
supply.maximum
} else {
option::none()
}
}
#[view]
/// Get the name of the fungible asset from the `metadata` object.
public fun name<T: key>(metadata: Object<T>): String acquires Metadata {
borrow_fungible_metadata(&metadata).name
}
#[view]
/// Get the symbol of the fungible asset from the `metadata` object.
public fun symbol<T: key>(metadata: Object<T>): String acquires Metadata {
borrow_fungible_metadata(&metadata).symbol
}
#[view]
/// Get the decimals from the `metadata` object.
public fun decimals<T: key>(metadata: Object<T>): u8 acquires Metadata {
borrow_fungible_metadata(&metadata).decimals
}
#[view]
/// Return whether the provided address has a store initialized.
public fun store_exists(store: address): bool {
exists<FungibleStore>(store)
}
/// Return the underlying metadata object
public fun metadata_from_asset(fa: &FungibleAsset): Object<Metadata> {
fa.metadata
}
#[view]
/// Return the underlying metadata object.
public fun store_metadata<T: key>(store: Object<T>): Object<Metadata> acquires FungibleStore {
borrow_store_resource(&store).metadata
}
/// Return the `amount` of a given fungible asset.
public fun amount(fa: &FungibleAsset): u64 {
fa.amount
}
#[view]
/// Get the balance of a given store.
public fun balance<T: key>(store: Object<T>): u64 acquires FungibleStore {
if (store_exists(object::object_address(&store))) {
borrow_store_resource(&store).balance
} else {
0
}
}
#[view]
/// Check whether the balance of a given store is >= `amount`.
public fun is_balance_at_least<T: key>(store: Object<T>, amount: u64): bool acquires FungibleStore {
let store_addr = object::object_address(&store);
if (store_exists(store_addr)) {
borrow_store_resource(&store).balance >= amount
} else {
amount == 0
}
}
#[view]
/// Return whether a store is frozen.
///
/// If the store has not been created, we default to returning false so deposits can be sent to it.
public fun is_frozen<T: key>(store: Object<T>): bool acquires FungibleStore {
store_exists(object::object_address(&store)) && borrow_store_resource(&store).frozen
}
#[view]
/// Return whether a fungible asset type is dispatchable.
public fun is_dispatchable(store: Object<Metadata>): bool acquires FungibleStore {
let fa_store = borrow_store_resource(&store);
let metadata_addr = object::object_address(&fa_store.metadata);
exists<DispatchFunctionStore>(metadata_addr)
}
public fun deposit_dispatch_function<T: key>(store: Object<T>): Option<FunctionInfo> acquires FungibleStore, DispatchFunctionStore {
let fa_store = borrow_store_resource(&store);
let metadata_addr = object::object_address(&fa_store.metadata);
if(exists<DispatchFunctionStore>(metadata_addr)) {
borrow_global<DispatchFunctionStore>(metadata_addr).deposit_function
} else {
option::none()
}
}
fun has_deposit_dispatch_function(metadata: Object<Metadata>): bool acquires DispatchFunctionStore {
let metadata_addr = object::object_address(&metadata);
// Short circuit on APT for better perf
if(metadata_addr != @aptos_fungible_asset && exists<DispatchFunctionStore>(metadata_addr)) {
option::is_some(&borrow_global<DispatchFunctionStore>(metadata_addr).deposit_function)
} else {
false
}
}
public fun withdraw_dispatch_function<T: key>(store: Object<T>): Option<FunctionInfo> acquires FungibleStore, DispatchFunctionStore {
let fa_store = borrow_store_resource(&store);
let metadata_addr = object::object_address(&fa_store.metadata);
if(exists<DispatchFunctionStore>(metadata_addr)) {
borrow_global<DispatchFunctionStore>(metadata_addr).withdraw_function
} else {
option::none()
}
}
fun has_withdraw_dispatch_function(metadata: Object<Metadata>): bool acquires DispatchFunctionStore {
let metadata_addr = object::object_address(&metadata);
// Short circuit on APT for better perf
if (metadata_addr != @aptos_fungible_asset && exists<DispatchFunctionStore>(metadata_addr)) {
option::is_some(&borrow_global<DispatchFunctionStore>(metadata_addr).withdraw_function)
} else {
false
}
}
public(friend) fun derived_balance_dispatch_function<T: key>(store: Object<T>): Option<FunctionInfo> acquires FungibleStore, DispatchFunctionStore {
let fa_store = borrow_store_resource(&store);
let metadata_addr = object::object_address(&fa_store.metadata);
if (exists<DispatchFunctionStore>(metadata_addr)) {
borrow_global<DispatchFunctionStore>(metadata_addr).derived_balance_function
} else {
option::none()
}
}
public fun asset_metadata(fa: &FungibleAsset): Object<Metadata> {
fa.metadata
}
/// Get the underlying metadata object from the `MintRef`.
public fun mint_ref_metadata(ref: &MintRef): Object<Metadata> {
ref.metadata
}
/// Get the underlying metadata object from the `TransferRef`.
public fun transfer_ref_metadata(ref: &TransferRef): Object<Metadata> {
ref.metadata
}
/// Get the underlying metadata object from the `BurnRef`.
public fun burn_ref_metadata(ref: &BurnRef): Object<Metadata> {
ref.metadata
}
/// Transfer an `amount` of fungible asset from `from_store`, which should be owned by `sender`, to `receiver`.
/// Note: it does not move the underlying object.
public entry fun transfer<T: key>(
sender: &signer,
from: Object<T>,
to: Object<T>,
amount: u64,
) acquires FungibleStore, DispatchFunctionStore {
let fa = withdraw(sender, from, amount);
deposit(to, fa);
}
/// Allow an object to hold a store for fungible assets.
/// Applications can use this to create multiple stores for isolating fungible assets for different purposes.
public fun create_store<T: key>(
constructor_ref: &ConstructorRef,
metadata: Object<T>,
): Object<FungibleStore> {
let store_obj = &object::generate_signer(constructor_ref);
move_to(store_obj, FungibleStore {
metadata: object::convert(metadata),
balance: 0,
frozen: false,
});
object::object_from_constructor_ref<FungibleStore>(constructor_ref)
}
/// Used to delete a store. Requires the store to be completely empty prior to removing it
public fun remove_store(delete_ref: &DeleteRef) acquires FungibleStore, FungibleAssetEvents {
let store = &object::object_from_delete_ref<FungibleStore>(delete_ref);
let addr = object::object_address(store);
let FungibleStore { metadata: _, balance, frozen: _ }
= move_from<FungibleStore>(addr);
assert!(balance == 0, error::permission_denied(EBALANCE_IS_NOT_ZERO));
// Cleanup deprecated event handles if exist.
if (exists<FungibleAssetEvents>(addr)) {
let FungibleAssetEvents {
deposit_events,
withdraw_events,
frozen_events,
} = move_from<FungibleAssetEvents>(addr);
event::destroy_handle(deposit_events);
event::destroy_handle(withdraw_events);
event::destroy_handle(frozen_events);
}
}
/// Withdraw `amount` of the fungible asset from `store` by the owner.
public fun withdraw<T: key>(
owner: &signer,
store: Object<T>,
amount: u64,
): FungibleAsset acquires FungibleStore, DispatchFunctionStore {
assert!(object::owns(store, signer::address_of(owner)), error::permission_denied(ENOT_STORE_OWNER));
assert!(store_exists(object::object_address(&store)), error::invalid_argument(ESTORE_IS_FROZEN));
let fa_store = borrow_store_resource(&store);
assert!(
!has_withdraw_dispatch_function(fa_store.metadata),
error::invalid_argument(EINVALID_DISPATCHABLE_OPERATIONS)
);
assert!(!fa_store.frozen, error::invalid_argument(ESTORE_IS_FROZEN));
withdraw_internal(object::object_address(&store), amount)
}
/// Deposit `amount` of the fungible asset to `store`.
public fun deposit<T: key>(store: Object<T>, fa: FungibleAsset) acquires FungibleStore, DispatchFunctionStore {
assert!(store_exists(object::object_address(&store)), error::permission_denied(ESTORE_IS_FROZEN));
let fa_store = borrow_store_resource(&store);
assert!(
!has_deposit_dispatch_function(fa_store.metadata),
error::invalid_argument(EINVALID_DISPATCHABLE_OPERATIONS)
);
assert!(!fa_store.frozen, error::permission_denied(ESTORE_IS_FROZEN));
deposit_internal(store, fa);
}
/// Withdraw `amount` of the fungible asset from `store` by the owner.
public(friend) fun withdraw_non_dispatch<T: key>(
owner: &signer,
store: Object<T>,
amount: u64,
): FungibleAsset acquires FungibleStore {
assert!(object::owns(store, signer::address_of(owner)), error::permission_denied(ENOT_STORE_OWNER));
assert!(!is_frozen(store), error::permission_denied(ESTORE_IS_FROZEN));
withdraw_internal(object::object_address(&store), amount)
}
/// Deposit `amount` of the fungible asset to `store`.
public(friend) fun deposit_non_dispatch<T: key>(store: Object<T>, fa: FungibleAsset) acquires FungibleStore {
assert!(!is_frozen(store), error::permission_denied(ESTORE_IS_FROZEN));
deposit_internal(store, fa);
}
/// Mint the specified `amount` of the fungible asset.
public fun mint(ref: &MintRef, amount: u64): FungibleAsset acquires Supply, ConcurrentSupply {
let metadata = ref.metadata;
mint_internal(metadata, amount)
}
/// CAN ONLY BE CALLED BY coin.move for migration.
public(friend) fun mint_internal(
metadata: Object<Metadata>,
amount: u64
): FungibleAsset acquires Supply, ConcurrentSupply {
increase_supply(&metadata, amount);
FungibleAsset {
metadata,
amount
}
}
/// Mint the specified `amount` of the fungible asset to a destination store.
public fun mint_to<T: key>(ref: &MintRef, store: Object<T>, amount: u64)
acquires FungibleStore, Supply, ConcurrentSupply, DispatchFunctionStore {
deposit(store, mint(ref, amount));
}
/// Enable/disable a store's ability to do direct transfers of the fungible asset.
public fun set_frozen_flag<T: key>(
ref: &TransferRef,
store: Object<T>,
frozen: bool,
) acquires FungibleStore {
assert!(
ref.metadata == store_metadata(store),
error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH),
);
set_frozen_flag_internal(store, frozen)
}
public(friend) fun set_frozen_flag_internal<T: key>(
store: Object<T>,
frozen: bool
) acquires FungibleStore {
let store_addr = object::object_address(&store);
borrow_global_mut<FungibleStore>(store_addr).frozen = frozen;
event::emit(Frozen { store: store_addr, frozen });
}
/// Burns a fungible asset
public fun burn(ref: &BurnRef, fa: FungibleAsset) acquires Supply, ConcurrentSupply {
assert!(
ref.metadata == metadata_from_asset(&fa),
error::invalid_argument(EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH)
);
burn_internal(fa);
}
/// CAN ONLY BE CALLED BY coin.move for migration.
public(friend) fun burn_internal(
fa: FungibleAsset
): u64 acquires Supply, ConcurrentSupply {
let FungibleAsset {
metadata,
amount
} = fa;
decrease_supply(&metadata, amount);
amount
}
/// Burn the `amount` of the fungible asset from the given store.
public fun burn_from<T: key>(
ref: &BurnRef,
store: Object<T>,
amount: u64
) acquires FungibleStore, Supply, ConcurrentSupply {
let metadata = ref.metadata;
assert!(metadata == store_metadata(store), error::invalid_argument(EBURN_REF_AND_STORE_MISMATCH));
let store_addr = object::object_address(&store);
burn(ref, withdraw_internal(store_addr, amount));
}
/// Withdraw `amount` of the fungible asset from the `store` ignoring `frozen`.
public fun withdraw_with_ref<T: key>(
ref: &TransferRef,
store: Object<T>,
amount: u64
): FungibleAsset acquires FungibleStore {
assert!(
ref.metadata == store_metadata(store),
error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH),
);
withdraw_internal(object::object_address(&store), amount)
}
/// Deposit the fungible asset into the `store` ignoring `frozen`.
public fun deposit_with_ref<T: key>(
ref: &TransferRef,
store: Object<T>,
fa: FungibleAsset
) acquires FungibleStore {
assert!(
ref.metadata == fa.metadata,
error::invalid_argument(ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH)
);
deposit_internal(store, fa);
}
/// Transfer `amount` of the fungible asset with `TransferRef` even it is frozen.
public fun transfer_with_ref<T: key>(
transfer_ref: &TransferRef,
from: Object<T>,
to: Object<T>,
amount: u64,
) acquires FungibleStore {
let fa = withdraw_with_ref(transfer_ref, from, amount);
deposit_with_ref(transfer_ref, to, fa);
}
/// Create a fungible asset with zero amount.
/// This can be useful when starting a series of computations where the initial value is 0.
public fun zero<T: key>(metadata: Object<T>): FungibleAsset {
FungibleAsset {
metadata: object::convert(metadata),
amount: 0,
}
}
/// Extract a given amount from the given fungible asset and return a new one.
public fun extract(fungible_asset: &mut FungibleAsset, amount: u64): FungibleAsset {
assert!(fungible_asset.amount >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE));
fungible_asset.amount = fungible_asset.amount - amount;
FungibleAsset {
metadata: fungible_asset.metadata,
amount,
}
}
/// "Merges" the two given fungible assets. The fungible asset passed in as `dst_fungible_asset` will have a value
/// equal to the sum of the two (`dst_fungible_asset` and `src_fungible_asset`).
public fun merge(dst_fungible_asset: &mut FungibleAsset, src_fungible_asset: FungibleAsset) {
let FungibleAsset { metadata, amount } = src_fungible_asset;
assert!(metadata == dst_fungible_asset.metadata, error::invalid_argument(EFUNGIBLE_ASSET_MISMATCH));
dst_fungible_asset.amount = dst_fungible_asset.amount + amount;
}
/// Destroy an empty fungible asset.
public fun destroy_zero(fungible_asset: FungibleAsset) {
let FungibleAsset { amount, metadata: _ } = fungible_asset;
assert!(amount == 0, error::invalid_argument(EAMOUNT_IS_NOT_ZERO));
}
public(friend) fun deposit_internal<T: key>(store: Object<T>, fa: FungibleAsset) acquires FungibleStore {
let FungibleAsset { metadata, amount } = fa;
if (amount == 0) return;
let store_metadata = store_metadata(store);
assert!(metadata == store_metadata, error::invalid_argument(EFUNGIBLE_ASSET_AND_STORE_MISMATCH));
let store_addr = object::object_address(&store);
let store = borrow_global_mut<FungibleStore>(store_addr);
store.balance = store.balance + amount;
event::emit(Deposit { store: store_addr, amount });
}
/// Extract `amount` of the fungible asset from `store`.
public(friend) fun withdraw_internal(
store_addr: address,
amount: u64,
): FungibleAsset acquires FungibleStore {
assert!(exists<FungibleStore>(store_addr), error::not_found(EFUNGIBLE_STORE_EXISTENCE));
let store = borrow_global_mut<FungibleStore>(store_addr);
let metadata = store.metadata;
if (amount != 0) {
assert!(store.balance >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE));
store.balance = store.balance - amount;
event::emit<Withdraw>(Withdraw { store: store_addr, amount });
};
FungibleAsset { metadata, amount }
}
/// Increase the supply of a fungible asset by minting.
fun increase_supply<T: key>(metadata: &Object<T>, amount: u64) acquires Supply, ConcurrentSupply {
if (amount == 0) {
return
};
let metadata_address = object::object_address(metadata);
if (exists<ConcurrentSupply>(metadata_address)) {
let supply = borrow_global_mut<ConcurrentSupply>(metadata_address);
assert!(
aggregator_v2::try_add(&mut supply.current, (amount as u128)),
error::out_of_range(EMAX_SUPPLY_EXCEEDED)
);
} else if (exists<Supply>(metadata_address)) {
let supply = borrow_global_mut<Supply>(metadata_address);
if (option::is_some(&supply.maximum)) {
let max = *option::borrow_mut(&mut supply.maximum);
assert!(
max - supply.current >= (amount as u128),
error::out_of_range(EMAX_SUPPLY_EXCEEDED)
)
};
supply.current = supply.current + (amount as u128);
} else {
abort error::not_found(ESUPPLY_NOT_FOUND)
}
}
/// Decrease the supply of a fungible asset by burning.
fun decrease_supply<T: key>(metadata: &Object<T>, amount: u64) acquires Supply, ConcurrentSupply {
if (amount == 0) {
return
};
let metadata_address = object::object_address(metadata);
if (exists<ConcurrentSupply>(metadata_address)) {
let supply = borrow_global_mut<ConcurrentSupply>(metadata_address);
assert!(
aggregator_v2::try_sub(&mut supply.current, (amount as u128)),
error::out_of_range(ESUPPLY_UNDERFLOW)
);
} else if (exists<Supply>(metadata_address)) {
assert!(exists<Supply>(metadata_address), error::not_found(ESUPPLY_NOT_FOUND));
let supply = borrow_global_mut<Supply>(metadata_address);
assert!(
supply.current >= (amount as u128),
error::invalid_state(ESUPPLY_UNDERFLOW)
);
supply.current = supply.current - (amount as u128);
} else {
assert!(false, error::not_found(ESUPPLY_NOT_FOUND));
}
}
inline fun borrow_fungible_metadata<T: key>(
metadata: &Object<T>
): &Metadata acquires Metadata {
let addr = object::object_address(metadata);
borrow_global<Metadata>(addr)
}
inline fun borrow_fungible_metadata_mut<T: key>(
metadata: &Object<T>
): &mut Metadata acquires Metadata {
let addr = object::object_address(metadata);
borrow_global_mut<Metadata>(addr)
}
inline fun borrow_store_resource<T: key>(store: &Object<T>): &FungibleStore acquires FungibleStore {
let store_addr = object::object_address(store);
assert!(exists<FungibleStore>(store_addr), error::not_found(EFUNGIBLE_STORE_EXISTENCE));
borrow_global<FungibleStore>(store_addr)
}
public fun upgrade_to_concurrent(
ref: &ExtendRef,
) acquires Supply {
let metadata_object_address = object::address_from_extend_ref(ref);
let metadata_object_signer = object::generate_signer_for_extending(ref);
assert!(
features::concurrent_fungible_assets_enabled(),
error::invalid_argument(ECONCURRENT_SUPPLY_NOT_ENABLED)
);
assert!(exists<Supply>(metadata_object_address), error::not_found(ESUPPLY_NOT_FOUND));
let Supply {
current,
maximum,
} = move_from<Supply>(metadata_object_address);
let unlimited = option::is_none(&maximum);
let supply = ConcurrentSupply {
current: if (unlimited) {
aggregator_v2::create_unbounded_aggregator()
}
else {
aggregator_v2::create_aggregator(option::extract(&mut maximum))
},
};
// update current state:
aggregator_v2::add(&mut supply.current, current);
move_to(&metadata_object_signer, supply);
}
#[test_only]
use aptos_framework::account;
#[test_only]
#[resource_group_member(group = aptos_framework::object::ObjectGroup)]
struct TestToken has key {}
#[test_only]
public fun create_test_token(creator: &signer): (ConstructorRef, Object<TestToken>) {
account::create_account_for_test(signer::address_of(creator));
let creator_ref = object::create_named_object(creator, b"TEST");
let object_signer = object::generate_signer(&creator_ref);
move_to(&object_signer, TestToken {});
let token = object::object_from_constructor_ref<TestToken>(&creator_ref);
(creator_ref, token)
}
#[test_only]
public fun init_test_metadata(constructor_ref: &ConstructorRef): (MintRef, TransferRef, BurnRef) {
add_fungibility(
constructor_ref,
option::some(100) /* max supply */,
string::utf8(b"TEST"),
string::utf8(b"@@"),
0,
string::utf8(b"http://www.example.com/favicon.ico"),
string::utf8(b"http://www.example.com"),
);
let mint_ref = generate_mint_ref(constructor_ref);
let burn_ref = generate_burn_ref(constructor_ref);
let transfer_ref = generate_transfer_ref(constructor_ref);
(mint_ref, transfer_ref, burn_ref)
}
#[test_only]
public fun create_fungible_asset(
creator: &signer
): (MintRef, TransferRef, BurnRef, Object<Metadata>) {
let (creator_ref, token_object) = create_test_token(creator);
let (mint, transfer, burn) = init_test_metadata(&creator_ref);
(mint, transfer, burn, object::convert(token_object))
}
#[test_only]
public fun create_test_store<T: key>(owner: &signer, metadata: Object<T>): Object<FungibleStore> {
let owner_addr = signer::address_of(owner);
if (!account::exists_at(owner_addr)) {
account::create_account_for_test(owner_addr);
};
create_store(&object::create_object_from_account(owner), metadata)
}
#[test(creator = @0xcafe)]
fun test_metadata_basic_flow(creator: &signer) acquires Metadata, Supply, ConcurrentSupply {
let (creator_ref, metadata) = create_test_token(creator);
init_test_metadata(&creator_ref);
assert!(supply(metadata) == option::some(0), 1);
assert!(maximum(metadata) == option::some(100), 2);
assert!(name(metadata) == string::utf8(b"TEST"), 3);
assert!(symbol(metadata) == string::utf8(b"@@"), 4);
assert!(decimals(metadata) == 0, 5);
increase_supply(&metadata, 50);
assert!(supply(metadata) == option::some(50), 6);
decrease_supply(&metadata, 30);
assert!(supply(metadata) == option::some(20), 7);
}
#[test(creator = @0xcafe)]
#[expected_failure(abort_code = 0x20005, location = Self)]
fun test_supply_overflow(creator: &signer) acquires Supply, ConcurrentSupply {
let (creator_ref, metadata) = create_test_token(creator);
init_test_metadata(&creator_ref);
increase_supply(&metadata, 101);
}
#[test(creator = @0xcafe)]
fun test_create_and_remove_store(creator: &signer) acquires FungibleStore, FungibleAssetEvents {
let (_, _, _, metadata) = create_fungible_asset(creator);
let creator_ref = object::create_object_from_account(creator);
create_store(&creator_ref, metadata);
let delete_ref = object::generate_delete_ref(&creator_ref);
remove_store(&delete_ref);
}
#[test(creator = @0xcafe, aaron = @0xface)]
fun test_e2e_basic_flow(
creator: &signer,
aaron: &signer,
) acquires FungibleStore, Supply, ConcurrentSupply, DispatchFunctionStore {
let (mint_ref, transfer_ref, burn_ref, test_token) = create_fungible_asset(creator);