From 8cf2ea4da0abaf5e5cae20041be15f28b7b8eaa9 Mon Sep 17 00:00:00 2001 From: Trinity Date: Tue, 2 Jul 2024 15:00:57 +0700 Subject: [PATCH 01/15] Custom contract for zero max cap --- Cargo.lock | 1 + contracts/consumer/converter/Cargo.toml | 1 + contracts/consumer/converter/src/contract.rs | 60 ++++++- contracts/consumer/converter/src/ibc.rs | 43 ++++- contracts/consumer/converter/src/multitest.rs | 10 +- .../src/multitest/virtual_staking_mock.rs | 12 ++ contracts/consumer/virtual-staking/Cargo.toml | 1 + .../consumer/virtual-staking/src/contract.rs | 160 +++++++++++++----- .../provider/external-staking/src/contract.rs | 66 +++++++- .../provider/external-staking/src/ibc.rs | 5 + packages/apis/src/converter_api.rs | 10 ++ packages/apis/src/ibc/packet.rs | 10 ++ packages/apis/src/virtual_staking_api.rs | 13 ++ packages/bindings/src/query.rs | 23 ++- packages/virtual-staking-mock/src/lib.rs | 10 +- 15 files changed, 363 insertions(+), 62 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0df67f14..ae9071cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -610,6 +610,7 @@ dependencies = [ "mesh-bindings", "mesh-burn", "mesh-simple-price-feed", + "mesh-sync", "schemars", "serde", "sylvia", diff --git a/contracts/consumer/converter/Cargo.toml b/contracts/consumer/converter/Cargo.toml index a152fbeb..0a03ffe6 100644 --- a/contracts/consumer/converter/Cargo.toml +++ b/contracts/consumer/converter/Cargo.toml @@ -23,6 +23,7 @@ fake-custom = [ "mesh-simple-price-feed/fake-custom" ] [dependencies] mesh-apis = { workspace = true } mesh-bindings = { workspace = true } +mesh-sync = { workspace = true } sylvia = { workspace = true } cosmwasm-schema = { workspace = true } diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index caedb92d..ba62e558 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -1,7 +1,7 @@ use cosmwasm_std::{ ensure_eq, to_json_binary, Addr, BankMsg, Coin, CosmosMsg, Decimal, Deps, DepsMut, Event, - Fraction, MessageInfo, Reply, Response, StdError, SubMsg, SubMsgResponse, Uint128, Validator, - WasmMsg, + Fraction, IbcMsg, MessageInfo, Reply, Response, StdError, SubMsg, SubMsgResponse, Uint128, + Validator, WasmMsg, }; use cw2::set_contract_version; use cw_storage_plus::Item; @@ -15,7 +15,9 @@ use mesh_apis::price_feed_api; use mesh_apis::virtual_staking_api; use crate::error::ContractError; -use crate::ibc::{make_ibc_packet, valset_update_msg, IBC_CHANNEL}; +use crate::ibc::{ + make_ibc_packet, packet_timeout_internal_unstake, valset_update_msg, IBC_CHANNEL, +}; use crate::msg::ConfigResponse; use crate::state::Config; @@ -138,13 +140,14 @@ impl ConverterContract<'_> { fn test_stake( &self, ctx: ExecCtx, + delegator: String, validator: String, stake: Coin, ) -> Result { #[cfg(any(test, feature = "mt"))] { // This can only ever be called in tests - self.stake(ctx.deps, validator, stake) + self.stake(ctx.deps, delegator, validator, stake) } #[cfg(not(any(test, feature = "mt")))] { @@ -159,13 +162,14 @@ impl ConverterContract<'_> { fn test_unstake( &self, ctx: ExecCtx, + delegator: String, validator: String, unstake: Coin, ) -> Result { #[cfg(any(test, feature = "mt"))] { // This can only ever be called in tests - self.unstake(ctx.deps, validator, unstake) + self.unstake(ctx.deps, delegator, validator, unstake) } #[cfg(not(any(test, feature = "mt")))] { @@ -214,6 +218,7 @@ impl ConverterContract<'_> { pub(crate) fn stake( &self, deps: DepsMut, + delegator: String, validator: String, stake: Coin, ) -> Result { @@ -223,7 +228,11 @@ impl ConverterContract<'_> { .add_attribute("validator", &validator) .add_attribute("amount", amount.amount.to_string()); - let msg = virtual_staking_api::sv::ExecMsg::Bond { validator, amount }; + let msg = virtual_staking_api::sv::ExecMsg::Bond { + delegator, + validator, + amount, + }; let msg = WasmMsg::Execute { contract_addr: self.virtual_stake.load(deps.storage)?.into(), msg: to_json_binary(&msg)?, @@ -238,6 +247,7 @@ impl ConverterContract<'_> { pub(crate) fn unstake( &self, deps: DepsMut, + delegator: String, validator: String, unstake: Coin, ) -> Result { @@ -247,7 +257,11 @@ impl ConverterContract<'_> { .add_attribute("validator", &validator) .add_attribute("amount", amount.amount.to_string()); - let msg = virtual_staking_api::sv::ExecMsg::Unbond { validator, amount }; + let msg = virtual_staking_api::sv::ExecMsg::Unbond { + delegator, + validator, + amount, + }; let msg = WasmMsg::Execute { contract_addr: self.virtual_stake.load(deps.storage)?.into(), msg: to_json_binary(&msg)?, @@ -603,4 +617,36 @@ impl ConverterApi for ConverterContract<'_> { resp = resp.add_event(event); Ok(resp) } + + fn internal_unstake( + &self, + ctx: ExecCtx, + delegator: String, + validator: String, + amount: Coin, + ) -> Result { + let virtual_stake = self.virtual_stake.load(ctx.deps.storage)?; + ensure_eq!(ctx.info.sender, virtual_stake, ContractError::Unauthorized); + + #[allow(unused_mut)] + let mut resp = Response::new() + .add_attribute("action", "internal_unstake") + .add_attribute("amount", amount.amount.to_string()) + .add_attribute("owner", delegator.clone()); + + let channel = IBC_CHANNEL.load(ctx.deps.storage)?; + let packet = ConsumerPacket::InternalUnstake { + delegator: delegator, + validator, + amount, + }; + let msg = IbcMsg::SendPacket { + channel_id: channel.endpoint.channel_id, + data: to_json_binary(&packet)?, + timeout: packet_timeout_internal_unstake(&ctx.env), + }; + // send packet if we are ibc enabled + resp = resp.add_message(msg); + Ok(resp) + } } diff --git a/contracts/consumer/converter/src/ibc.rs b/contracts/consumer/converter/src/ibc.rs index c54a19dd..f719fee8 100644 --- a/contracts/consumer/converter/src/ibc.rs +++ b/contracts/consumer/converter/src/ibc.rs @@ -5,7 +5,7 @@ use cosmwasm_std::{ from_json, to_json_binary, DepsMut, Env, Event, Ibc3ChannelOpenResponse, IbcBasicResponse, IbcChannel, IbcChannelCloseMsg, IbcChannelConnectMsg, IbcChannelOpenMsg, IbcChannelOpenResponse, IbcMsg, IbcPacketAckMsg, IbcPacketReceiveMsg, IbcPacketTimeoutMsg, - IbcReceiveResponse, IbcTimeout, Validator, + IbcReceiveResponse, IbcTimeout, Validator, WasmMsg, }; use cw_storage_plus::Item; @@ -14,6 +14,7 @@ use mesh_apis::ibc::{ ack_success, validate_channel_order, AckWrapper, AddValidator, ConsumerPacket, ProtocolVersion, ProviderPacket, StakeAck, TransferRewardsAck, UnstakeAck, PROTOCOL_NAME, }; +use mesh_apis::virtual_staking_api; use sylvia::types::ExecCtx; use crate::{ @@ -34,6 +35,8 @@ const DEFAULT_VALIDATOR_TIMEOUT: u64 = 24 * 60 * 60; // But reward messages should go faster or timeout const DEFAULT_REWARD_TIMEOUT: u64 = 60 * 60; +const DEFAULT_INTERNAL_UNSTAKE_TIMEOUT: u64 = 60 * 60; + pub fn packet_timeout_validator(env: &Env) -> IbcTimeout { // No idea about their block time, but 24 hours ahead of our view of the clock // should be decently in the future. @@ -48,6 +51,13 @@ pub fn packet_timeout_rewards(env: &Env) -> IbcTimeout { IbcTimeout::with_timestamp(timeout) } +pub fn packet_timeout_internal_unstake(env: &Env) -> IbcTimeout { + // No idea about their block time, but 24 hours ahead of our view of the clock + // should be decently in the future. + let timeout = env.block.time.plus_seconds(DEFAULT_INTERNAL_UNSTAKE_TIMEOUT); + IbcTimeout::with_timestamp(timeout) +} + #[cfg_attr(not(feature = "library"), entry_point)] /// enforces ordering and versioning constraints pub fn ibc_channel_open( @@ -195,11 +205,12 @@ pub fn ibc_packet_receive( let contract = ConverterContract::new(); let res = match packet { ProviderPacket::Stake { + delegator, validator, stake, tx_id: _, } => { - let response = contract.stake(deps, validator, stake)?; + let response = contract.stake(deps, delegator, validator, stake)?; let ack = ack_success(&StakeAck {})?; IbcReceiveResponse::new() .set_ack(ack) @@ -208,11 +219,12 @@ pub fn ibc_packet_receive( .add_attributes(response.attributes) } ProviderPacket::Unstake { + delegator, validator, unstake, tx_id: _, } => { - let response = contract.unstake(deps, validator, unstake)?; + let response = contract.unstake(deps, delegator, validator, unstake)?; let ack = ack_success(&UnstakeAck {})?; IbcReceiveResponse::new() .set_ack(ack) @@ -245,14 +257,35 @@ pub fn ibc_packet_receive( /// If it succeeded, take no action. If it errored, we can't do anything else and let it go. /// We just log the error cases so they can be detected. pub fn ibc_packet_ack( - _deps: DepsMut, + deps: DepsMut, _env: Env, msg: IbcPacketAckMsg, ) -> Result { let ack: AckWrapper = from_json(&msg.acknowledgement.data)?; + let contract = ConverterContract::new(); let mut res = IbcBasicResponse::new(); match ack { - AckWrapper::Result(_) => {} + AckWrapper::Result(_) => { + let packet: ConsumerPacket = from_json(&msg.original_packet.data)?; + if let ConsumerPacket::InternalUnstake { + delegator, + validator, + amount, + } = packet { + // execute virtual contract's internal unbond + let msg = virtual_staking_api::sv::ExecMsg::InternalUnbond { + delegator, + validator, + amount, + }; + let msg = WasmMsg::Execute { + contract_addr: contract.virtual_stake.load(deps.storage)?.into(), + msg: to_json_binary(&msg)?, + funds: vec![], + }; + res = res.add_message(msg); + } + } AckWrapper::Error(e) => { // The wasmd framework will label this with the contract_addr, which helps us find the port and issue. // Provide info to find the actual packet. diff --git a/contracts/consumer/converter/src/multitest.rs b/contracts/consumer/converter/src/multitest.rs index 22169d99..2ee2b19e 100644 --- a/contracts/consumer/converter/src/multitest.rs +++ b/contracts/consumer/converter/src/multitest.rs @@ -172,17 +172,17 @@ fn ibc_stake_and_unstake() { // let's stake some converter - .test_stake(val1.to_string(), coin(1000, JUNO)) + .test_stake(owner.to_string(), val1.to_string(), coin(1000, JUNO)) .call(owner) .unwrap(); converter - .test_stake(val2.to_string(), coin(4000, JUNO)) + .test_stake(owner.to_string(), val2.to_string(), coin(4000, JUNO)) .call(owner) .unwrap(); // and unstake some converter - .test_unstake(val2.to_string(), coin(2000, JUNO)) + .test_unstake(owner.to_string(), val2.to_string(), coin(2000, JUNO)) .call(owner) .unwrap(); @@ -258,11 +258,11 @@ fn ibc_stake_and_burn() { // let's stake some converter - .test_stake(val1.to_string(), coin(1000, JUNO)) + .test_stake(owner.to_string(),val1.to_string(), coin(1000, JUNO)) .call(owner) .unwrap(); converter - .test_stake(val2.to_string(), coin(4000, JUNO)) + .test_stake(owner.to_string(), val2.to_string(), coin(4000, JUNO)) .call(owner) .unwrap(); diff --git a/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs b/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs index 3faaedf8..d4422445 100644 --- a/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs +++ b/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs @@ -133,6 +133,7 @@ impl VirtualStakingApi for VirtualStakingMock<'_> { fn bond( &self, ctx: ExecCtx, + _delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -160,6 +161,7 @@ impl VirtualStakingApi for VirtualStakingMock<'_> { fn unbond( &self, ctx: ExecCtx, + _delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -241,6 +243,16 @@ impl VirtualStakingApi for VirtualStakingMock<'_> { Ok(Response::new()) } + fn internal_unbond( + &self, + _ctx:ExecCtx, + _delegator:String, + _validator:String, + _amount:Coin + ) -> Result ,Self::Error> { + unimplemented!() + } + /// SudoMsg::HandleEpoch{} should be called once per epoch by the sdk (in EndBlock). /// It allows the virtual staking contract to bond or unbond any pending requests, as well /// as to perform a rebalance if needed (over the max cap). diff --git a/contracts/consumer/virtual-staking/Cargo.toml b/contracts/consumer/virtual-staking/Cargo.toml index 2952a33b..000abb3c 100644 --- a/contracts/consumer/virtual-staking/Cargo.toml +++ b/contracts/consumer/virtual-staking/Cargo.toml @@ -35,6 +35,7 @@ serde = { workspace = true } thiserror = { workspace = true } [dev-dependencies] +sylvia = { workspace = true, features = ["mt"] } mesh-simple-price-feed = { workspace = true, features = ["mt", "fake-custom"] } mesh-converter = { workspace = true, features = ["mt", "fake-custom"] } cw-multi-test = { workspace = true } diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index 52af7d8b..01f23edc 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -24,6 +24,9 @@ use crate::state::Config; pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME"); pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); +// TODO: lack test for the appropriate max retrieve. +pub const MAX_RETRIEVE: u16 = 50; + pub struct VirtualStakingContract<'a> { pub config: Item<'a, Config>, /// Amount of tokens that have been requested to bond to a validator @@ -360,6 +363,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn bond( &self, ctx: ExecCtx, + _delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -390,6 +394,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn unbond( &self, ctx: ExecCtx, + _delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -475,6 +480,44 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { Ok(Response::new()) } + /// Immediately unbond the given amount due to zero max cap + fn internal_unbond( + &self, + ctx: ExecCtx, + _delegator: String, + validator: String, + amount: Coin, + ) -> Result, Self::Error> { + nonpayable(&ctx.info)?; + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(ctx.info.sender, cfg.converter, ContractError::Unauthorized); // only the converter can call this + ensure_eq!( + amount.denom, + cfg.denom, + ContractError::WrongDenom(cfg.denom) + ); + + // Immediately unbond + let bonded = self.bond_requests.load(ctx.deps.storage, &validator)?; + let bonded = bonded + .checked_sub(amount.amount) + .map_err(|_| ContractError::InsufficientBond(validator.clone(), amount.amount))?; + self.bond_requests + .save(ctx.deps.storage, &validator, &bonded)?; + + let requests: Vec<(String, Uint128)> = self + .bond_requests + .range( + ctx.deps.as_ref().storage, + None, + None, + cosmwasm_std::Order::Ascending, + ) + .collect::>()?; + self.bonded.save(ctx.deps.storage, &requests)?; + return Ok(Response::new()) + } + // FIXME: need to handle custom message types and queries /** * This is called once per epoch to withdraw all rewards and rebalance the bonded tokens. @@ -506,15 +549,35 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { let bond = TokenQuerier::new(&deps.querier).bond_status(env.contract.address.to_string())?; let max_cap = bond.cap.amount; + + let config = self.config.load(deps.storage)?; // If 0 max cap, then we assume all tokens were force unbonded already, and just return the withdraw rewards // call and set bonded to empty // TODO: verify this behavior with SDK module (otherwise we send unbond message) if max_cap.is_zero() { - self.bonded.save(deps.storage, &vec![])?; - return Ok(resp); + let all_delegations = + TokenQuerier::new(&deps.querier).all_delegations( + env.contract.address.to_string(), MAX_RETRIEVE + )?; + let mut msgs = vec![]; + for delegation in all_delegations.delegations { + let validator = delegation.validator.clone(); + // Send unstake request to converter contract + let msg = converter_api::sv::ExecMsg::InternalUnstake { + delegator: delegation.delegator, + validator: validator, + amount: Coin { denom: config.denom.clone(), amount: delegation.amount } + }; + let msg = WasmMsg::Execute { + contract_addr: config.converter.to_string(), + msg: to_json_binary(&msg)?, + funds: vec![], + }; + msgs.push(msg); + } + return Ok(resp.add_messages(msgs)); } - let config = self.config.load(deps.storage)?; // Make current bonded mutable let mut current = bonded; // Process slashes due to tombstoning (unbonded) or jailing, over bond_requests and current @@ -645,9 +708,7 @@ mod tests { }; use cosmwasm_std::{ - coins, from_json, - testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage}, - Decimal, + coins, from_json, testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage}, AllDelegationsResponse, Decimal }; use mesh_bindings::{BondStatusResponse, SlashRatioResponse}; @@ -665,7 +726,7 @@ mod tests { contract.quick_inst(deps.as_mut()); knobs.bond_status.update_cap(0u128); - contract.quick_bond(deps.as_mut(), "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_no_bonding() @@ -681,7 +742,7 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(10u128); - contract.quick_bond(deps.as_mut(), "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom))]) @@ -697,8 +758,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(10u128); - contract.quick_bond(deps.as_mut(), "val1", 6); - contract.quick_bond(deps.as_mut(), "val2", 4); + contract.quick_bond(deps.as_mut(), "owner", "val1", 6); + contract.quick_bond(deps.as_mut(), "owner", "val2", 4); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (6u128, &denom)), ("val2", (4u128, &denom))]) @@ -716,8 +777,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(5u128); - contract.quick_bond(deps.as_mut(), "val1", 10); - contract.quick_bond(deps.as_mut(), "val2", 40); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val2", 40); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (1u128, &denom)), ("val2", (4u128, &denom))]) @@ -733,13 +794,13 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(10u128); - contract.quick_bond(deps.as_mut(), "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom))]) .assert_rewards(&[]); - contract.quick_unbond(deps.as_mut(), "val1", 5); + contract.quick_unbond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_unbond(&[("val1", (5u128, &denom))]) @@ -755,7 +816,7 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(10u128); - contract.quick_bond(deps.as_mut(), "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom))]) @@ -777,8 +838,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 5); - contract.quick_bond(deps.as_mut(), "val2", 20); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val2", 20); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom)), ("val2", (20u128, &denom))]) @@ -802,8 +863,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 5); - contract.quick_bond(deps.as_mut(), "val2", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val2", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom)), ("val2", (10u128, &denom))]) @@ -827,8 +888,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 5); - contract.quick_bond(deps.as_mut(), "val2", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val2", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom)), ("val2", (10u128, &denom))]) @@ -850,8 +911,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 10); - contract.quick_bond(deps.as_mut(), "val2", 20); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val2", 20); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (10u128, &denom)), ("val2", (20u128, &denom))]) @@ -914,14 +975,14 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (10u128, &denom))]) .assert_rewards(&[]); // Val1 is bonding some more - contract.quick_bond(deps.as_mut(), "val1", 20); + contract.quick_bond(deps.as_mut(), "owner", "val1", 20); // And it's being jailed at the same time contract.jail(deps.as_mut(), "val1", Decimal::percent(10), Uint128::one()); @@ -946,14 +1007,14 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (10u128, &denom))]) .assert_rewards(&[]); // Val1 is unbonding - contract.quick_unbond(deps.as_mut(), "val1", 10); + contract.quick_unbond(deps.as_mut(), "owner", "val1", 10); // And it's being jailed at the same time contract.jail(deps.as_mut(), "val1", Decimal::percent(10), Uint128::one()); @@ -993,7 +1054,7 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(10u128); - contract.quick_bond(deps.as_mut(), "val1", 5); + contract.quick_bond(deps.as_mut(), "owner", "val1", 5); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (5u128, &denom))]) @@ -1021,8 +1082,8 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 20); - contract.quick_bond(deps.as_mut(), "val2", 20); + contract.quick_bond(deps.as_mut(), "owner", "val1", 20); + contract.quick_bond(deps.as_mut(), "owner", "val2", 20); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (20u128, &denom)), ("val2", (20u128, &denom))]) @@ -1061,14 +1122,14 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (10u128, &denom))]) .assert_rewards(&[]); // Val1 is bonding some more - contract.quick_bond(deps.as_mut(), "val1", 20); + contract.quick_bond(deps.as_mut(), "owner", "val1", 20); // And it's being tombstoned at the same time contract.tombstone(deps.as_mut(), "val1", Decimal::percent(25), Uint128::new(2)); @@ -1101,14 +1162,14 @@ mod tests { let denom = contract.config.load(&deps.storage).unwrap().denom; knobs.bond_status.update_cap(100u128); - contract.quick_bond(deps.as_mut(), "val1", 10); + contract.quick_bond(deps.as_mut(), "owner", "val1", 10); contract .hit_epoch(deps.as_mut()) .assert_bond(&[("val1", (10u128, &denom))]) .assert_rewards(&[]); // Val1 is unbonding - contract.quick_unbond(deps.as_mut(), "val1", 10); + contract.quick_unbond(deps.as_mut(), "owner", "val1", 10); // And it's being tombstoned at the same time contract.tombstone(deps.as_mut(), "val1", Decimal::percent(25), Uint128::new(2)); @@ -1213,6 +1274,9 @@ mod tests { slash_fraction_downtime: "0.1".to_string(), slash_fraction_double_sign: "0.25".to_string(), }); + let all_delegations = MockAllDelegations::new(AllDelegationsResponse { + delegations: vec![] + }); let handler = { let bs_copy = bond_status.clone(); @@ -1229,6 +1293,11 @@ mod tests { to_json_binary(&*slash_ratio.borrow()).unwrap(), )) } + mesh_bindings::VirtualStakeQuery::AllDelegations { .. } => { + cosmwasm_std::SystemResult::Ok(cosmwasm_std::ContractResult::Ok( + to_json_binary(&*all_delegations.borrow()).unwrap(), + )) + } } } }; @@ -1279,6 +1348,19 @@ mod tests { } } + #[derive(Clone)] + struct MockAllDelegations(Rc>); + + impl MockAllDelegations { + fn new(res: AllDelegationsResponse) -> Self { + Self(Rc::new(RefCell::new(res))) + } + + fn borrow(&self) -> Ref<'_, AllDelegationsResponse> { + self.0.borrow() + } + } + fn set_reward_targets(storage: &mut dyn Storage, targets: &[&str]) { REWARD_TARGETS .save( @@ -1292,8 +1374,8 @@ mod tests { fn quick_inst(&self, deps: DepsMut); fn push_rewards(&self, deps: &mut OwnedDeps, amount: u128) -> PushRewardsResult; fn hit_epoch(&self, deps: DepsMut) -> HitEpochResult; - fn quick_bond(&self, deps: DepsMut, validator: &str, amount: u128); - fn quick_unbond(&self, deps: DepsMut, validator: &str, amount: u128); + fn quick_bond(&self, deps: DepsMut, delegator: &str, validator: &str, amount: u128); + fn quick_unbond(&self, deps: DepsMut, delegator: &str, validator: &str, amount: u128); fn quick_burn( &self, deps: DepsMut, @@ -1366,7 +1448,7 @@ mod tests { HitEpochResult::new(self.handle_epoch(deps).unwrap()) } - fn quick_bond(&self, deps: DepsMut, validator: &str, amount: u128) { + fn quick_bond(&self, deps: DepsMut, delegator: &str, validator: &str, amount: u128) { let denom = self.config.load(deps.storage).unwrap().denom; self.bond( @@ -1375,13 +1457,14 @@ mod tests { env: mock_env(), info: mock_info("me", &[]), }, + delegator.to_string(), validator.to_string(), coin(amount, denom), ) .unwrap(); } - fn quick_unbond(&self, deps: DepsMut, validator: &str, amount: u128) { + fn quick_unbond(&self, deps: DepsMut, delegator: &str, validator: &str, amount: u128) { let denom = self.config.load(deps.storage).unwrap().denom; self.unbond( @@ -1390,6 +1473,7 @@ mod tests { env: mock_env(), info: mock_info("me", &[]), }, + delegator.to_string(), validator.to_string(), coin(amount, denom), ) diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index 25293bc3..2b996ea4 100644 --- a/contracts/provider/external-staking/src/contract.rs +++ b/contracts/provider/external-staking/src/contract.rs @@ -26,7 +26,7 @@ use crate::msg::{ StakeInfo, StakesResponse, TxResponse, ValidatorPendingRewards, }; use crate::stakes::Stakes; -use crate::state::{Config, Distribution, SlashRatio, Stake}; +use crate::state::{Config, Distribution, PendingUnbond, SlashRatio, Stake}; pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME"); pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -296,10 +296,11 @@ impl ExternalStakingContract<'_> { let mut resp = Response::new() .add_attribute("action", "unstake") .add_attribute("amount", amount.amount.to_string()) - .add_attribute("owner", info.sender); + .add_attribute("owner", info.sender.clone()); let channel = IBC_CHANNEL.load(deps.storage)?; let packet = ProviderPacket::Unstake { + delegator: info.sender.to_string(), validator, unstake: amount, tx_id, @@ -445,6 +446,66 @@ impl ExternalStakingContract<'_> { Ok(()) } + pub(crate) fn internal_unstake( + &self, + deps: DepsMut, + env: Env, + delegator: String, + validator: String, + amount: Coin, + ) -> Result { + let config = self.config.load(deps.storage)?; + let user = deps.api.addr_validate(&delegator)?; + // Load stake + let mut stake = self.stakes.stake.load(deps.storage, (&user, &validator))?; + + // Load distribution + let mut distribution = self + .distribution + .may_load(deps.storage, &validator)? + .unwrap_or_default(); + + // Commit sub amount, saturating if slashed + let amount = min(amount.amount, stake.stake.high()); + stake.stake.commit_sub(amount); + + let immediate_release = matches!( + self.val_set.validator_state(deps.storage, &validator)?, + State::Unbonded {} | State::Tombstoned {} + ); + + // FIXME? Release period being computed after successful IBC tx + // (Note: this is good for now, but can be revisited in v1 design) + let release_at = if immediate_release { + env.block.time + } else { + env.block.time.plus_seconds(config.unbonding_period) + }; + let unbond = PendingUnbond { amount, release_at }; + stake.pending_unbonds.push(unbond); + + // Distribution alignment + stake + .points_alignment + .stake_decreased(amount, distribution.points_per_stake); + distribution.total_stake -= amount; + + // Save stake + self.stakes + .stake + .save(deps.storage, (&user, &validator), &stake)?; + + // Save distribution + self.distribution + .save(deps.storage, &validator, &distribution)?; + let event = Event::new("internal_unstake") + .add_attribute("delegator", delegator) + .add_attribute("validator", validator) + .add_attribute("amount", amount.to_string()); + + Ok(event) + } + /// In non-test code, this is called from `ibc_packet_ack` #[allow(clippy::too_many_arguments)] pub(crate) fn valset_update( @@ -1271,6 +1332,7 @@ pub mod cross_staking { let channel = IBC_CHANNEL.load(ctx.deps.storage)?; let packet = ProviderPacket::Stake { + delegator: owner.to_string(), validator: msg.validator, stake: amount.clone(), tx_id, diff --git a/contracts/provider/external-staking/src/ibc.rs b/contracts/provider/external-staking/src/ibc.rs index 69127f2d..fc24ea14 100644 --- a/contracts/provider/external-staking/src/ibc.rs +++ b/contracts/provider/external-staking/src/ibc.rs @@ -155,6 +155,11 @@ pub fn ibc_packet_receive( .add_event(evt) .add_messages(msgs) } + ConsumerPacket::InternalUnstake { delegator, validator, amount} => { + let evt = contract.internal_unstake(deps, env, delegator, validator, amount)?; + let ack = ack_success(&DistributeAck {})?; + IbcReceiveResponse::new().set_ack(ack).add_event(evt) + } ConsumerPacket::Distribute { validator, rewards } => { let evt = contract.distribute_rewards(deps, &validator, rewards)?; let ack = ack_success(&DistributeAck {})?; diff --git a/packages/apis/src/converter_api.rs b/packages/apis/src/converter_api.rs index 8fc26412..d9d900e9 100644 --- a/packages/apis/src/converter_api.rs +++ b/packages/apis/src/converter_api.rs @@ -51,6 +51,16 @@ pub trait ConverterApi { tombstoned: Vec, slashed: Vec, ) -> Result, Self::Error>; + + /// Send ibc packet, request the external staking contract to unstake + #[sv::msg(exec)] + fn internal_unstake( + &self, + ctx: ExecCtx, + delegator: String, + validator: String, + amount: Coin, + ) -> Result, Self::Error>; } #[cw_serde] diff --git a/packages/apis/src/ibc/packet.rs b/packages/apis/src/ibc/packet.rs index 0978b9e8..7d02b76b 100644 --- a/packages/apis/src/ibc/packet.rs +++ b/packages/apis/src/ibc/packet.rs @@ -12,6 +12,7 @@ use crate::converter_api::{RewardInfo, ValidatorSlashInfo}; pub enum ProviderPacket { /// This should be called when we lock more tokens to virtually stake on a given validator Stake { + delegator: String, validator: String, /// This is the local (provider-side) denom that is held in the vault. /// It will be converted to the consumer-side staking token in the converter with help @@ -22,6 +23,7 @@ pub enum ProviderPacket { }, /// This should be called when we begin the unbonding period of some more tokens previously virtually staked Unstake { + delegator: String, validator: String, /// This is the local (provider-side) denom that is held in the vault. /// It will be converted to the consumer-side staking token in the converter with help @@ -110,6 +112,14 @@ pub enum ConsumerPacket { /// This has precedence over all other events in the same packet. slashed: Vec, }, + InternalUnstake { + delegator: String, + validator: String, + /// This is the local (provider-side) denom that is held in the vault. + /// It will be converted to the consumer-side staking token in the converter with help + /// of the price feed. + amount: Coin, + }, /// This is part of the rewards protocol Distribute { /// The validator whose stakers should receive these rewards diff --git a/packages/apis/src/virtual_staking_api.rs b/packages/apis/src/virtual_staking_api.rs index 982855ce..5c6df27e 100644 --- a/packages/apis/src/virtual_staking_api.rs +++ b/packages/apis/src/virtual_staking_api.rs @@ -25,6 +25,7 @@ pub trait VirtualStakingApi { fn bond( &self, ctx: ExecCtx, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error>; @@ -36,6 +37,7 @@ pub trait VirtualStakingApi { fn unbond( &self, ctx: ExecCtx, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error>; @@ -51,6 +53,17 @@ pub trait VirtualStakingApi { amount: Coin, ) -> Result, Self::Error>; + /// TODO: docs for this function + /// + #[sv::msg(exec)] + fn internal_unbond( + &self, + ctx: ExecCtx, + delegator: String, + validator: String, + amount: Coin, + ) -> Result, Self::Error>; + /// SudoMsg::HandleEpoch{} should be called once per epoch by the sdk (in EndBlock). /// It allows the virtual staking contract to bond or unbond any pending requests, as well /// as to perform a rebalance if needed (over the max cap). diff --git a/packages/bindings/src/query.rs b/packages/bindings/src/query.rs index 07af5ac5..c561ec17 100644 --- a/packages/bindings/src/query.rs +++ b/packages/bindings/src/query.rs @@ -1,5 +1,5 @@ use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::{Coin, CustomQuery, QuerierWrapper, QueryRequest, StdResult}; +use cosmwasm_std::{Coin, Uint128, CustomQuery, QuerierWrapper, QueryRequest, StdResult}; #[cw_serde] #[derive(QueryResponses)] @@ -21,6 +21,10 @@ pub enum VirtualStakeQuery { /// Returns the blockchain's slashing ratios. #[returns(SlashRatioResponse)] SlashRatio {}, + + /// Returns a max retrieve amount of delegations for the given contract + #[returns(AllDelegationsResponse)] + AllDelegations { contract: String, max_retrieve: u16 }, } /// Bookkeeping info in the virtual staking sdk module @@ -42,6 +46,18 @@ pub struct SlashRatioResponse { pub slash_fraction_double_sign: String, } +#[cw_serde] +pub struct AllDelegationsResponse { + pub delegations: Vec, +} + +#[cw_serde] +pub struct Delegation { + pub delegator: String, + pub validator: String, + pub amount: Uint128, +} + impl CustomQuery for VirtualStakeCustomQuery {} impl From for QueryRequest { @@ -69,4 +85,9 @@ impl<'a> TokenQuerier<'a> { let slash_ratio_query = VirtualStakeQuery::SlashRatio {}; self.querier.query(&slash_ratio_query.into()) } + + pub fn all_delegations(&self, contract: String, max_retrieve: u16) -> StdResult { + let all_delegations_query = VirtualStakeQuery::AllDelegations { contract, max_retrieve }; + self.querier.query(&all_delegations_query.into()) + } } diff --git a/packages/virtual-staking-mock/src/lib.rs b/packages/virtual-staking-mock/src/lib.rs index 09abfeb6..b9a8b7b7 100644 --- a/packages/virtual-staking-mock/src/lib.rs +++ b/packages/virtual-staking-mock/src/lib.rs @@ -1,9 +1,6 @@ use anyhow::Result as AnyResult; use cosmwasm_std::{ - coin, - testing::{MockApi, MockStorage}, - to_json_binary, Addr, Api, Binary, BlockInfo, CustomQuery, Empty, Querier, QuerierWrapper, - Storage, Uint128, + coin, testing::{MockApi, MockStorage}, to_json_binary, Addr, AllDelegationsResponse, Api, Binary, BlockInfo, CustomQuery, Empty, Querier, QuerierWrapper, Storage, Uint128 }; use cw_multi_test::{AppResponse, BankKeeper, Module, WasmKeeper}; use cw_storage_plus::{Item, Map}; @@ -181,6 +178,11 @@ impl Module for VirtualStakingModule { mesh_bindings::VirtualStakeQuery::SlashRatio {} => { to_json_binary(&self.slash_ratio.load(storage)?)? } + mesh_bindings::VirtualStakeQuery::AllDelegations { .. } => { + to_json_binary(&AllDelegationsResponse { + delegations: vec![] + })? + } }; Ok(to_json_binary(&result)?) From 766fe9816e48eec42820ef52a290840602b2ae9d Mon Sep 17 00:00:00 2001 From: Trinity Date: Tue, 2 Jul 2024 16:24:31 +0700 Subject: [PATCH 02/15] change internal_unstake logic to immediate --- .../provider/external-staking/src/contract.rs | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index 2b996ea4..542ece4f 100644 --- a/contracts/provider/external-staking/src/contract.rs +++ b/contracts/provider/external-staking/src/contract.rs @@ -446,6 +446,7 @@ impl ExternalStakingContract<'_> { Ok(()) } + // immediate unstake assets pub(crate) fn internal_unstake( &self, deps: DepsMut, @@ -454,7 +455,6 @@ impl ExternalStakingContract<'_> { validator: String, amount: Coin, ) -> Result { - let config = self.config.load(deps.storage)?; let user = deps.api.addr_validate(&delegator)?; // Load stake let mut stake = self.stakes.stake.load(deps.storage, (&user, &validator))?; @@ -469,19 +469,7 @@ impl ExternalStakingContract<'_> { let amount = min(amount.amount, stake.stake.high()); stake.stake.commit_sub(amount); - let immediate_release = matches!( - self.val_set.validator_state(deps.storage, &validator)?, - State::Unbonded {} | State::Tombstoned {} - ); - - // FIXME? Release period being computed after successful IBC tx - // (Note: this is good for now, but can be revisited in v1 design) - let release_at = if immediate_release { - env.block.time - } else { - env.block.time.plus_seconds(config.unbonding_period) - }; - let unbond = PendingUnbond { amount, release_at }; + let unbond = PendingUnbond { amount, release_at: env.block.time }; stake.pending_unbonds.push(unbond); // Distribution alignment From 4cc0bab7b742178506a5ee92fab98723bfc62939 Mon Sep 17 00:00:00 2001 From: Trinity Date: Wed, 3 Jul 2024 16:17:55 +0700 Subject: [PATCH 03/15] move update delegation to separate msg --- .../consumer/virtual-staking/src/contract.rs | 20 +++++++++++++++---- packages/bindings/src/msg.rs | 16 +++++++++++++++ packages/virtual-staking-mock/src/lib.rs | 3 +++ 3 files changed, 35 insertions(+), 4 deletions(-) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index 01f23edc..0697374f 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -363,7 +363,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn bond( &self, ctx: ExecCtx, - _delegator: String, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -385,7 +385,13 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { self.bond_requests .save(ctx.deps.storage, &validator, &bonded)?; - Ok(Response::new()) + let msg = VirtualStakeMsg::UpdateDelegation { + amount, + is_deduct: false, + delegator, + validator + }; + Ok(Response::new().add_message(msg)) } /// Requests to unbond tokens from a validator. This will be actually handled at the next epoch. @@ -394,7 +400,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn unbond( &self, ctx: ExecCtx, - _delegator: String, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -415,7 +421,13 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { self.bond_requests .save(ctx.deps.storage, &validator, &bonded)?; - Ok(Response::new()) + let msg = VirtualStakeMsg::UpdateDelegation { + amount, + is_deduct: true, + delegator, + validator + }; + Ok(Response::new().add_message(msg)) } /// Requests to unbond and burn tokens from a list of validators. Unbonding will be actually handled at the next epoch. diff --git a/packages/bindings/src/msg.rs b/packages/bindings/src/msg.rs index 4ecce123..850fcf0b 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -30,6 +30,9 @@ pub enum VirtualStakeMsg { /// It will then burn those tokens from the caller's account, /// and update the currently minted amount. Unbond { amount: Coin, validator: String }, + /// TODO: Add docs for this msg + /// + UpdateDelegation { amount: Coin, is_deduct: bool, delegator: String, validator: String}, } impl VirtualStakeMsg { @@ -54,6 +57,19 @@ impl VirtualStakeMsg { validator: validator.to_string(), } } + + pub fn update_delegation(denom: &str, is_deduct: bool, amount: impl Into, delgator: &str, validator: &str) -> VirtualStakeMsg { + let coin = Coin { + amount: amount.into(), + denom: denom.into(), + }; + VirtualStakeMsg::UpdateDelegation { + amount: coin, + is_deduct, + delegator: delgator.to_string(), + validator: validator.to_string(), + } + } } impl From for CosmosMsg { diff --git a/packages/virtual-staking-mock/src/lib.rs b/packages/virtual-staking-mock/src/lib.rs index b9a8b7b7..31e9a0b1 100644 --- a/packages/virtual-staking-mock/src/lib.rs +++ b/packages/virtual-staking-mock/src/lib.rs @@ -132,6 +132,9 @@ impl Module for VirtualStakingModule { Err(anyhow::anyhow!("bonded amount exceeded")) } } + mesh_bindings::VirtualStakeMsg::UpdateDelegation { .. } => { + Ok(AppResponse::default()) + } } } From 3d0c6025cdcc67f5dd1260cedf7db3e6211c134f Mon Sep 17 00:00:00 2001 From: Trinity Date: Fri, 5 Jul 2024 20:40:54 +0700 Subject: [PATCH 04/15] move max_retrieve to config --- contracts/consumer/virtual-staking/src/contract.rs | 11 ++++++----- contracts/consumer/virtual-staking/src/state.rs | 4 ++++ contracts/provider/vault/src/contract.rs | 3 +-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index 0697374f..af20e3ac 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -24,9 +24,6 @@ use crate::state::Config; pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME"); pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); -// TODO: lack test for the appropriate max retrieve. -pub const MAX_RETRIEVE: u16 = 50; - pub struct VirtualStakingContract<'a> { pub config: Item<'a, Config>, /// Amount of tokens that have been requested to bond to a validator @@ -77,12 +74,14 @@ impl VirtualStakingContract<'_> { pub fn instantiate( &self, ctx: InstantiateCtx, + max_retrieve: u16 ) -> Result, ContractError> { nonpayable(&ctx.info)?; let denom = ctx.deps.querier.query_bonded_denom()?; let config = Config { denom, converter: ctx.info.sender, + max_retrieve: max_retrieve, }; self.config.save(ctx.deps.storage, &config)?; // initialize these to no one, so no issue when reading for the first time @@ -569,7 +568,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { if max_cap.is_zero() { let all_delegations = TokenQuerier::new(&deps.querier).all_delegations( - env.contract.address.to_string(), MAX_RETRIEVE + env.contract.address.to_string(), config.max_retrieve )?; let mut msgs = vec![]; for delegation in all_delegations.delegations { @@ -1419,7 +1418,9 @@ mod tests { deps, env: mock_env(), info: mock_info("me", &[]), - }) + }, + 50 + ) .unwrap(); } diff --git a/contracts/consumer/virtual-staking/src/state.rs b/contracts/consumer/virtual-staking/src/state.rs index 705e61a7..931bb7db 100644 --- a/contracts/consumer/virtual-staking/src/state.rs +++ b/contracts/consumer/virtual-staking/src/state.rs @@ -8,4 +8,8 @@ pub struct Config { /// The address of the converter contract (that is authorized to bond/unbond and will receive rewards) pub converter: Addr, + + /// Maximum + /// + pub max_retrieve: u16, } diff --git a/contracts/provider/vault/src/contract.rs b/contracts/provider/vault/src/contract.rs index 04a0d0e6..4538295e 100644 --- a/contracts/provider/vault/src/contract.rs +++ b/contracts/provider/vault/src/contract.rs @@ -1,6 +1,5 @@ use cosmwasm_std::{ - coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, - StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg, + coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, StdError, StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg }; use cw2::set_contract_version; use cw_storage_plus::{Bounder, Item, Map}; From 1f9b907390e7a8754f32ae2b53f49c3d0458ef55 Mon Sep 17 00:00:00 2001 From: Trinity Date: Tue, 9 Jul 2024 14:47:57 +0700 Subject: [PATCH 05/15] make max_retrieve work on converter contract --- Cargo.lock | 1 + contracts/consumer/converter/Cargo.toml | 3 ++- contracts/consumer/converter/src/contract.rs | 10 +++++++--- contracts/consumer/converter/src/multitest.rs | 1 + contracts/consumer/virtual-staking/src/multitest.rs | 1 + contracts/provider/vault/src/contract.rs | 3 ++- 6 files changed, 14 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ae9071cf..e73e7d98 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -611,6 +611,7 @@ dependencies = [ "mesh-burn", "mesh-simple-price-feed", "mesh-sync", + "mesh-virtual-staking", "schemars", "serde", "sylvia", diff --git a/contracts/consumer/converter/Cargo.toml b/contracts/consumer/converter/Cargo.toml index 0a03ffe6..aefd9b14 100644 --- a/contracts/consumer/converter/Cargo.toml +++ b/contracts/consumer/converter/Cargo.toml @@ -24,6 +24,7 @@ fake-custom = [ "mesh-simple-price-feed/fake-custom" ] mesh-apis = { workspace = true } mesh-bindings = { workspace = true } mesh-sync = { workspace = true } +mesh-virtual-staking = { workspace = true } sylvia = { workspace = true } cosmwasm-schema = { workspace = true } @@ -39,7 +40,7 @@ thiserror = { workspace = true } [dev-dependencies] mesh-burn = { workspace = true } mesh-simple-price-feed = { workspace = true, features = ["mt"] } - +mesh-virtual-staking = { workspace = true, features = ["mt"] } cw-multi-test = { workspace = true } test-case = { workspace = true } derivative = { workspace = true } diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index ba62e558..674606e4 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -74,6 +74,7 @@ impl ConverterContract<'_> { remote_denom: String, virtual_staking_code_id: u64, admin: Option, + max_retrieve: u16, ) -> Result { nonpayable(&ctx.info)?; // validate args @@ -97,11 +98,14 @@ impl ConverterContract<'_> { ctx.deps.api.addr_validate(admin)?; } + let msg = to_json_binary(&mesh_virtual_staking::contract::sv::InstantiateMsg{ + max_retrieve + })?; // Instantiate virtual staking contract let init_msg = WasmMsg::Instantiate { admin, code_id: virtual_staking_code_id, - msg: b"{}".into(), + msg, funds: vec![], label: format!("Virtual Staking: {}", &config.remote_denom), }; @@ -151,7 +155,7 @@ impl ConverterContract<'_> { } #[cfg(not(any(test, feature = "mt")))] { - let _ = (ctx, validator, stake); + let _ = (ctx, delegator, validator, stake); Err(ContractError::Unauthorized) } } @@ -173,7 +177,7 @@ impl ConverterContract<'_> { } #[cfg(not(any(test, feature = "mt")))] { - let _ = (ctx, validator, unstake); + let _ = (ctx, delegator, validator, unstake); Err(ContractError::Unauthorized) } } diff --git a/contracts/consumer/converter/src/multitest.rs b/contracts/consumer/converter/src/multitest.rs index 2ee2b19e..56ac9181 100644 --- a/contracts/consumer/converter/src/multitest.rs +++ b/contracts/consumer/converter/src/multitest.rs @@ -63,6 +63,7 @@ fn setup<'a>(app: &'a App, args: SetupArgs<'a>) -> SetupResponse<'a> { JUNO.to_owned(), virtual_staking_code.code_id(), Some(admin.to_owned()), + 50 ) .with_label("Juno Converter") .with_admin(admin) diff --git a/contracts/consumer/virtual-staking/src/multitest.rs b/contracts/consumer/virtual-staking/src/multitest.rs index 54be3760..76f6ff1e 100644 --- a/contracts/consumer/virtual-staking/src/multitest.rs +++ b/contracts/consumer/virtual-staking/src/multitest.rs @@ -60,6 +60,7 @@ fn setup<'a>(app: &'a App, args: SetupArgs<'a>) -> SetupResponse<'a> { JUNO.to_owned(), virtual_staking_code.code_id(), Some(admin.to_owned()), + 50, ) .with_label("Juno Converter") .with_admin(admin) diff --git a/contracts/provider/vault/src/contract.rs b/contracts/provider/vault/src/contract.rs index 4538295e..7a7d0d5a 100644 --- a/contracts/provider/vault/src/contract.rs +++ b/contracts/provider/vault/src/contract.rs @@ -1,5 +1,5 @@ use cosmwasm_std::{ - coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, StdError, StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg + coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg }; use cw2::set_contract_version; use cw_storage_plus::{Bounder, Item, Map}; @@ -13,6 +13,7 @@ use mesh_apis::local_staking_api::{ use mesh_apis::vault_api::{self, SlashInfo, VaultApi}; use mesh_sync::Tx::InFlightStaking; use mesh_sync::{max_range, ValueRange}; + use sylvia::types::{ExecCtx, InstantiateCtx, QueryCtx, ReplyCtx}; use sylvia::{contract, schemars}; From 360a8f469a198ca948862424dc9e76448feceec8 Mon Sep 17 00:00:00 2001 From: Trinity Date: Mon, 5 Aug 2024 11:20:09 +0700 Subject: [PATCH 06/15] lint --- contracts/consumer/converter/src/contract.rs | 5 +- contracts/consumer/converter/src/ibc.rs | 22 ++++--- contracts/consumer/converter/src/multitest.rs | 4 +- .../src/multitest/virtual_staking_mock.rs | 10 +-- .../consumer/virtual-staking/src/contract.rs | 64 ++++++++++--------- .../consumer/virtual-staking/src/state.rs | 4 +- .../provider/external-staking/src/contract.rs | 5 +- .../provider/external-staking/src/ibc.rs | 6 +- contracts/provider/vault/src/contract.rs | 3 +- packages/apis/src/virtual_staking_api.rs | 2 +- packages/bindings/src/msg.rs | 19 ++++-- packages/bindings/src/query.rs | 15 +++-- packages/virtual-staking-mock/src/lib.rs | 11 ++-- 13 files changed, 102 insertions(+), 68 deletions(-) diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index 674606e4..900401ec 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -98,9 +98,8 @@ impl ConverterContract<'_> { ctx.deps.api.addr_validate(admin)?; } - let msg = to_json_binary(&mesh_virtual_staking::contract::sv::InstantiateMsg{ - max_retrieve - })?; + let msg = + to_json_binary(&mesh_virtual_staking::contract::sv::InstantiateMsg { max_retrieve })?; // Instantiate virtual staking contract let init_msg = WasmMsg::Instantiate { admin, diff --git a/contracts/consumer/converter/src/ibc.rs b/contracts/consumer/converter/src/ibc.rs index f719fee8..875809b3 100644 --- a/contracts/consumer/converter/src/ibc.rs +++ b/contracts/consumer/converter/src/ibc.rs @@ -54,7 +54,10 @@ pub fn packet_timeout_rewards(env: &Env) -> IbcTimeout { pub fn packet_timeout_internal_unstake(env: &Env) -> IbcTimeout { // No idea about their block time, but 24 hours ahead of our view of the clock // should be decently in the future. - let timeout = env.block.time.plus_seconds(DEFAULT_INTERNAL_UNSTAKE_TIMEOUT); + let timeout = env + .block + .time + .plus_seconds(DEFAULT_INTERNAL_UNSTAKE_TIMEOUT); IbcTimeout::with_timestamp(timeout) } @@ -267,15 +270,16 @@ pub fn ibc_packet_ack( match ack { AckWrapper::Result(_) => { let packet: ConsumerPacket = from_json(&msg.original_packet.data)?; - if let ConsumerPacket::InternalUnstake { - delegator, - validator, - amount, - } = packet { - // execute virtual contract's internal unbond + if let ConsumerPacket::InternalUnstake { + delegator, + validator, + amount, + } = packet + { + // execute virtual contract's internal unbond let msg = virtual_staking_api::sv::ExecMsg::InternalUnbond { - delegator, - validator, + delegator, + validator, amount, }; let msg = WasmMsg::Execute { diff --git a/contracts/consumer/converter/src/multitest.rs b/contracts/consumer/converter/src/multitest.rs index 56ac9181..6d3a8ab7 100644 --- a/contracts/consumer/converter/src/multitest.rs +++ b/contracts/consumer/converter/src/multitest.rs @@ -63,7 +63,7 @@ fn setup<'a>(app: &'a App, args: SetupArgs<'a>) -> SetupResponse<'a> { JUNO.to_owned(), virtual_staking_code.code_id(), Some(admin.to_owned()), - 50 + 50, ) .with_label("Juno Converter") .with_admin(admin) @@ -259,7 +259,7 @@ fn ibc_stake_and_burn() { // let's stake some converter - .test_stake(owner.to_string(),val1.to_string(), coin(1000, JUNO)) + .test_stake(owner.to_string(), val1.to_string(), coin(1000, JUNO)) .call(owner) .unwrap(); converter diff --git a/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs b/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs index d4422445..96048e17 100644 --- a/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs +++ b/contracts/consumer/converter/src/multitest/virtual_staking_mock.rs @@ -245,11 +245,11 @@ impl VirtualStakingApi for VirtualStakingMock<'_> { fn internal_unbond( &self, - _ctx:ExecCtx, - _delegator:String, - _validator:String, - _amount:Coin - ) -> Result ,Self::Error> { + _ctx: ExecCtx, + _delegator: String, + _validator: String, + _amount: Coin, + ) -> Result, Self::Error> { unimplemented!() } diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index af20e3ac..96425c3e 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -74,7 +74,7 @@ impl VirtualStakingContract<'_> { pub fn instantiate( &self, ctx: InstantiateCtx, - max_retrieve: u16 + max_retrieve: u16, ) -> Result, ContractError> { nonpayable(&ctx.info)?; let denom = ctx.deps.querier.query_bonded_denom()?; @@ -384,11 +384,11 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { self.bond_requests .save(ctx.deps.storage, &validator, &bonded)?; - let msg = VirtualStakeMsg::UpdateDelegation { - amount, + let msg = VirtualStakeMsg::UpdateDelegation { + amount, is_deduct: false, - delegator, - validator + delegator, + validator, }; Ok(Response::new().add_message(msg)) } @@ -420,11 +420,11 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { self.bond_requests .save(ctx.deps.storage, &validator, &bonded)?; - let msg = VirtualStakeMsg::UpdateDelegation { - amount, + let msg = VirtualStakeMsg::UpdateDelegation { + amount, is_deduct: true, - delegator, - validator + delegator, + validator, }; Ok(Response::new().add_message(msg)) } @@ -498,7 +498,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { _delegator: String, validator: String, amount: Coin, - ) -> Result, Self::Error> { + ) -> Result, Self::Error> { nonpayable(&ctx.info)?; let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(ctx.info.sender, cfg.converter, ContractError::Unauthorized); // only the converter can call this @@ -526,7 +526,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { ) .collect::>()?; self.bonded.save(ctx.deps.storage, &requests)?; - return Ok(Response::new()) + return Ok(Response::new()); } // FIXME: need to handle custom message types and queries @@ -566,18 +566,19 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { // call and set bonded to empty // TODO: verify this behavior with SDK module (otherwise we send unbond message) if max_cap.is_zero() { - let all_delegations = - TokenQuerier::new(&deps.querier).all_delegations( - env.contract.address.to_string(), config.max_retrieve - )?; + let all_delegations = TokenQuerier::new(&deps.querier) + .all_delegations(env.contract.address.to_string(), config.max_retrieve)?; let mut msgs = vec![]; for delegation in all_delegations.delegations { let validator = delegation.validator.clone(); // Send unstake request to converter contract - let msg = converter_api::sv::ExecMsg::InternalUnstake { - delegator: delegation.delegator, - validator: validator, - amount: Coin { denom: config.denom.clone(), amount: delegation.amount } + let msg = converter_api::sv::ExecMsg::InternalUnstake { + delegator: delegation.delegator, + validator: validator, + amount: Coin { + denom: config.denom.clone(), + amount: delegation.amount, + }, }; let msg = WasmMsg::Execute { contract_addr: config.converter.to_string(), @@ -719,7 +720,9 @@ mod tests { }; use cosmwasm_std::{ - coins, from_json, testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage}, AllDelegationsResponse, Decimal + coins, from_json, + testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage}, + AllDelegationsResponse, Decimal, }; use mesh_bindings::{BondStatusResponse, SlashRatioResponse}; @@ -1285,8 +1288,8 @@ mod tests { slash_fraction_downtime: "0.1".to_string(), slash_fraction_double_sign: "0.25".to_string(), }); - let all_delegations = MockAllDelegations::new(AllDelegationsResponse { - delegations: vec![] + let all_delegations = MockAllDelegations::new(AllDelegationsResponse { + delegations: vec![], }); let handler = { @@ -1371,7 +1374,7 @@ mod tests { self.0.borrow() } } - + fn set_reward_targets(storage: &mut dyn Storage, targets: &[&str]) { REWARD_TARGETS .save( @@ -1414,13 +1417,14 @@ mod tests { impl VirtualStakingExt for VirtualStakingContract<'_> { fn quick_inst(&self, deps: DepsMut) { - self.instantiate(InstantiateCtx { - deps, - env: mock_env(), - info: mock_info("me", &[]), - }, - 50 - ) + self.instantiate( + InstantiateCtx { + deps, + env: mock_env(), + info: mock_info("me", &[]), + }, + 50, + ) .unwrap(); } diff --git a/contracts/consumer/virtual-staking/src/state.rs b/contracts/consumer/virtual-staking/src/state.rs index 931bb7db..76a6cb25 100644 --- a/contracts/consumer/virtual-staking/src/state.rs +++ b/contracts/consumer/virtual-staking/src/state.rs @@ -9,7 +9,7 @@ pub struct Config { /// The address of the converter contract (that is authorized to bond/unbond and will receive rewards) pub converter: Addr, - /// Maximum - /// + /// Maximum + /// pub max_retrieve: u16, } diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index 542ece4f..d2684505 100644 --- a/contracts/provider/external-staking/src/contract.rs +++ b/contracts/provider/external-staking/src/contract.rs @@ -469,7 +469,10 @@ impl ExternalStakingContract<'_> { let amount = min(amount.amount, stake.stake.high()); stake.stake.commit_sub(amount); - let unbond = PendingUnbond { amount, release_at: env.block.time }; + let unbond = PendingUnbond { + amount, + release_at: env.block.time, + }; stake.pending_unbonds.push(unbond); // Distribution alignment diff --git a/contracts/provider/external-staking/src/ibc.rs b/contracts/provider/external-staking/src/ibc.rs index fc24ea14..42cf9328 100644 --- a/contracts/provider/external-staking/src/ibc.rs +++ b/contracts/provider/external-staking/src/ibc.rs @@ -155,7 +155,11 @@ pub fn ibc_packet_receive( .add_event(evt) .add_messages(msgs) } - ConsumerPacket::InternalUnstake { delegator, validator, amount} => { + ConsumerPacket::InternalUnstake { + delegator, + validator, + amount, + } => { let evt = contract.internal_unstake(deps, env, delegator, validator, amount)?; let ack = ack_success(&DistributeAck {})?; IbcReceiveResponse::new().set_ack(ack).add_event(evt) diff --git a/contracts/provider/vault/src/contract.rs b/contracts/provider/vault/src/contract.rs index 7a7d0d5a..33ad3987 100644 --- a/contracts/provider/vault/src/contract.rs +++ b/contracts/provider/vault/src/contract.rs @@ -1,5 +1,6 @@ use cosmwasm_std::{ - coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg + coin, ensure, Addr, BankMsg, Binary, Coin, Decimal, DepsMut, Fraction, Order, Reply, Response, + StdResult, Storage, SubMsg, SubMsgResponse, Uint128, WasmMsg, }; use cw2::set_contract_version; use cw_storage_plus::{Bounder, Item, Map}; diff --git a/packages/apis/src/virtual_staking_api.rs b/packages/apis/src/virtual_staking_api.rs index 5c6df27e..ed02e47b 100644 --- a/packages/apis/src/virtual_staking_api.rs +++ b/packages/apis/src/virtual_staking_api.rs @@ -54,7 +54,7 @@ pub trait VirtualStakingApi { ) -> Result, Self::Error>; /// TODO: docs for this function - /// + /// #[sv::msg(exec)] fn internal_unbond( &self, diff --git a/packages/bindings/src/msg.rs b/packages/bindings/src/msg.rs index 850fcf0b..49e3b36a 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -31,8 +31,13 @@ pub enum VirtualStakeMsg { /// and update the currently minted amount. Unbond { amount: Coin, validator: String }, /// TODO: Add docs for this msg - /// - UpdateDelegation { amount: Coin, is_deduct: bool, delegator: String, validator: String}, + /// + UpdateDelegation { + amount: Coin, + is_deduct: bool, + delegator: String, + validator: String, + }, } impl VirtualStakeMsg { @@ -57,8 +62,14 @@ impl VirtualStakeMsg { validator: validator.to_string(), } } - - pub fn update_delegation(denom: &str, is_deduct: bool, amount: impl Into, delgator: &str, validator: &str) -> VirtualStakeMsg { + + pub fn update_delegation( + denom: &str, + is_deduct: bool, + amount: impl Into, + delgator: &str, + validator: &str, + ) -> VirtualStakeMsg { let coin = Coin { amount: amount.into(), denom: denom.into(), diff --git a/packages/bindings/src/query.rs b/packages/bindings/src/query.rs index c561ec17..72b3bf14 100644 --- a/packages/bindings/src/query.rs +++ b/packages/bindings/src/query.rs @@ -1,5 +1,5 @@ use cosmwasm_schema::{cw_serde, QueryResponses}; -use cosmwasm_std::{Coin, Uint128, CustomQuery, QuerierWrapper, QueryRequest, StdResult}; +use cosmwasm_std::{Coin, CustomQuery, QuerierWrapper, QueryRequest, StdResult, Uint128}; #[cw_serde] #[derive(QueryResponses)] @@ -22,7 +22,7 @@ pub enum VirtualStakeQuery { #[returns(SlashRatioResponse)] SlashRatio {}, - /// Returns a max retrieve amount of delegations for the given contract + /// Returns a max retrieve amount of delegations for the given contract #[returns(AllDelegationsResponse)] AllDelegations { contract: String, max_retrieve: u16 }, } @@ -86,8 +86,15 @@ impl<'a> TokenQuerier<'a> { self.querier.query(&slash_ratio_query.into()) } - pub fn all_delegations(&self, contract: String, max_retrieve: u16) -> StdResult { - let all_delegations_query = VirtualStakeQuery::AllDelegations { contract, max_retrieve }; + pub fn all_delegations( + &self, + contract: String, + max_retrieve: u16, + ) -> StdResult { + let all_delegations_query = VirtualStakeQuery::AllDelegations { + contract, + max_retrieve, + }; self.querier.query(&all_delegations_query.into()) } } diff --git a/packages/virtual-staking-mock/src/lib.rs b/packages/virtual-staking-mock/src/lib.rs index 31e9a0b1..44dd07af 100644 --- a/packages/virtual-staking-mock/src/lib.rs +++ b/packages/virtual-staking-mock/src/lib.rs @@ -1,6 +1,9 @@ use anyhow::Result as AnyResult; use cosmwasm_std::{ - coin, testing::{MockApi, MockStorage}, to_json_binary, Addr, AllDelegationsResponse, Api, Binary, BlockInfo, CustomQuery, Empty, Querier, QuerierWrapper, Storage, Uint128 + coin, + testing::{MockApi, MockStorage}, + to_json_binary, Addr, AllDelegationsResponse, Api, Binary, BlockInfo, CustomQuery, Empty, + Querier, QuerierWrapper, Storage, Uint128, }; use cw_multi_test::{AppResponse, BankKeeper, Module, WasmKeeper}; use cw_storage_plus::{Item, Map}; @@ -132,9 +135,7 @@ impl Module for VirtualStakingModule { Err(anyhow::anyhow!("bonded amount exceeded")) } } - mesh_bindings::VirtualStakeMsg::UpdateDelegation { .. } => { - Ok(AppResponse::default()) - } + mesh_bindings::VirtualStakeMsg::UpdateDelegation { .. } => Ok(AppResponse::default()), } } @@ -183,7 +184,7 @@ impl Module for VirtualStakingModule { } mesh_bindings::VirtualStakeQuery::AllDelegations { .. } => { to_json_binary(&AllDelegationsResponse { - delegations: vec![] + delegations: vec![], })? } }; From d7fa3964502e7b71516ea37c37321c980fbbffaa Mon Sep 17 00:00:00 2001 From: Trinity Date: Mon, 5 Aug 2024 11:28:40 +0700 Subject: [PATCH 07/15] lint --- contracts/consumer/virtual-staking/src/contract.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index 96425c3e..b087cd47 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -81,7 +81,7 @@ impl VirtualStakingContract<'_> { let config = Config { denom, converter: ctx.info.sender, - max_retrieve: max_retrieve, + max_retrieve, }; self.config.save(ctx.deps.storage, &config)?; // initialize these to no one, so no issue when reading for the first time @@ -526,7 +526,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { ) .collect::>()?; self.bonded.save(ctx.deps.storage, &requests)?; - return Ok(Response::new()); + Ok(Response::new()) } // FIXME: need to handle custom message types and queries @@ -574,7 +574,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { // Send unstake request to converter contract let msg = converter_api::sv::ExecMsg::InternalUnstake { delegator: delegation.delegator, - validator: validator, + validator, amount: Coin { denom: config.denom.clone(), amount: delegation.amount, From 0894cda3e4bed0e6e28ad200a099f433a8dd2c9d Mon Sep 17 00:00:00 2001 From: Trinity Date: Mon, 5 Aug 2024 11:40:06 +0700 Subject: [PATCH 08/15] add doc --- packages/apis/src/ibc/packet.rs | 2 ++ packages/apis/src/virtual_staking_api.rs | 5 +++-- packages/bindings/src/msg.rs | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/apis/src/ibc/packet.rs b/packages/apis/src/ibc/packet.rs index 7d02b76b..c873f697 100644 --- a/packages/apis/src/ibc/packet.rs +++ b/packages/apis/src/ibc/packet.rs @@ -112,6 +112,8 @@ pub enum ConsumerPacket { /// This has precedence over all other events in the same packet. slashed: Vec, }, + /// This is a part of zero max cap process + /// The consumer chain will send this packet to provider, force user to unbond token InternalUnstake { delegator: String, validator: String, diff --git a/packages/apis/src/virtual_staking_api.rs b/packages/apis/src/virtual_staking_api.rs index ed02e47b..9377eee1 100644 --- a/packages/apis/src/virtual_staking_api.rs +++ b/packages/apis/src/virtual_staking_api.rs @@ -53,8 +53,9 @@ pub trait VirtualStakingApi { amount: Coin, ) -> Result, Self::Error>; - /// TODO: docs for this function - /// + /// Immediately unbond the given amount due to zero max cap + /// When the consumer chain receives ack packet from provider - which means the unbond process from provider is success, + /// consumer chain will trigger this function to unbond this contract actor staking base on the delegate amount. #[sv::msg(exec)] fn internal_unbond( &self, diff --git a/packages/bindings/src/msg.rs b/packages/bindings/src/msg.rs index 49e3b36a..74fecafe 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -30,8 +30,8 @@ pub enum VirtualStakeMsg { /// It will then burn those tokens from the caller's account, /// and update the currently minted amount. Unbond { amount: Coin, validator: String }, - /// TODO: Add docs for this msg - /// + /// After each bonding or unbond process, a msg will be sent to the chain + /// Consumer chain will save the data - represent each delegator's stake amount UpdateDelegation { amount: Coin, is_deduct: bool, From b6a0bfbe2dd1fdc5558fdd17595aa4782cf6be70 Mon Sep 17 00:00:00 2001 From: Trinity Date: Mon, 5 Aug 2024 11:41:03 +0700 Subject: [PATCH 09/15] lint --- contracts/consumer/converter/src/contract.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index 900401ec..d24f94ac 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -639,7 +639,7 @@ impl ConverterApi for ConverterContract<'_> { let channel = IBC_CHANNEL.load(ctx.deps.storage)?; let packet = ConsumerPacket::InternalUnstake { - delegator: delegator, + delegator, validator, amount, }; From aba6c2af282155baf185fc60db248365a00761e3 Mon Sep 17 00:00:00 2001 From: Trinity Date: Fri, 23 Aug 2024 13:49:31 +0700 Subject: [PATCH 10/15] Recalculate the price when unbond --- contracts/consumer/converter/src/contract.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index d24f94ac..5f2b0da3 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -638,6 +638,9 @@ impl ConverterApi for ConverterContract<'_> { .add_attribute("owner", delegator.clone()); let channel = IBC_CHANNEL.load(ctx.deps.storage)?; + + // Recalculate the price when unbond + let amount = self.invert_price(ctx.deps.as_ref(), amount)?; let packet = ConsumerPacket::InternalUnstake { delegator, validator, From 90c34a420889ec9836d6f238207fcf8cf84be0ff Mon Sep 17 00:00:00 2001 From: Trinity Date: Fri, 23 Aug 2024 15:15:19 +0700 Subject: [PATCH 11/15] fix logic for zero max cap --- contracts/consumer/converter/src/contract.rs | 5 +++-- contracts/consumer/converter/src/ibc.rs | 6 ++++-- .../consumer/virtual-staking/src/contract.rs | 16 ++++++++++++++-- .../provider/external-staking/src/contract.rs | 4 ++-- contracts/provider/external-staking/src/ibc.rs | 5 +++-- packages/apis/src/ibc/packet.rs | 3 ++- 6 files changed, 28 insertions(+), 11 deletions(-) diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index 5f2b0da3..894761b0 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -640,11 +640,12 @@ impl ConverterApi for ConverterContract<'_> { let channel = IBC_CHANNEL.load(ctx.deps.storage)?; // Recalculate the price when unbond - let amount = self.invert_price(ctx.deps.as_ref(), amount)?; + let inverted_amount = self.invert_price(ctx.deps.as_ref(), amount.clone())?; let packet = ConsumerPacket::InternalUnstake { delegator, validator, - amount, + normalize_amount: amount, + inverted_amount, }; let msg = IbcMsg::SendPacket { channel_id: channel.endpoint.channel_id, diff --git a/contracts/consumer/converter/src/ibc.rs b/contracts/consumer/converter/src/ibc.rs index 875809b3..0c8fb107 100644 --- a/contracts/consumer/converter/src/ibc.rs +++ b/contracts/consumer/converter/src/ibc.rs @@ -273,14 +273,16 @@ pub fn ibc_packet_ack( if let ConsumerPacket::InternalUnstake { delegator, validator, - amount, + normalize_amount, + inverted_amount: _, } = packet { + // execute virtual contract's internal unbond let msg = virtual_staking_api::sv::ExecMsg::InternalUnbond { delegator, validator, - amount, + amount: normalize_amount, }; let msg = WasmMsg::Execute { contract_addr: contract.virtual_stake.load(deps.storage)?.into(), diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index b087cd47..a6a302bc 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -495,7 +495,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn internal_unbond( &self, ctx: ExecCtx, - _delegator: String, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -526,7 +526,19 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { ) .collect::>()?; self.bonded.save(ctx.deps.storage, &requests)?; - Ok(Response::new()) + + let mut msgs: Vec<_> = vec![]; + msgs.push(VirtualStakeMsg::UpdateDelegation { + amount: amount.clone(), + is_deduct: true, + delegator, + validator: validator.clone(), + }); + msgs.push(VirtualStakeMsg::Unbond { + amount, + validator, + }); + Ok(Response::new().add_messages(msgs)) } // FIXME: need to handle custom message types and queries diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index d2684505..cd3a93c3 100644 --- a/contracts/provider/external-staking/src/contract.rs +++ b/contracts/provider/external-staking/src/contract.rs @@ -467,8 +467,8 @@ impl ExternalStakingContract<'_> { // Commit sub amount, saturating if slashed let amount = min(amount.amount, stake.stake.high()); - stake.stake.commit_sub(amount); - + stake.stake.sub(amount, Uint128::zero())?; + let unbond = PendingUnbond { amount, release_at: env.block.time, diff --git a/contracts/provider/external-staking/src/ibc.rs b/contracts/provider/external-staking/src/ibc.rs index 42cf9328..b054d7ec 100644 --- a/contracts/provider/external-staking/src/ibc.rs +++ b/contracts/provider/external-staking/src/ibc.rs @@ -158,9 +158,10 @@ pub fn ibc_packet_receive( ConsumerPacket::InternalUnstake { delegator, validator, - amount, + normalize_amount: _, + inverted_amount, } => { - let evt = contract.internal_unstake(deps, env, delegator, validator, amount)?; + let evt = contract.internal_unstake(deps, env, delegator, validator, inverted_amount)?; let ack = ack_success(&DistributeAck {})?; IbcReceiveResponse::new().set_ack(ack).add_event(evt) } diff --git a/packages/apis/src/ibc/packet.rs b/packages/apis/src/ibc/packet.rs index c873f697..86bdac64 100644 --- a/packages/apis/src/ibc/packet.rs +++ b/packages/apis/src/ibc/packet.rs @@ -120,7 +120,8 @@ pub enum ConsumerPacket { /// This is the local (provider-side) denom that is held in the vault. /// It will be converted to the consumer-side staking token in the converter with help /// of the price feed. - amount: Coin, + normalize_amount: Coin, + inverted_amount: Coin, }, /// This is part of the rewards protocol Distribute { From a0bba9b5f7eed6768d7a84ac766afb9d89dea4c2 Mon Sep 17 00:00:00 2001 From: Trinity Date: Fri, 23 Aug 2024 15:16:21 +0700 Subject: [PATCH 12/15] lint --- contracts/consumer/converter/src/contract.rs | 2 +- contracts/consumer/converter/src/ibc.rs | 1 - contracts/consumer/virtual-staking/src/contract.rs | 5 +---- contracts/provider/external-staking/src/contract.rs | 2 +- contracts/provider/external-staking/src/ibc.rs | 3 ++- 5 files changed, 5 insertions(+), 8 deletions(-) diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index 894761b0..98eb878c 100644 --- a/contracts/consumer/converter/src/contract.rs +++ b/contracts/consumer/converter/src/contract.rs @@ -640,7 +640,7 @@ impl ConverterApi for ConverterContract<'_> { let channel = IBC_CHANNEL.load(ctx.deps.storage)?; // Recalculate the price when unbond - let inverted_amount = self.invert_price(ctx.deps.as_ref(), amount.clone())?; + let inverted_amount = self.invert_price(ctx.deps.as_ref(), amount.clone())?; let packet = ConsumerPacket::InternalUnstake { delegator, validator, diff --git a/contracts/consumer/converter/src/ibc.rs b/contracts/consumer/converter/src/ibc.rs index 0c8fb107..90865843 100644 --- a/contracts/consumer/converter/src/ibc.rs +++ b/contracts/consumer/converter/src/ibc.rs @@ -277,7 +277,6 @@ pub fn ibc_packet_ack( inverted_amount: _, } = packet { - // execute virtual contract's internal unbond let msg = virtual_staking_api::sv::ExecMsg::InternalUnbond { delegator, diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index a6a302bc..a9cd06e0 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -534,10 +534,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { delegator, validator: validator.clone(), }); - msgs.push(VirtualStakeMsg::Unbond { - amount, - validator, - }); + msgs.push(VirtualStakeMsg::Unbond { amount, validator }); Ok(Response::new().add_messages(msgs)) } diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index cd3a93c3..115d1bef 100644 --- a/contracts/provider/external-staking/src/contract.rs +++ b/contracts/provider/external-staking/src/contract.rs @@ -468,7 +468,7 @@ impl ExternalStakingContract<'_> { // Commit sub amount, saturating if slashed let amount = min(amount.amount, stake.stake.high()); stake.stake.sub(amount, Uint128::zero())?; - + let unbond = PendingUnbond { amount, release_at: env.block.time, diff --git a/contracts/provider/external-staking/src/ibc.rs b/contracts/provider/external-staking/src/ibc.rs index b054d7ec..c8080f70 100644 --- a/contracts/provider/external-staking/src/ibc.rs +++ b/contracts/provider/external-staking/src/ibc.rs @@ -161,7 +161,8 @@ pub fn ibc_packet_receive( normalize_amount: _, inverted_amount, } => { - let evt = contract.internal_unstake(deps, env, delegator, validator, inverted_amount)?; + let evt = + contract.internal_unstake(deps, env, delegator, validator, inverted_amount)?; let ack = ack_success(&DistributeAck {})?; IbcReceiveResponse::new().set_ack(ack).add_event(evt) } From 2dd8d509702ce6c2cbbea250fe88ea2b6c185254 Mon Sep 17 00:00:00 2001 From: Trinity Date: Fri, 23 Aug 2024 16:33:26 +0700 Subject: [PATCH 13/15] lint --- .../consumer/virtual-staking/src/contract.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index a9cd06e0..a025575e 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -527,14 +527,15 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { .collect::>()?; self.bonded.save(ctx.deps.storage, &requests)?; - let mut msgs: Vec<_> = vec![]; - msgs.push(VirtualStakeMsg::UpdateDelegation { - amount: amount.clone(), - is_deduct: true, - delegator, - validator: validator.clone(), - }); - msgs.push(VirtualStakeMsg::Unbond { amount, validator }); + let msgs = vec![ + VirtualStakeMsg::UpdateDelegation { + amount: amount.clone(), + is_deduct: true, + delegator, + validator: validator.clone(), + }, + VirtualStakeMsg::Unbond { amount, validator } + ]; Ok(Response::new().add_messages(msgs)) } From 9d82cc7bf766a4ccab08212dea78bf4a42ef2e1a Mon Sep 17 00:00:00 2001 From: Trinity Date: Thu, 5 Sep 2024 11:50:07 +0700 Subject: [PATCH 14/15] Update schedule logic for zero max cap --- contracts/consumer/virtual-staking/src/contract.rs | 3 +++ packages/bindings/src/msg.rs | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index a025575e..fee5bd71 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -578,6 +578,9 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { if max_cap.is_zero() { let all_delegations = TokenQuerier::new(&deps.querier) .all_delegations(env.contract.address.to_string(), config.max_retrieve)?; + if all_delegations.delegations.len() == 0 { + return Ok(resp.add_message(VirtualStakeMsg::DeleteAllScheduledTasks{})); + } let mut msgs = vec![]; for delegation in all_delegations.delegations { let validator = delegation.validator.clone(); diff --git a/packages/bindings/src/msg.rs b/packages/bindings/src/msg.rs index d732f39a..e145ed48 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -38,6 +38,8 @@ pub enum VirtualStakeMsg { delegator: String, validator: String, }, + /// Delete all scheduled tasks after zero max cap and unbond all delegations + DeleteAllScheduledTasks {} } impl VirtualStakeMsg { @@ -81,6 +83,10 @@ impl VirtualStakeMsg { validator: validator.to_string(), } } + + pub fn delete_all_scheduled_tasks() -> VirtualStakeMsg { + VirtualStakeMsg::DeleteAllScheduledTasks {} + } } impl From for CosmosMsg { From 8b6f4ee0002e8bd285d790f52d204b848afbce7e Mon Sep 17 00:00:00 2001 From: Trinity Date: Thu, 5 Sep 2024 12:20:49 +0700 Subject: [PATCH 15/15] Fix tests --- contracts/consumer/virtual-staking/src/contract.rs | 8 ++++---- packages/bindings/src/msg.rs | 2 +- packages/virtual-staking-mock/src/lib.rs | 3 +++ 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/contracts/consumer/virtual-staking/src/contract.rs b/contracts/consumer/virtual-staking/src/contract.rs index fee5bd71..037e28d4 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -534,7 +534,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { delegator, validator: validator.clone(), }, - VirtualStakeMsg::Unbond { amount, validator } + VirtualStakeMsg::Unbond { amount, validator }, ]; Ok(Response::new().add_messages(msgs)) } @@ -579,7 +579,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { let all_delegations = TokenQuerier::new(&deps.querier) .all_delegations(env.contract.address.to_string(), config.max_retrieve)?; if all_delegations.delegations.len() == 0 { - return Ok(resp.add_message(VirtualStakeMsg::DeleteAllScheduledTasks{})); + return Ok(resp.add_message(VirtualStakeMsg::DeleteAllScheduledTasks {})); } let mut msgs = vec![]; for delegation in all_delegations.delegations { @@ -1737,9 +1737,9 @@ mod tests { #[track_caller] fn assert_no_bonding(&self) -> &Self { - if !self.virtual_stake_msgs.is_empty() { + if self.virtual_stake_msgs.len() > 1 { panic!( - "hit_epoch result was expected to be a noop, but has these: {:?}", + "hit_epoch result was expected to only contain DeleteAllScheduledTasks, but has these: {:?}", self.virtual_stake_msgs ); } diff --git a/packages/bindings/src/msg.rs b/packages/bindings/src/msg.rs index e145ed48..b897c850 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -39,7 +39,7 @@ pub enum VirtualStakeMsg { validator: String, }, /// Delete all scheduled tasks after zero max cap and unbond all delegations - DeleteAllScheduledTasks {} + DeleteAllScheduledTasks {}, } impl VirtualStakeMsg { diff --git a/packages/virtual-staking-mock/src/lib.rs b/packages/virtual-staking-mock/src/lib.rs index 44dd07af..0796f5e5 100644 --- a/packages/virtual-staking-mock/src/lib.rs +++ b/packages/virtual-staking-mock/src/lib.rs @@ -136,6 +136,9 @@ impl Module for VirtualStakingModule { } } mesh_bindings::VirtualStakeMsg::UpdateDelegation { .. } => Ok(AppResponse::default()), + mesh_bindings::VirtualStakeMsg::DeleteAllScheduledTasks { .. } => { + Ok(AppResponse::default()) + } } }