-
Notifications
You must be signed in to change notification settings - Fork 11
/
contract.rs
2366 lines (2044 loc) · 81.7 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
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
coin, coins, to_binary, Addr, BankMsg, Binary, Coin, CustomQuery, Decimal, Deps, DepsMut,
Empty, Env, MessageInfo, Order, StdResult, Storage, Uint128,
};
use std::cmp::min;
use std::ops::Sub;
use cw2::set_contract_version;
use cw_storage_plus::Bound;
use cw_utils::maybe_addr;
use tg4::{
HooksResponse, Member, MemberChangedHookMsg, MemberDiff, MemberInfo, MemberListResponse,
MemberResponse, TotalPointsResponse,
};
use tg_bindings::{
request_privileges, Privilege, PrivilegeChangeMsg, TgradeMsg, TgradeQuery, TgradeSudoMsg,
};
use tg_utils::{
ensure_from_older_version, members, validate_portion, Duration, ADMIN, HOOKS, PREAUTH_HOOKS,
PREAUTH_SLASHING, SLASHERS, TOTAL,
};
use crate::error::ContractError;
use crate::msg::{
ClaimsResponse, ExecuteMsg, InstantiateMsg, PreauthResponse, QueryMsg, StakedResponse,
UnbondingPeriodResponse,
};
use crate::state::{claims, Config, CONFIG, STAKE, STAKE_VESTING};
pub type Response = cosmwasm_std::Response<TgradeMsg>;
pub type SubMsg = cosmwasm_std::SubMsg<TgradeMsg>;
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:tg4-stake";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
// Note, you can use StdResult in some functions where you do not
// make use of the custom errors
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
mut deps: DepsMut<TgradeQuery>,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
let api = deps.api;
ADMIN.set(deps.branch(), maybe_addr(api, msg.admin)?)?;
PREAUTH_HOOKS.set_auth(deps.storage, msg.preauths_hooks)?;
PREAUTH_SLASHING.set_auth(deps.storage, msg.preauths_slashing)?;
// min_bond is at least 1, so 0 stake -> non-membership
let min_bond = if msg.min_bond == Uint128::zero() {
Uint128::new(1)
} else {
msg.min_bond
};
let config = Config {
denom: msg.denom,
tokens_per_point: msg.tokens_per_point,
min_bond,
unbonding_period: Duration::new(msg.unbonding_period),
auto_return_limit: msg.auto_return_limit,
};
CONFIG.save(deps.storage, &config)?;
TOTAL.save(deps.storage, &0)?;
SLASHERS.instantiate(deps.storage)?;
Ok(Response::default())
}
// And declare a custom Error variant for the ones where you will want to make use of it
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut<TgradeQuery>,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
let api = deps.api;
match msg {
ExecuteMsg::UpdateAdmin { admin } => ADMIN
.execute_update_admin(deps, info, maybe_addr(api, admin)?)
.map_err(Into::into),
ExecuteMsg::AddHook { addr } => execute_add_hook(deps, info, addr),
ExecuteMsg::RemoveHook { addr } => execute_remove_hook(deps, info, addr),
ExecuteMsg::Bond { vesting_tokens } => execute_bond(deps, env, info, vesting_tokens),
ExecuteMsg::Unbond {
tokens: Coin { amount, denom },
} => execute_unbond(deps, env, info, amount, denom),
ExecuteMsg::Claim {} => execute_claim(deps, env, info),
ExecuteMsg::AddSlasher { addr } => execute_add_slasher(deps, info, addr),
ExecuteMsg::RemoveSlasher { addr } => execute_remove_slasher(deps, info, addr),
ExecuteMsg::Slash { addr, portion } => execute_slash(deps, env, info, addr, portion),
}
}
pub fn execute_add_hook<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
hook: String,
) -> Result<Response, ContractError> {
// custom guard: using a preauth OR being admin
if !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
PREAUTH_HOOKS.use_auth(deps.storage)?;
}
// add the hook
HOOKS.add_hook(deps.storage, deps.api.addr_validate(&hook)?)?;
// response
let res = Response::new()
.add_attribute("action", "add_hook")
.add_attribute("hook", hook)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_remove_hook<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
hook: String,
) -> Result<Response, ContractError> {
// custom guard: self-removal OR being admin
let hook_addr = deps.api.addr_validate(&hook)?;
if info.sender != hook_addr && !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
return Err(ContractError::Unauthorized(
"Hook address is not same as sender's and sender is not an admin".to_owned(),
));
}
// remove the hook
HOOKS.remove_hook(deps.storage, hook_addr)?;
// response
let res = Response::new()
.add_attribute("action", "remove_hook")
.add_attribute("hook", hook)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_bond<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
vesting_tokens: Option<Coin>,
) -> Result<Response, ContractError> {
let cfg = CONFIG.load(deps.storage)?;
let amount = validate_funds(&info.funds, &cfg.denom)?;
let vesting_amount = vesting_tokens
.map(|v| validate_funds(&[v], &cfg.denom))
.transpose()?
.unwrap_or_default();
if amount + vesting_amount == Uint128::zero() {
return Err(ContractError::NoFunds {});
}
// update the sender's stake
let new_stake = STAKE.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default() + amount)
})?;
let mut res = Response::new()
.add_attribute("action", "bond")
.add_attribute("amount", amount)
.add_attribute("sender", &info.sender);
// Update the sender's vesting stake
let new_vesting_stake =
STAKE_VESTING.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default() + vesting_amount)
})?;
// Delegate (stake to contract) to sender's vesting account
if vesting_amount > Uint128::zero() {
let msg = TgradeMsg::Delegate {
funds: coin(vesting_amount.into(), cfg.denom.clone()),
staker: info.sender.to_string(),
};
res = res
.add_message(msg)
.add_attribute("vesting_amount", vesting_amount);
}
// Update membership messages
res = res.add_submessages(update_membership(
deps.storage,
info.sender,
new_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
pub fn execute_unbond<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
amount: Uint128,
denom: String,
) -> Result<Response, ContractError> {
// provide them a claim
let cfg = CONFIG.load(deps.storage)?;
if cfg.denom != denom {
return Err(ContractError::InvalidDenom(denom));
}
// Load stake first for comparison
let stake = STAKE
.may_load(deps.storage, &info.sender)?
.unwrap_or_default();
// Reduce the sender's stake - saturating if insufficient
let new_stake = STAKE.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().saturating_sub(amount))
})?;
let mut res = Response::new()
.add_attribute("action", "unbond")
.add_attribute("amount", amount)
.add_attribute("denom", &denom)
.add_attribute("sender", &info.sender);
// Reduce the sender's vesting stake - aborting if insufficient
let vesting_amount = amount.saturating_sub(stake);
let new_vesting_stake =
STAKE_VESTING.update(deps.storage, &info.sender, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().checked_sub(vesting_amount)?)
})?;
// Undelegate (unstake from contract) to sender's vesting account
if vesting_amount > Uint128::zero() {
let msg = TgradeMsg::Undelegate {
funds: coin(vesting_amount.into(), cfg.denom.clone()),
recipient: info.sender.to_string(),
};
res = res
.add_message(msg)
.add_attribute("vesting_amount", vesting_amount);
}
// Create claim for unbonded liquid amount
let completion = cfg.unbonding_period.after(&env.block);
claims().create_claim(
deps.storage,
info.sender.clone(),
min(stake, amount),
completion,
env.block.height,
)?;
res = res.add_attribute("completion_time", completion.time().nanos().to_string());
// Update membership messages
res = res.add_submessages(update_membership(
deps.storage,
info.sender,
new_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
pub fn execute_add_slasher<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
slasher: String,
) -> Result<Response, ContractError> {
// custom guard: using a preauth OR being admin
if !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
PREAUTH_SLASHING.use_auth(deps.storage)?;
}
// add the slasher
SLASHERS.add_slasher(deps.storage, deps.api.addr_validate(&slasher)?)?;
// response
let res = Response::new()
.add_attribute("action", "add_slasher")
.add_attribute("slasher", slasher)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_remove_slasher<Q: CustomQuery>(
deps: DepsMut<Q>,
info: MessageInfo,
slasher: String,
) -> Result<Response, ContractError> {
// custom guard: self-removal OR being admin
let slasher_addr = Addr::unchecked(&slasher);
if info.sender != slasher_addr && !ADMIN.is_admin(deps.as_ref(), &info.sender)? {
return Err(ContractError::Unauthorized(
"Only slasher might remove himself and sender is not an admin".to_owned(),
));
}
// remove the slasher
SLASHERS.remove_slasher(deps.storage, slasher_addr)?;
// response
let res = Response::new()
.add_attribute("action", "remove_slasher")
.add_attribute("slasher", slasher)
.add_attribute("sender", info.sender);
Ok(res)
}
pub fn execute_slash<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
addr: String,
portion: Decimal,
) -> Result<Response, ContractError> {
if !SLASHERS.is_slasher(deps.storage, &info.sender)? {
return Err(ContractError::Unauthorized(
"Sender is not on slashers list".to_owned(),
));
}
validate_portion(portion)?;
let cfg = CONFIG.load(deps.storage)?;
let addr = deps.api.addr_validate(&addr)?;
let liquid_stake = STAKE.may_load(deps.storage, &addr)?;
let vesting_stake = STAKE_VESTING.may_load(deps.storage, &addr)?;
// If address doesn't match anyone, leave early
if liquid_stake.is_none() && vesting_stake.is_none() {
return Ok(Response::new());
}
// response
let mut res = Response::new()
.add_attribute("action", "slash")
.add_attribute("addr", &addr)
.add_attribute("sender", info.sender);
// slash the liquid stake, if any
let mut new_liquid_stake = Uint128::zero();
if let Some(liquid_stake) = liquid_stake {
let mut liquid_slashed = liquid_stake * portion;
new_liquid_stake = STAKE.update(deps.storage, &addr, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().sub(liquid_slashed))
})?;
// slash the claims
liquid_slashed += claims().slash_claims_for_addr(deps.storage, addr.clone(), portion)?;
// burn the liquid slashed tokens
if liquid_slashed > Uint128::zero() {
let burn_liquid_msg = BankMsg::Burn {
amount: coins(liquid_slashed.u128(), &cfg.denom),
};
res = res.add_message(burn_liquid_msg);
}
}
// slash the vesting stake, if any
let mut new_vesting_stake = Uint128::zero();
if let Some(vesting_stake) = vesting_stake {
let vesting_slashed = vesting_stake * portion;
new_vesting_stake = STAKE_VESTING.update(deps.storage, &addr, |stake| -> StdResult<_> {
Ok(stake.unwrap_or_default().sub(vesting_slashed))
})?;
// burn the vesting slashed tokens
if vesting_slashed > Uint128::zero() {
let burn_vesting_msg = BankMsg::Burn {
amount: coins(vesting_slashed.u128(), &cfg.denom),
};
res = res.add_message(burn_vesting_msg);
}
}
res.messages.extend(update_membership(
deps.storage,
addr,
new_liquid_stake + new_vesting_stake,
&cfg,
env.block.height,
)?);
Ok(res)
}
/// Validates funds sent with the message, that they are containing only a single denom. Returns
/// amount of funds sent, or error if:
/// * More than a single denom is sent (`ExtraDenoms` error)
/// * Invalid single denom is sent (`MissingDenom` error)
/// Note that no funds (or a coin of the right denom but zero amount) is a valid option here.
pub fn validate_funds(funds: &[Coin], stake_denom: &str) -> Result<Uint128, ContractError> {
match funds {
[] => Ok(Uint128::zero()),
[Coin { denom, amount }] if denom == stake_denom => Ok(*amount),
[_] => Err(ContractError::MissingDenom(stake_denom.to_string())),
_ => Err(ContractError::ExtraDenoms(stake_denom.to_string())),
}
}
fn update_membership(
storage: &mut dyn Storage,
sender: Addr,
new_stake: Uint128,
cfg: &Config,
height: u64,
) -> StdResult<Vec<SubMsg>> {
// update their membership points
let new = calc_points(new_stake, cfg);
let old = members().may_load(storage, &sender)?.map(|mi| mi.points);
// short-circuit if no change
if new == old {
return Ok(vec![]);
}
// otherwise, record change of points
match new.as_ref() {
Some(&p) => members().save(storage, &sender, &MemberInfo::new(p), height),
None => members().remove(storage, &sender, height),
}?;
// update total
TOTAL.update(storage, |total| -> StdResult<_> {
Ok(total + new.unwrap_or_default() - old.unwrap_or_default())
})?;
// alert the hooks
let diff = MemberDiff::new(sender, old, new);
HOOKS.prepare_hooks(storage, |h| {
MemberChangedHookMsg::one(diff.clone())
.into_cosmos_msg(h)
.map(SubMsg::new)
})
}
fn calc_points(stake: Uint128, cfg: &Config) -> Option<u64> {
if stake < cfg.min_bond {
None
} else {
let p = stake.u128() / cfg.tokens_per_point.u128();
Some(p as u64)
}
}
pub fn execute_claim<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
info: MessageInfo,
) -> Result<Response, ContractError> {
let release = claims().claim_addr(deps.storage, &info.sender, &env.block, None)?;
if release.is_zero() {
return Err(ContractError::NothingToClaim {});
}
let config = CONFIG.load(deps.storage)?;
let amount = coins(release.into(), config.denom);
let res = Response::new()
.add_attribute("action", "claim")
.add_attribute("tokens", coins_to_string(&amount))
.add_attribute("sender", &info.sender)
.add_message(BankMsg::Send {
to_address: info.sender.into(),
amount,
});
Ok(res)
}
// TODO: put in cosmwasm-std
fn coins_to_string(coins: &[Coin]) -> String {
let strings: Vec<_> = coins
.iter()
.map(|c| format!("{}{}", c.amount, c.denom))
.collect();
strings.join(",")
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn sudo(
deps: DepsMut<TgradeQuery>,
env: Env,
msg: TgradeSudoMsg,
) -> Result<Response, ContractError> {
match msg {
TgradeSudoMsg::PrivilegeChange(PrivilegeChangeMsg::Promoted {}) => privilege_promote(deps),
TgradeSudoMsg::EndBlock {} => end_block(deps, env),
_ => Err(ContractError::UnknownSudoMsg {}),
}
}
fn privilege_promote<Q: CustomQuery>(deps: DepsMut<Q>) -> Result<Response, ContractError> {
let config = CONFIG.load(deps.storage)?;
let mut res = Response::new();
if config.auto_return_limit > 0 {
let msgs = request_privileges(&[Privilege::EndBlocker]);
res = res.add_submessages(msgs);
}
let msgs = request_privileges(&[Privilege::Delegator]);
res = res.add_submessages(msgs);
Ok(res)
}
fn end_block<Q: CustomQuery>(deps: DepsMut<Q>, env: Env) -> Result<Response, ContractError> {
let mut resp = Response::new();
let config = CONFIG.load(deps.storage)?;
if config.auto_return_limit > 0 {
let sub_msgs = release_expired_claims(deps, env, config)?;
resp = resp.add_submessages(sub_msgs);
}
Ok(resp)
}
fn release_expired_claims<Q: CustomQuery>(
deps: DepsMut<Q>,
env: Env,
config: Config,
) -> Result<Vec<SubMsg>, ContractError> {
let releases = claims().claim_expired(deps.storage, &env.block, config.auto_return_limit)?;
releases
.into_iter()
.map(|(addr, amount)| {
let amount = coins(amount.into(), config.denom.clone());
Ok(SubMsg::new(BankMsg::Send {
to_address: addr.into(),
amount,
}))
})
.collect()
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<TgradeQuery>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
use QueryMsg::*;
match msg {
Configuration {} => to_binary(&CONFIG.load(deps.storage)?),
Member {
addr,
at_height: height,
} => to_binary(&query_member(deps, addr, height)?),
ListMembers { start_after, limit } => to_binary(&list_members(deps, start_after, limit)?),
ListMembersByPoints { start_after, limit } => {
to_binary(&list_members_by_points(deps, start_after, limit)?)
}
TotalPoints {} => to_binary(&query_total_points(deps)?),
Claims {
address,
limit,
start_after,
} => to_binary(&ClaimsResponse {
claims: claims().query_claims(
deps,
deps.api.addr_validate(&address)?,
limit,
start_after,
)?,
}),
Staked { address } => to_binary(&query_staked(deps, address)?),
Admin {} => to_binary(&ADMIN.query_admin(deps)?),
Hooks {} => {
let hooks = HOOKS.list_hooks(deps.storage)?;
to_binary(&HooksResponse { hooks })
}
Preauths {} => {
let preauths_hooks = PREAUTH_HOOKS.get_auth(deps.storage)?;
to_binary(&PreauthResponse { preauths_hooks })
}
UnbondingPeriod {} => {
let Config {
unbonding_period, ..
} = CONFIG.load(deps.storage)?;
to_binary(&UnbondingPeriodResponse { unbonding_period })
}
IsSlasher { addr } => {
let addr = deps.api.addr_validate(&addr)?;
to_binary(&SLASHERS.is_slasher(deps.storage, &addr)?)
}
ListSlashers {} => to_binary(&SLASHERS.list_slashers(deps.storage)?),
}
}
fn query_total_points<Q: CustomQuery>(deps: Deps<Q>) -> StdResult<TotalPointsResponse> {
let points = TOTAL.load(deps.storage)?;
Ok(TotalPointsResponse { points })
}
pub fn query_staked<Q: CustomQuery>(deps: Deps<Q>, addr: String) -> StdResult<StakedResponse> {
let addr = deps.api.addr_validate(&addr)?;
let stake = STAKE.may_load(deps.storage, &addr)?.unwrap_or_default();
let vesting = STAKE_VESTING
.may_load(deps.storage, &addr)?
.unwrap_or_default();
let config = CONFIG.load(deps.storage)?;
Ok(StakedResponse {
liquid: coin(stake.u128(), config.denom.clone()),
vesting: coin(vesting.u128(), config.denom),
})
}
fn query_member<Q: CustomQuery>(
deps: Deps<Q>,
addr: String,
height: Option<u64>,
) -> StdResult<MemberResponse> {
let addr = deps.api.addr_validate(&addr)?;
let mi = match height {
Some(h) => members().may_load_at_height(deps.storage, &addr, h),
None => members().may_load(deps.storage, &addr),
}?;
Ok(mi.into())
}
// settings for pagination
const MAX_LIMIT: u32 = 100;
const DEFAULT_LIMIT: u32 = 30;
fn list_members<Q: CustomQuery>(
deps: Deps<Q>,
start_after: Option<String>,
limit: Option<u32>,
) -> StdResult<MemberListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let addr = maybe_addr(deps.api, start_after)?;
let start = addr.as_ref().map(Bound::exclusive);
let members: StdResult<Vec<_>> = members()
.range(deps.storage, start, None, Order::Ascending)
.take(limit)
.map(|item| {
let (
addr,
MemberInfo {
points,
start_height,
},
) = item?;
Ok(Member {
addr: addr.into(),
points,
start_height,
})
})
.collect();
Ok(MemberListResponse { members: members? })
}
fn list_members_by_points<Q: CustomQuery>(
deps: Deps<Q>,
start_after: Option<Member>,
limit: Option<u32>,
) -> StdResult<MemberListResponse> {
let limit = limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT) as usize;
let start = start_after
.map(|m| {
deps.api
.addr_validate(&m.addr)
.map(|addr| Bound::exclusive((m.points, addr)))
})
.transpose()?;
let members: StdResult<Vec<_>> = members()
.idx
.points
.range(deps.storage, None, start, Order::Descending)
.take(limit)
.map(|item| {
let (
addr,
MemberInfo {
points,
start_height,
},
) = item?;
Ok(Member {
addr: addr.into(),
points,
start_height,
})
})
.collect();
Ok(MemberListResponse { members: members? })
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(
deps: DepsMut<TgradeQuery>,
_env: Env,
_msg: Empty,
) -> Result<Response, ContractError> {
ensure_from_older_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(Response::new())
}
#[cfg(test)]
mod tests {
use crate::claim::Claim;
use cosmwasm_std::testing::{mock_env, mock_info};
use cosmwasm_std::{
from_slice, CosmosMsg, OverflowError, OverflowOperation, StdError, Storage,
};
use tg4::{member_key, TOTAL_KEY};
use tg_utils::{Expiration, HookError, PreauthError, SlasherError};
use crate::error::ContractError;
use super::*;
use tg_bindings_test::mock_deps_tgrade;
const INIT_ADMIN: &str = "juan";
const USER1: &str = "user1";
const USER2: &str = "user2";
const USER3: &str = "user3";
const DENOM: &str = "stake";
const TOKENS_PER_POINT: Uint128 = Uint128::new(1_000);
const MIN_BOND: Uint128 = Uint128::new(5_000);
const UNBONDING_DURATION: u64 = 100;
fn default_instantiate(deps: DepsMut<TgradeQuery>) {
do_instantiate(deps, TOKENS_PER_POINT, MIN_BOND, UNBONDING_DURATION, 0)
}
fn do_instantiate(
deps: DepsMut<TgradeQuery>,
tokens_per_point: Uint128,
min_bond: Uint128,
unbonding_period: u64,
auto_return_limit: u64,
) {
let msg = InstantiateMsg {
denom: "stake".to_owned(),
tokens_per_point,
min_bond,
unbonding_period,
admin: Some(INIT_ADMIN.into()),
preauths_hooks: 1,
preauths_slashing: 1,
auto_return_limit,
};
let info = mock_info("creator", &[]);
instantiate(deps, mock_env(), info, msg).unwrap();
}
// Helper for staking only liquid assets
fn bond_liquid(
deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
) {
bond(deps, (user1, 0), (user2, 0), (user3, 0), height_delta);
}
// Helper for staking only illiquid assets
fn bond_vesting(
deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
) {
bond(deps, (0, user1), (0, user2), (0, user3), height_delta);
}
// Full stake is composed of `(liquid, illiquid (vesting))` amounts
fn bond(
mut deps: DepsMut<TgradeQuery>,
user1_stake: (u128, u128),
user2_stake: (u128, u128),
user3_stake: (u128, u128),
height_delta: u64,
) {
let mut env = mock_env();
env.block.height += height_delta;
for (addr, stake) in &[
(USER1, user1_stake),
(USER2, user2_stake),
(USER3, user3_stake),
] {
if stake.0 != 0 || stake.1 != 0 {
let vesting_tokens = if stake.1 != 0 {
Some(coin(stake.1, DENOM))
} else {
None
};
let msg = ExecuteMsg::Bond { vesting_tokens };
let info = mock_info(addr, &coins(stake.0, DENOM));
execute(deps.branch(), env.clone(), info, msg).unwrap();
}
}
}
fn unbond(
mut deps: DepsMut<TgradeQuery>,
user1: u128,
user2: u128,
user3: u128,
height_delta: u64,
time_delta: u64,
) {
let mut env = mock_env();
env.block.height += height_delta;
env.block.time = env.block.time.plus_seconds(time_delta);
for (addr, stake) in &[(USER1, user1), (USER2, user2), (USER3, user3)] {
if *stake != 0 {
let msg = ExecuteMsg::Unbond {
tokens: coin(*stake, DENOM),
};
let info = mock_info(addr, &[]);
execute(deps.branch(), env.clone(), info, msg).unwrap();
}
}
}
#[test]
fn proper_instantiation() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
// it worked, let's query the state
let res = ADMIN.query_admin(deps.as_ref()).unwrap();
assert_eq!(Some(INIT_ADMIN.into()), res.admin);
let res = query_total_points(deps.as_ref()).unwrap();
assert_eq!(0, res.points);
let raw = query(deps.as_ref(), mock_env(), QueryMsg::Configuration {}).unwrap();
let res: Config = from_slice(&raw).unwrap();
assert_eq!(
res,
Config {
denom: "stake".to_owned(),
tokens_per_point: TOKENS_PER_POINT,
min_bond: MIN_BOND,
unbonding_period: Duration::new(UNBONDING_DURATION),
auto_return_limit: 0,
}
);
// query the admin's staked amount (just to confirm the query works)
let res = query_staked(deps.as_ref(), INIT_ADMIN.into()).unwrap();
assert_eq!(coin(0, "stake"), res.liquid);
assert_eq!(coin(0, "stake"), res.vesting);
}
#[test]
fn unbonding_period_query_works() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let raw = query(deps.as_ref(), mock_env(), QueryMsg::UnbondingPeriod {}).unwrap();
let res: UnbondingPeriodResponse = from_slice(&raw).unwrap();
assert_eq!(res.unbonding_period, Duration::new(UNBONDING_DURATION));
}
fn get_member(deps: Deps<TgradeQuery>, addr: String, at_height: Option<u64>) -> Option<u64> {
let raw = query(deps, mock_env(), QueryMsg::Member { addr, at_height }).unwrap();
let res: MemberResponse = from_slice(&raw).unwrap();
res.points
}
// this tests the member queries
#[track_caller]
fn assert_users(
deps: Deps<TgradeQuery>,
user1_points: Option<u64>,
user2_points: Option<u64>,
user3_points: Option<u64>,
height: Option<u64>,
) {
let member1 = get_member(deps, USER1.into(), height);
assert_eq!(member1, user1_points);
let member2 = get_member(deps, USER2.into(), height);
assert_eq!(member2, user2_points);
let member3 = get_member(deps, USER3.into(), height);
assert_eq!(member3, user3_points);
// this is only valid if we are not doing a historical query
if height.is_none() {
// compute expected metrics
let points = vec![user1_points, user2_points, user3_points];
let sum: u64 = points.iter().map(|x| x.unwrap_or_default()).sum();
let count = points.iter().filter(|x| x.is_some()).count();
// TODO: more detailed compare?
let msg = QueryMsg::ListMembers {
start_after: None,
limit: None,
};
let raw = query(deps, mock_env(), msg).unwrap();
let members: MemberListResponse = from_slice(&raw).unwrap();
assert_eq!(count, members.members.len());
let raw = query(deps, mock_env(), QueryMsg::TotalPoints {}).unwrap();
let total: TotalPointsResponse = from_slice(&raw).unwrap();
assert_eq!(sum, total.points); // 17 - 11 + 15 = 21
}
}
// this tests the member queries of liquid amounts
#[track_caller]
fn assert_stake_liquid(deps: Deps<TgradeQuery>, user1: u128, user2: u128, user3: u128) {
let stake1 = query_staked(deps, USER1.into()).unwrap();
assert_eq!(stake1.liquid, coin(user1, DENOM));
let stake2 = query_staked(deps, USER2.into()).unwrap();
assert_eq!(stake2.liquid, coin(user2, DENOM));
let stake3 = query_staked(deps, USER3.into()).unwrap();
assert_eq!(stake3.liquid, coin(user3, DENOM));
}
// this tests the member queries of illiquid amounts
#[track_caller]
fn assert_stake_vesting(deps: Deps<TgradeQuery>, user1: u128, user2: u128, user3: u128) {
let stake1 = query_staked(deps, USER1.into()).unwrap();
assert_eq!(stake1.vesting, coin(user1, DENOM));
let stake2 = query_staked(deps, USER2.into()).unwrap();
assert_eq!(stake2.vesting, coin(user2, DENOM));
let stake3 = query_staked(deps, USER3.into()).unwrap();
assert_eq!(stake3.vesting, coin(user3, DENOM));
}
#[test]
fn bond_stake_liquid_adds_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// Assert original points
assert_users(deps.as_ref(), None, None, None, None);
// ensure it rounds down, and respects cut-off
bond_liquid(deps.as_mut(), 12_000, 7_500, 4_000, 1);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 12_000, 7_500, 4_000);
assert_users(deps.as_ref(), Some(12), Some(7), None, None);
// add some more, ensure the sum is properly respected (7.5 + 7.6 = 15 not 14)
bond_liquid(deps.as_mut(), 0, 7_600, 1_200, 2);
// Assert updated points
assert_stake_liquid(deps.as_ref(), 12_000, 15_100, 5_200);
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake
assert_users(deps.as_ref(), Some(12), Some(7), None, Some(height + 2)); // after first stake
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), Some(height + 3));
// after second stake
}
#[test]
fn bond_stake_vesting_adds_membership() {
let mut deps = mock_deps_tgrade();
default_instantiate(deps.as_mut());
let height = mock_env().block.height;
// Assert original points
assert_users(deps.as_ref(), None, None, None, None);
// ensure it rounds down, and respects cut-off
bond_vesting(deps.as_mut(), 12_000, 7_500, 4_000, 1);
// Assert updated points
assert_stake_vesting(deps.as_ref(), 12_000, 7_500, 4_000);
assert_users(deps.as_ref(), Some(12), Some(7), None, None);
// add some more, ensure the sum is properly respected (7.5 + 7.6 = 15 not 14)
bond_vesting(deps.as_mut(), 0, 7_600, 1_200, 2);
// Assert updated points
assert_stake_vesting(deps.as_ref(), 12_000, 15_100, 5_200);
assert_users(deps.as_ref(), Some(12), Some(15), Some(5), None);
// check historical queries all work
assert_users(deps.as_ref(), None, None, None, Some(height + 1)); // before first stake