-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathcontract.rs
6334 lines (5598 loc) · 199 KB
/
contract.rs
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 contract implements SNIP-20 standard:
/// https://github.com/SecretFoundation/SNIPs/blob/master/SNIP-20.md
use cosmwasm_std::{
entry_point, to_binary, Addr, BankMsg, Binary, Coin, CosmosMsg, Deps, DepsMut, Env,
MessageInfo, Response, StdError, StdResult, Storage, Uint128,
};
use rand::RngCore;
use secret_toolkit::permit::{Permit, RevokedPermits, TokenPermissions};
use secret_toolkit::utils::{pad_handle_result, pad_query_result};
use secret_toolkit::viewing_key::{ViewingKey, ViewingKeyStore};
use secret_toolkit_crypto::{sha_256, Prng, SHA256_HASH_SIZE};
use crate::batch;
use crate::msg::{
AllowanceGivenResult, AllowanceReceivedResult, ContractStatusLevel, Decoyable, ExecuteAnswer,
ExecuteMsg, InstantiateMsg, QueryAnswer, QueryMsg, QueryWithPermit, ResponseStatus::Success,
};
use crate::receiver::Snip20ReceiveMsg;
use crate::state::{
safe_add, AllowancesStore, BalancesStore, Config, MintersStore, PrngStore, ReceiverHashStore,
CONFIG, CONTRACT_STATUS, TOTAL_SUPPLY,
};
use crate::transaction_history::{
store_burn, store_deposit, store_mint, store_redeem, store_transfer, StoredExtendedTx,
StoredLegacyTransfer,
};
/// We make sure that responses from `handle` are padded to a multiple of this size.
pub const RESPONSE_BLOCK_SIZE: usize = 256;
pub const PREFIX_REVOKED_PERMITS: &str = "revoked_permits";
#[entry_point]
pub fn instantiate(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: InstantiateMsg,
) -> StdResult<Response> {
// Check name, symbol, decimals
if !is_valid_name(&msg.name) {
return Err(StdError::generic_err(
"Name is not in the expected format (3-30 UTF-8 bytes)",
));
}
if !is_valid_symbol(&msg.symbol) {
return Err(StdError::generic_err(
"Ticker symbol is not in expected format [A-Z]{3,20}",
));
}
if msg.decimals > 18 {
return Err(StdError::generic_err("Decimals must not exceed 18"));
}
let init_config = msg.config.unwrap_or_default();
let admin = match msg.admin {
Some(admin_addr) => deps.api.addr_validate(admin_addr.as_str())?,
None => info.sender,
};
let mut total_supply: u128 = 0;
let prng_seed_hashed = sha_256(&msg.prng_seed.0);
PrngStore::save(deps.storage, prng_seed_hashed)?;
{
let initial_balances = msg.initial_balances.unwrap_or_default();
for balance in initial_balances {
let amount = balance.amount.u128();
let balance_address = deps.api.addr_validate(balance.address.as_str())?;
// Here amount is also the amount to be added because the account has no prior balance
BalancesStore::update_balance(
deps.storage,
&balance_address,
amount,
true,
"",
&None,
&None,
)?;
if let Some(new_total_supply) = total_supply.checked_add(amount) {
total_supply = new_total_supply;
} else {
return Err(StdError::generic_err(
"The sum of all initial balances exceeds the maximum possible total supply",
));
}
store_mint(
deps.storage,
admin.clone(),
balance_address,
balance.amount,
msg.symbol.clone(),
Some("Initial Balance".to_string()),
&env.block,
&None,
&None,
)?;
}
}
let supported_denoms = match msg.supported_denoms {
None => vec![],
Some(x) => x,
};
CONFIG.save(
deps.storage,
&Config {
name: msg.name,
symbol: msg.symbol,
decimals: msg.decimals,
admin: admin.clone(),
total_supply_is_public: init_config.public_total_supply(),
deposit_is_enabled: init_config.deposit_enabled(),
redeem_is_enabled: init_config.redeem_enabled(),
mint_is_enabled: init_config.mint_enabled(),
burn_is_enabled: init_config.burn_enabled(),
contract_address: env.contract.address,
supported_denoms,
can_modify_denoms: init_config.can_modify_denoms(),
},
)?;
TOTAL_SUPPLY.save(deps.storage, &total_supply)?;
CONTRACT_STATUS.save(deps.storage, &ContractStatusLevel::NormalRun)?;
let minters = if init_config.mint_enabled() {
Vec::from([admin])
} else {
Vec::new()
};
MintersStore::save(deps.storage, minters)?;
ViewingKey::set_seed(deps.storage, &prng_seed_hashed);
Ok(Response::default())
}
fn get_address_position(
store: &mut dyn Storage,
decoys_size: usize,
entropy: &[u8; SHA256_HASH_SIZE],
) -> StdResult<usize> {
let mut rng = Prng::new(&PrngStore::load(store)?, entropy);
let mut new_contract_entropy = [0u8; 20];
rng.rng.fill_bytes(&mut new_contract_entropy);
let new_prng_seed = sha_256(&new_contract_entropy);
PrngStore::save(store, new_prng_seed)?;
// decoys_size is also an accepted output which means: set the account balance after you've set decoys' balanace
Ok(rng.rng.next_u64() as usize % (decoys_size + 1))
}
#[entry_point]
pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {
let contract_status = CONTRACT_STATUS.load(deps.storage)?;
let mut account_random_pos: Option<usize> = None;
let entropy = match msg.clone().get_entropy() {
None => [0u8; SHA256_HASH_SIZE],
Some(e) => sha_256(&e.0),
};
let decoys_size = msg.get_minimal_decoys_size();
if decoys_size != 0 {
account_random_pos = Some(get_address_position(deps.storage, decoys_size, &entropy)?);
}
match contract_status {
ContractStatusLevel::StopAll | ContractStatusLevel::StopAllButRedeems => {
let response = match msg {
ExecuteMsg::SetContractStatus { level, .. } => {
set_contract_status(deps, info, level)
}
ExecuteMsg::Redeem {
amount,
denom,
decoys,
..
} if contract_status == ContractStatusLevel::StopAllButRedeems => {
try_redeem(deps, env, info, amount, denom, decoys, account_random_pos)
}
_ => Err(StdError::generic_err(
"This contract is stopped and this action is not allowed",
)),
};
return pad_handle_result(response, RESPONSE_BLOCK_SIZE);
}
ContractStatusLevel::NormalRun => {} // If it's a normal run just continue
}
let response = match msg.clone() {
// Native
ExecuteMsg::Deposit { decoys, .. } => {
try_deposit(deps, env, info, decoys, account_random_pos)
}
ExecuteMsg::Redeem {
amount,
denom,
decoys,
..
} => try_redeem(deps, env, info, amount, denom, decoys, account_random_pos),
// Base
ExecuteMsg::Transfer {
recipient,
amount,
memo,
decoys,
..
} => try_transfer(
deps,
env,
info,
recipient,
amount,
memo,
decoys,
account_random_pos,
),
ExecuteMsg::Send {
recipient,
recipient_code_hash,
amount,
msg,
memo,
decoys,
..
} => try_send(
deps,
env,
info,
recipient,
recipient_code_hash,
amount,
memo,
msg,
decoys,
account_random_pos,
),
ExecuteMsg::BatchTransfer { actions, .. } => {
try_batch_transfer(deps, env, info, actions, account_random_pos)
}
ExecuteMsg::BatchSend { actions, .. } => {
try_batch_send(deps, env, info, actions, account_random_pos)
}
ExecuteMsg::Burn {
amount,
memo,
decoys,
..
} => try_burn(deps, env, info, amount, memo, decoys, account_random_pos),
ExecuteMsg::RegisterReceive { code_hash, .. } => {
try_register_receive(deps, info, code_hash)
}
ExecuteMsg::CreateViewingKey { entropy, .. } => try_create_key(deps, env, info, entropy),
ExecuteMsg::SetViewingKey { key, .. } => try_set_key(deps, info, key),
// Allowance
ExecuteMsg::IncreaseAllowance {
spender,
amount,
expiration,
..
} => try_increase_allowance(deps, env, info, spender, amount, expiration),
ExecuteMsg::DecreaseAllowance {
spender,
amount,
expiration,
..
} => try_decrease_allowance(deps, env, info, spender, amount, expiration),
ExecuteMsg::TransferFrom {
owner,
recipient,
amount,
memo,
decoys,
..
} => try_transfer_from(
deps,
&env,
info,
owner,
recipient,
amount,
memo,
decoys,
account_random_pos,
),
ExecuteMsg::SendFrom {
owner,
recipient,
recipient_code_hash,
amount,
msg,
memo,
decoys,
..
} => try_send_from(
deps,
env,
&info,
owner,
recipient,
recipient_code_hash,
amount,
memo,
msg,
decoys,
account_random_pos,
),
ExecuteMsg::BatchTransferFrom { actions, .. } => {
try_batch_transfer_from(deps, &env, info, actions, account_random_pos)
}
ExecuteMsg::BatchSendFrom { actions, .. } => {
try_batch_send_from(deps, env, &info, actions, account_random_pos)
}
ExecuteMsg::BurnFrom {
owner,
amount,
memo,
decoys,
..
} => try_burn_from(
deps,
&env,
info,
owner,
amount,
memo,
decoys,
account_random_pos,
),
ExecuteMsg::BatchBurnFrom { actions, .. } => {
try_batch_burn_from(deps, &env, info, actions, account_random_pos)
}
// Mint
ExecuteMsg::Mint {
recipient,
amount,
memo,
decoys,
..
} => try_mint(
deps,
env,
info,
recipient,
amount,
memo,
decoys,
account_random_pos,
),
ExecuteMsg::BatchMint { actions, .. } => {
try_batch_mint(deps, env, info, actions, account_random_pos)
}
// Other
ExecuteMsg::ChangeAdmin { address, .. } => change_admin(deps, info, address),
ExecuteMsg::SetContractStatus { level, .. } => set_contract_status(deps, info, level),
ExecuteMsg::AddMinters { minters, .. } => add_minters(deps, info, minters),
ExecuteMsg::RemoveMinters { minters, .. } => remove_minters(deps, info, minters),
ExecuteMsg::SetMinters { minters, .. } => set_minters(deps, info, minters),
ExecuteMsg::RevokePermit { permit_name, .. } => revoke_permit(deps, info, permit_name),
ExecuteMsg::AddSupportedDenoms { denoms, .. } => add_supported_denoms(deps, info, denoms),
ExecuteMsg::RemoveSupportedDenoms { denoms, .. } => {
remove_supported_denoms(deps, info, denoms)
}
};
pad_handle_result(response, RESPONSE_BLOCK_SIZE)
}
#[entry_point]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
pad_query_result(
match msg {
QueryMsg::TokenInfo {} => query_token_info(deps.storage),
QueryMsg::TokenConfig {} => query_token_config(deps.storage),
QueryMsg::ContractStatus {} => query_contract_status(deps.storage),
QueryMsg::ExchangeRate {} => query_exchange_rate(deps.storage),
QueryMsg::Minters { .. } => query_minters(deps),
QueryMsg::WithPermit { permit, query } => permit_queries(deps, permit, query),
_ => viewing_keys_queries(deps, msg),
},
RESPONSE_BLOCK_SIZE,
)
}
fn permit_queries(deps: Deps, permit: Permit, query: QueryWithPermit) -> Result<Binary, StdError> {
// Validate permit content
let token_address = CONFIG.load(deps.storage)?.contract_address;
let account = secret_toolkit::permit::validate(
deps,
PREFIX_REVOKED_PERMITS,
&permit,
token_address.into_string(),
None,
)?;
// Permit validated! We can now execute the query.
match query {
QueryWithPermit::Balance {} => {
if !permit.check_permission(&TokenPermissions::Balance) {
return Err(StdError::generic_err(format!(
"No permission to query balance, got permissions {:?}",
permit.params.permissions
)));
}
query_balance(deps, account)
}
QueryWithPermit::TransferHistory {
page,
page_size,
should_filter_decoys,
} => {
if !permit.check_permission(&TokenPermissions::History) {
return Err(StdError::generic_err(format!(
"No permission to query history, got permissions {:?}",
permit.params.permissions
)));
}
query_transfers(
deps,
account,
page.unwrap_or(0),
page_size,
should_filter_decoys,
)
}
QueryWithPermit::TransactionHistory {
page,
page_size,
should_filter_decoys,
} => {
if !permit.check_permission(&TokenPermissions::History) {
return Err(StdError::generic_err(format!(
"No permission to query history, got permissions {:?}",
permit.params.permissions
)));
}
query_transactions(
deps,
account,
page.unwrap_or(0),
page_size,
should_filter_decoys,
)
}
QueryWithPermit::Allowance { owner, spender } => {
if !permit.check_permission(&TokenPermissions::Allowance) {
return Err(StdError::generic_err(format!(
"No permission to query allowance, got permissions {:?}",
permit.params.permissions
)));
}
if account != owner && account != spender {
return Err(StdError::generic_err(format!(
"Cannot query allowance. Requires permit for either owner {:?} or spender {:?}, got permit for {:?}",
owner.as_str(), spender.as_str(), account.as_str()
)));
}
query_allowance(deps, owner, spender)
}
QueryWithPermit::AllowancesGiven {
owner,
page,
page_size,
} => {
if account != owner {
return Err(StdError::generic_err(
"Cannot query allowance. Requires permit for owner",
));
}
// we really should add a check_permission(s) function.. an owner permit should
// just give you permissions to do everything
if !permit.check_permission(&TokenPermissions::Allowance)
&& !permit.check_permission(&TokenPermissions::Owner)
{
return Err(StdError::generic_err(format!(
"No permission to query all allowances, got permissions {:?}",
permit.params.permissions
)));
}
query_allowances_given(deps, account, page.unwrap_or(0), page_size)
}
QueryWithPermit::AllowancesReceived {
spender,
page,
page_size,
} => {
if account != spender {
return Err(StdError::generic_err(
"Cannot query allowance. Requires permit for spender",
));
}
if !permit.check_permission(&TokenPermissions::Allowance)
&& !permit.check_permission(&TokenPermissions::Owner)
{
return Err(StdError::generic_err(format!(
"No permission to query all allowed, got permissions {:?}",
permit.params.permissions
)));
}
query_allowances_received(deps, account, page.unwrap_or(0), page_size)
}
}
}
pub fn viewing_keys_queries(deps: Deps, msg: QueryMsg) -> StdResult<Binary> {
let (addresses, key) = msg.get_validation_params(deps.api)?;
for address in addresses {
let result = ViewingKey::check(deps.storage, address.as_str(), key.as_str());
if result.is_ok() {
return match msg {
// Base
QueryMsg::Balance { address, .. } => query_balance(deps, address),
QueryMsg::TransferHistory {
address,
page,
page_size,
should_filter_decoys,
..
} => query_transfers(
deps,
address,
page.unwrap_or(0),
page_size,
should_filter_decoys,
),
QueryMsg::TransactionHistory {
address,
page,
page_size,
should_filter_decoys,
..
} => query_transactions(
deps,
address,
page.unwrap_or(0),
page_size,
should_filter_decoys,
),
QueryMsg::Allowance { owner, spender, .. } => query_allowance(deps, owner, spender),
QueryMsg::AllowancesGiven {
owner,
page,
page_size,
..
} => query_allowances_given(deps, owner, page.unwrap_or(0), page_size),
QueryMsg::AllowancesReceived {
spender,
page,
page_size,
..
} => query_allowances_received(deps, spender, page.unwrap_or(0), page_size),
_ => panic!("This query type does not require authentication"),
};
}
}
to_binary(&QueryAnswer::ViewingKeyError {
msg: "Wrong viewing key for this address or viewing key not set".to_string(),
})
}
fn query_exchange_rate(storage: &dyn Storage) -> StdResult<Binary> {
let constants = CONFIG.load(storage)?;
if constants.deposit_is_enabled || constants.redeem_is_enabled {
let rate: Uint128;
let denom: String;
// if token has more decimals than SCRT, you get magnitudes of SCRT per token
if constants.decimals >= 6 {
rate = Uint128::new(10u128.pow(constants.decimals as u32 - 6));
denom = "SCRT".to_string();
// if token has less decimals, you get magnitudes token for SCRT
} else {
rate = Uint128::new(10u128.pow(6 - constants.decimals as u32));
denom = constants.symbol;
}
return to_binary(&QueryAnswer::ExchangeRate { rate, denom });
}
to_binary(&QueryAnswer::ExchangeRate {
rate: Uint128::zero(),
denom: String::new(),
})
}
fn query_token_info(storage: &dyn Storage) -> StdResult<Binary> {
let constants = CONFIG.load(storage)?;
let total_supply = if constants.total_supply_is_public {
Some(Uint128::new(TOTAL_SUPPLY.load(storage)?))
} else {
None
};
to_binary(&QueryAnswer::TokenInfo {
name: constants.name,
symbol: constants.symbol,
decimals: constants.decimals,
total_supply,
})
}
fn query_token_config(storage: &dyn Storage) -> StdResult<Binary> {
let constants = CONFIG.load(storage)?;
to_binary(&QueryAnswer::TokenConfig {
public_total_supply: constants.total_supply_is_public,
deposit_enabled: constants.deposit_is_enabled,
redeem_enabled: constants.redeem_is_enabled,
mint_enabled: constants.mint_is_enabled,
burn_enabled: constants.burn_is_enabled,
supported_denoms: constants.supported_denoms,
})
}
fn query_contract_status(storage: &dyn Storage) -> StdResult<Binary> {
let contract_status = CONTRACT_STATUS.load(storage)?;
to_binary(&QueryAnswer::ContractStatus {
status: contract_status,
})
}
pub fn query_transfers(
deps: Deps,
account: String,
page: u32,
page_size: u32,
should_filter_decoys: bool,
) -> StdResult<Binary> {
// Notice that if query_transfers() was called by a viewking-key call, the address of 'account'
// has already been validated.
// The address of 'account' should not be validated if query_transfers() was called by a permit
// call, for compatibility with non-Secret addresses.
let account = Addr::unchecked(account);
let (txs, total) = StoredLegacyTransfer::get_transfers(
deps.storage,
account,
page,
page_size,
should_filter_decoys,
)?;
let result = QueryAnswer::TransferHistory {
txs,
total: Some(total),
};
to_binary(&result)
}
pub fn query_transactions(
deps: Deps,
account: String,
page: u32,
page_size: u32,
should_filter_decoys: bool,
) -> StdResult<Binary> {
// Notice that if query_transactions() was called by a viewking-key call, the address of
// 'account' has already been validated.
// The address of 'account' should not be validated if query_transactions() was called by a
// permit call, for compatibility with non-Secret addresses.
let account = Addr::unchecked(account);
let (txs, total) =
StoredExtendedTx::get_txs(deps.storage, account, page, page_size, should_filter_decoys)?;
let result = QueryAnswer::TransactionHistory {
txs,
total: Some(total),
};
to_binary(&result)
}
pub fn query_balance(deps: Deps, account: String) -> StdResult<Binary> {
// Notice that if query_balance() was called by a viewking-key call, the address of 'account'
// has already been validated.
// The address of 'account' should not be validated if query_balance() was called by a permit
// call, for compatibility with non-Secret addresses.
let account = Addr::unchecked(account);
let amount = Uint128::new(BalancesStore::load(deps.storage, &account));
let response = QueryAnswer::Balance { amount };
to_binary(&response)
}
fn query_minters(deps: Deps) -> StdResult<Binary> {
let minters = MintersStore::load(deps.storage)?;
let response = QueryAnswer::Minters { minters };
to_binary(&response)
}
fn change_admin(deps: DepsMut, info: MessageInfo, address: String) -> StdResult<Response> {
let address = deps.api.addr_validate(address.as_str())?;
let mut constants = CONFIG.load(deps.storage)?;
check_if_admin(&constants.admin, &info.sender)?;
constants.admin = address;
CONFIG.save(deps.storage, &constants)?;
Ok(Response::new().set_data(to_binary(&ExecuteAnswer::ChangeAdmin { status: Success })?))
}
fn add_supported_denoms(
deps: DepsMut,
info: MessageInfo,
denoms: Vec<String>,
) -> StdResult<Response> {
let mut config = CONFIG.load(deps.storage)?;
check_if_admin(&config.admin, &info.sender)?;
if !config.can_modify_denoms {
return Err(StdError::generic_err(
"Cannot modify denoms for this contract",
));
}
for denom in denoms.iter() {
if !config.supported_denoms.contains(denom) {
config.supported_denoms.push(denom.clone());
}
}
CONFIG.save(deps.storage, &config)?;
Ok(
Response::new().set_data(to_binary(&ExecuteAnswer::AddSupportedDenoms {
status: Success,
})?),
)
}
fn remove_supported_denoms(
deps: DepsMut,
info: MessageInfo,
denoms: Vec<String>,
) -> StdResult<Response> {
let mut config = CONFIG.load(deps.storage)?;
check_if_admin(&config.admin, &info.sender)?;
if !config.can_modify_denoms {
return Err(StdError::generic_err(
"Cannot modify denoms for this contract",
));
}
for denom in denoms.iter() {
config.supported_denoms.retain(|x| x != denom);
}
CONFIG.save(deps.storage, &config)?;
Ok(
Response::new().set_data(to_binary(&ExecuteAnswer::RemoveSupportedDenoms {
status: Success,
})?),
)
}
#[allow(clippy::too_many_arguments)]
fn try_mint_impl(
deps: &mut DepsMut,
minter: Addr,
recipient: Addr,
amount: Uint128,
denom: String,
memo: Option<String>,
block: &cosmwasm_std::BlockInfo,
decoys: Option<Vec<Addr>>,
account_random_pos: Option<usize>,
) -> StdResult<()> {
let raw_amount = amount.u128();
BalancesStore::update_balance(
deps.storage,
&recipient,
raw_amount,
true,
"",
&decoys,
&account_random_pos,
)?;
store_mint(
deps.storage,
minter,
recipient,
amount,
denom,
memo,
block,
&decoys,
&account_random_pos,
)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn try_mint(
mut deps: DepsMut,
env: Env,
info: MessageInfo,
recipient: String,
amount: Uint128,
memo: Option<String>,
decoys: Option<Vec<Addr>>,
account_random_pos: Option<usize>,
) -> StdResult<Response> {
let recipient = deps.api.addr_validate(recipient.as_str())?;
let constants = CONFIG.load(deps.storage)?;
if !constants.mint_is_enabled {
return Err(StdError::generic_err(
"Mint functionality is not enabled for this token.",
));
}
// let minters = MintersStore::load(deps.storage)?;
// if !minters.contains(&info.sender) {
// return Err(StdError::generic_err(
// "Minting is allowed to minter accounts only",
// ));
// }
let mut total_supply = TOTAL_SUPPLY.load(deps.storage)?;
let minted_amount = safe_add(&mut total_supply, amount.u128());
TOTAL_SUPPLY.save(deps.storage, &total_supply)?;
// Note that even when minted_amount is equal to 0 we still want to perform the operations for logic consistency
try_mint_impl(
&mut deps,
info.sender,
recipient,
Uint128::new(minted_amount),
constants.symbol,
memo,
&env.block,
decoys,
account_random_pos,
)?;
Ok(Response::new().set_data(to_binary(&ExecuteAnswer::Mint { status: Success })?))
}
fn try_batch_mint(
mut deps: DepsMut,
env: Env,
info: MessageInfo,
actions: Vec<batch::MintAction>,
account_random_pos: Option<usize>,
) -> StdResult<Response> {
let constants = CONFIG.load(deps.storage)?;
if !constants.mint_is_enabled {
return Err(StdError::generic_err(
"Mint functionality is not enabled for this token.",
));
}
let minters = MintersStore::load(deps.storage)?;
if !minters.contains(&info.sender) {
return Err(StdError::generic_err(
"Minting is allowed to minter accounts only",
));
}
let mut total_supply = TOTAL_SUPPLY.load(deps.storage)?;
// Quick loop to check that the total of amounts is valid
for action in actions {
let actual_amount = safe_add(&mut total_supply, action.amount.u128());
let recipient = deps.api.addr_validate(action.recipient.as_str())?;
try_mint_impl(
&mut deps,
info.sender.clone(),
recipient,
Uint128::new(actual_amount),
constants.symbol.clone(),
action.memo,
&env.block,
action.decoys,
account_random_pos,
)?;
}
TOTAL_SUPPLY.save(deps.storage, &total_supply)?;
Ok(Response::new().set_data(to_binary(&ExecuteAnswer::BatchMint { status: Success })?))
}
pub fn try_set_key(deps: DepsMut, info: MessageInfo, key: String) -> StdResult<Response> {
ViewingKey::set(deps.storage, info.sender.as_str(), key.as_str());
Ok(
Response::new().set_data(to_binary(&ExecuteAnswer::SetViewingKey {
status: Success,
})?),
)
}
pub fn try_create_key(
deps: DepsMut,
env: Env,
info: MessageInfo,
entropy: String,
) -> StdResult<Response> {
let key = ViewingKey::create(
deps.storage,
&info,
&env,
info.sender.as_str(),
entropy.as_ref(),
);
Ok(Response::new().set_data(to_binary(&ExecuteAnswer::CreateViewingKey { key })?))
}
fn set_contract_status(
deps: DepsMut,
info: MessageInfo,
status_level: ContractStatusLevel,
) -> StdResult<Response> {
let constants = CONFIG.load(deps.storage)?;
check_if_admin(&constants.admin, &info.sender)?;
CONTRACT_STATUS.save(deps.storage, &status_level)?;
Ok(
Response::new().set_data(to_binary(&ExecuteAnswer::SetContractStatus {
status: Success,
})?),
)
}
pub fn query_allowance(deps: Deps, owner: String, spender: String) -> StdResult<Binary> {
// Notice that if query_allowance() was called by a viewing-key call, the addresses of 'owner'
// and 'spender' have already been validated.
// The addresses of 'owner' and 'spender' should not be validated if query_allowance() was
// called by a permit call, for compatibility with non-Secret addresses.
let owner = Addr::unchecked(owner);
let spender = Addr::unchecked(spender);
let allowance = AllowancesStore::load(deps.storage, &owner, &spender);
let response = QueryAnswer::Allowance {
owner,
spender,
allowance: Uint128::new(allowance.amount),
expiration: allowance.expiration,
};
to_binary(&response)
}
pub fn query_allowances_given(
deps: Deps,
owner: String,
page: u32,
page_size: u32,
) -> StdResult<Binary> {
// Notice that if query_all_allowances_given() was called by a viewing-key call,
// the address of 'owner' has already been validated.
// The addresses of 'owner' should not be validated if query_all_allowances_given() was
// called by a permit call, for compatibility with non-Secret addresses.
let owner = Addr::unchecked(owner);
let all_allowances =
AllowancesStore::all_allowances(deps.storage, &owner, page, page_size).unwrap_or(vec![]);
let allowances_result = all_allowances
.into_iter()
.map(|(spender, allowance)| AllowanceGivenResult {
spender,
allowance: Uint128::from(allowance.amount),
expiration: allowance.expiration,
})
.collect();
let response = QueryAnswer::AllowancesGiven {