diff --git a/Cargo.lock b/Cargo.lock index 34953ac5..88c413ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -609,6 +609,7 @@ dependencies = [ "mesh-bindings", "mesh-burn", "mesh-simple-price-feed", + "mesh-sync", "mesh-virtual-staking", "schemars", "serde", @@ -676,6 +677,7 @@ dependencies = [ "cw2", "derivative", "mesh-apis", + "mesh-bindings", "mesh-burn", "mesh-native-staking", "mesh-vault", diff --git a/contracts/consumer/converter/Cargo.toml b/contracts/consumer/converter/Cargo.toml index f28e95fe..0d7b3858 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 } mesh-virtual-staking = { workspace = true } sylvia = { workspace = true } diff --git a/contracts/consumer/converter/src/contract.rs b/contracts/consumer/converter/src/contract.rs index 1c2fe4c6..c747ba45 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; @@ -73,6 +75,7 @@ impl ConverterContract<'_> { virtual_staking_code_id: u64, tombstoned_unbond_enable: bool, admin: Option, + max_retrieve: u16, ) -> Result { nonpayable(&ctx.info)?; // validate args @@ -97,6 +100,7 @@ impl ConverterContract<'_> { } let msg = to_json_binary(&mesh_virtual_staking::contract::sv::InstantiateMsg { + max_retrieve, tombstoned_unbond_enable, })?; // Instantiate virtual staking contract @@ -142,17 +146,18 @@ 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")))] { - let _ = (ctx, validator, stake); + let _ = (ctx, delegator, validator, stake); Err(ContractError::Unauthorized) } } @@ -163,17 +168,18 @@ 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")))] { - let _ = (ctx, validator, unstake); + let _ = (ctx, delegator, validator, unstake); Err(ContractError::Unauthorized) } } @@ -218,6 +224,7 @@ impl ConverterContract<'_> { pub(crate) fn stake( &self, deps: DepsMut, + delegator: String, validator: String, stake: Coin, ) -> Result { @@ -227,7 +234,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)?, @@ -242,6 +253,7 @@ impl ConverterContract<'_> { pub(crate) fn unstake( &self, deps: DepsMut, + delegator: String, validator: String, unstake: Coin, ) -> Result { @@ -251,7 +263,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)?, @@ -607,4 +623,40 @@ 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)?; + + // Recalculate the price when unbond + let inverted_amount = self.invert_price(ctx.deps.as_ref(), amount.clone())?; + let packet = ConsumerPacket::InternalUnstake { + delegator, + validator, + normalize_amount: amount, + inverted_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..90865843 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,16 @@ 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 +208,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 +222,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 +260,37 @@ 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, + normalize_amount, + inverted_amount: _, + } = packet + { + // execute virtual contract's internal unbond + let msg = virtual_staking_api::sv::ExecMsg::InternalUnbond { + delegator, + validator, + amount: normalize_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 afc410bb..7eab1e95 100644 --- a/contracts/consumer/converter/src/multitest.rs +++ b/contracts/consumer/converter/src/multitest.rs @@ -64,6 +64,7 @@ fn setup<'a>(app: &'a App, args: SetupArgs<'a>) -> SetupResponse<'a> { virtual_staking_code.code_id(), true, Some(admin.to_owned()), + 50, ) .with_label("Juno Converter") .with_admin(admin) @@ -173,17 +174,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(); @@ -259,11 +260,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..96048e17 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 3e124a5d..a1b52d31 100644 --- a/contracts/consumer/virtual-staking/src/contract.rs +++ b/contracts/consumer/virtual-staking/src/contract.rs @@ -74,6 +74,7 @@ impl VirtualStakingContract<'_> { pub fn instantiate( &self, ctx: InstantiateCtx, + max_retrieve: u16, tombstoned_unbond_enable: bool, ) -> Result, ContractError> { nonpayable(&ctx.info)?; @@ -81,6 +82,7 @@ impl VirtualStakingContract<'_> { let config = Config { denom, converter: ctx.info.sender, + max_retrieve, tombstoned_unbond_enable, }; self.config.save(ctx.deps.storage, &config)?; @@ -370,6 +372,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn bond( &self, ctx: ExecCtx, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -391,7 +394,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. @@ -400,6 +409,7 @@ impl VirtualStakingApi for VirtualStakingContract<'_> { fn unbond( &self, ctx: ExecCtx, + delegator: String, validator: String, amount: Coin, ) -> Result, Self::Error> { @@ -420,7 +430,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. @@ -485,6 +501,54 @@ 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)?; + + 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)) + } + // FIXME: need to handle custom message types and queries /** * This is called once per epoch to withdraw all rewards and rebalance the bonded tokens. @@ -523,15 +587,39 @@ 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(), 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(); + // Send unstake request to converter contract + let msg = converter_api::sv::ExecMsg::InternalUnstake { + delegator: delegation.delegator, + 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 @@ -700,7 +788,7 @@ mod tests { use cosmwasm_std::{ coins, from_json, testing::{mock_env, mock_info, MockApi, MockQuerier, MockStorage}, - Decimal, + AllDelegationsResponse, Decimal, }; use mesh_bindings::{BondStatusResponse, SlashRatioResponse, TotalDelegationResponse}; @@ -718,7 +806,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() @@ -734,7 +822,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))]) @@ -750,8 +838,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))]) @@ -769,8 +857,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))]) @@ -786,13 +874,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))]) @@ -808,7 +896,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))]) @@ -830,8 +918,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))]) @@ -855,8 +943,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))]) @@ -880,8 +968,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))]) @@ -903,8 +991,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))]) @@ -967,14 +1055,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()); @@ -999,14 +1087,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()); @@ -1046,7 +1134,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))]) @@ -1074,8 +1162,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))]) @@ -1117,14 +1205,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)); @@ -1164,14 +1252,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)); @@ -1279,6 +1367,9 @@ mod tests { let total_delegation = MockTotalDelegation::new(TotalDelegationResponse { delegation: coin(0, "DOES NOT MATTER"), }); + let all_delegations = MockAllDelegations::new(AllDelegationsResponse { + delegations: vec![], + }); let handler = { let bs_copy = bond_status.clone(); @@ -1301,6 +1392,11 @@ mod tests { to_json_binary(&*td_copy.borrow()).unwrap(), )) } + mesh_bindings::VirtualStakeQuery::AllDelegations { .. } => { + cosmwasm_std::SystemResult::Ok(cosmwasm_std::ContractResult::Ok( + to_json_binary(&*all_delegations.borrow()).unwrap(), + )) + } } } }; @@ -1375,6 +1471,18 @@ 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 @@ -1389,8 +1497,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, @@ -1424,6 +1532,7 @@ mod tests { env: mock_env(), info: mock_info("me", &[]), }, + 50, true, ) .unwrap(); @@ -1466,7 +1575,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( @@ -1475,13 +1584,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( @@ -1490,6 +1600,7 @@ mod tests { env: mock_env(), info: mock_info("me", &[]), }, + delegator.to_string(), validator.to_string(), coin(amount, denom), ) @@ -1725,9 +1836,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/contracts/consumer/virtual-staking/src/multitest.rs b/contracts/consumer/virtual-staking/src/multitest.rs index 27bca83b..fa927e09 100644 --- a/contracts/consumer/virtual-staking/src/multitest.rs +++ b/contracts/consumer/virtual-staking/src/multitest.rs @@ -61,6 +61,7 @@ fn setup<'a>(app: &'a App, args: SetupArgs<'a>) -> SetupResponse<'a> { virtual_staking_code.code_id(), true, Some(admin.to_owned()), + 50, ) .with_label("Juno Converter") .with_admin(admin) diff --git a/contracts/consumer/virtual-staking/src/state.rs b/contracts/consumer/virtual-staking/src/state.rs index 63e58802..45a1a65f 100644 --- a/contracts/consumer/virtual-staking/src/state.rs +++ b/contracts/consumer/virtual-staking/src/state.rs @@ -11,4 +11,7 @@ pub struct Config { /// If it enable, tombstoned validators will be unbond automatically pub tombstoned_unbond_enable: bool, + + /// Maximum delegations per query + pub max_retrieve: u16, } diff --git a/contracts/provider/external-staking/src/contract.rs b/contracts/provider/external-staking/src/contract.rs index b953c151..b611a154 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,57 @@ impl ExternalStakingContract<'_> { Ok(()) } + // immediate unstake assets + pub(crate) fn internal_unstake( + &self, + deps: DepsMut, + env: Env, + delegator: String, + validator: String, + amount: Coin, + ) -> Result { + 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.sub(amount, Uint128::zero())?; + + let unbond = PendingUnbond { + amount, + release_at: env.block.time, + }; + 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 +1323,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..c8080f70 100644 --- a/contracts/provider/external-staking/src/ibc.rs +++ b/contracts/provider/external-staking/src/ibc.rs @@ -155,6 +155,17 @@ pub fn ibc_packet_receive( .add_event(evt) .add_messages(msgs) } + ConsumerPacket::InternalUnstake { + delegator, + validator, + normalize_amount: _, + 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) + } ConsumerPacket::Distribute { validator, rewards } => { let evt = contract.distribute_rewards(deps, &validator, rewards)?; let ack = ack_success(&DistributeAck {})?; diff --git a/contracts/provider/external-staking/src/multitest.rs b/contracts/provider/external-staking/src/multitest.rs index ed8298a2..84092f45 100644 --- a/contracts/provider/external-staking/src/multitest.rs +++ b/contracts/provider/external-staking/src/multitest.rs @@ -6,7 +6,7 @@ use cosmwasm_std::{coin, coins, to_json_binary, Decimal, Uint128}; use cw_multi_test::App as MtApp; use mesh_native_staking::contract::sv::mt::CodeId as NativeStakingCodeId; use mesh_native_staking::contract::sv::InstantiateMsg as NativeStakingInstantiateMsg; -use mesh_native_staking_proxy::contract::sv::mt::CodeId as NativeStakingProxyCodeId; +use mesh_native_staking_proxy::mock::sv::mt::CodeId as NativeStakingProxyCodeId; use mesh_vault::mock::sv::mt::{CodeId as VaultCodeId, VaultMockProxy}; use mesh_vault::mock::VaultMock; use mesh_vault::msg::{LocalStakingInfo, StakingInitInfo}; diff --git a/contracts/provider/native-staking-proxy/Cargo.toml b/contracts/provider/native-staking-proxy/Cargo.toml index a8210310..6328e09e 100644 --- a/contracts/provider/native-staking-proxy/Cargo.toml +++ b/contracts/provider/native-staking-proxy/Cargo.toml @@ -21,6 +21,7 @@ mt = ["library", "sylvia/mt"] [dependencies] mesh-apis = { workspace = true } mesh-burn = { workspace = true } +mesh-bindings = { workspace = true } sylvia = { workspace = true } cosmwasm-schema = { workspace = true } diff --git a/contracts/provider/native-staking-proxy/src/contract.rs b/contracts/provider/native-staking-proxy/src/contract.rs index 89aa6240..fcbc52c8 100644 --- a/contracts/provider/native-staking-proxy/src/contract.rs +++ b/contracts/provider/native-staking-proxy/src/contract.rs @@ -7,6 +7,7 @@ use cw2::set_contract_version; use cw_storage_plus::Item; use cw_utils::{must_pay, nonpayable}; +use mesh_bindings::{ProviderCustomMsg, ProviderMsg}; use sylvia::types::{ExecCtx, InstantiateCtx, QueryCtx}; use sylvia::{contract, schemars}; @@ -26,6 +27,7 @@ pub struct NativeStakingProxyContract<'a> { #[cfg_attr(not(feature = "library"), sylvia::entry_points)] #[contract] #[sv::error(ContractError)] +#[sv::custom(msg=ProviderCustomMsg)] impl NativeStakingProxyContract<'_> { pub const fn new() -> Self { Self { @@ -43,7 +45,7 @@ impl NativeStakingProxyContract<'_> { denom: String, owner: String, validator: String, - ) -> Result { + ) -> Result, ContractError> { let config = Config { denom, parent: ctx.info.sender.clone(), @@ -76,7 +78,11 @@ impl NativeStakingProxyContract<'_> { /// Stakes the tokens from `info.funds` to the given validator. /// Can only be called by the parent contract #[sv::msg(exec)] - fn stake(&self, ctx: ExecCtx, validator: String) -> Result { + fn stake( + &self, + ctx: ExecCtx, + validator: String, + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.parent, ctx.info.sender, ContractError::Unauthorized {}); @@ -97,7 +103,7 @@ impl NativeStakingProxyContract<'_> { ctx: ExecCtx, validator: Option, amount: Coin, - ) -> Result { + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.parent, ctx.info.sender, ContractError::Unauthorized {}); @@ -186,7 +192,7 @@ impl NativeStakingProxyContract<'_> { src_validator: String, dst_validator: String, amount: Coin, - ) -> Result { + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); @@ -213,7 +219,7 @@ impl NativeStakingProxyContract<'_> { ctx: ExecCtx, proposal_id: u64, vote: VoteOption, - ) -> Result { + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); @@ -230,7 +236,7 @@ impl NativeStakingProxyContract<'_> { ctx: ExecCtx, proposal_id: u64, vote: Vec, - ) -> Result { + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); @@ -247,7 +253,7 @@ impl NativeStakingProxyContract<'_> { /// send the tokens to the caller. /// NOTE: must make sure not to release unbonded tokens #[sv::msg(exec)] - fn withdraw_rewards(&self, ctx: ExecCtx) -> Result { + fn withdraw_rewards(&self, ctx: ExecCtx) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); @@ -276,7 +282,7 @@ impl NativeStakingProxyContract<'_> { ctx: ExecCtx, validator: String, amount: Coin, - ) -> Result { + ) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); @@ -288,7 +294,11 @@ impl NativeStakingProxyContract<'_> { ContractError::InvalidDenom(amount.denom) ); - let msg = StakingMsg::Undelegate { validator, amount }; + let msg = ProviderMsg::Unstake { + delegator: ctx.info.sender.to_string(), + validator, + amount, + }; Ok(Response::new().add_message(msg)) } @@ -296,7 +306,7 @@ impl NativeStakingProxyContract<'_> { /// This will go back to the parent via `release_proxy_stake`. /// Errors if the proxy doesn't have any liquid tokens #[sv::msg(exec)] - fn release_unbonded(&self, ctx: ExecCtx) -> Result { + fn release_unbonded(&self, ctx: ExecCtx) -> Result, ContractError> { let cfg = self.config.load(ctx.deps.storage)?; ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); diff --git a/contracts/provider/native-staking-proxy/src/lib.rs b/contracts/provider/native-staking-proxy/src/lib.rs index 684e3b37..54c54224 100644 --- a/contracts/provider/native-staking-proxy/src/lib.rs +++ b/contracts/provider/native-staking-proxy/src/lib.rs @@ -1,5 +1,6 @@ pub mod contract; pub mod error; +pub mod mock; pub mod msg; #[cfg(test)] mod multitest; diff --git a/contracts/provider/native-staking-proxy/src/mock.rs b/contracts/provider/native-staking-proxy/src/mock.rs new file mode 100644 index 00000000..9fc5b3d6 --- /dev/null +++ b/contracts/provider/native-staking-proxy/src/mock.rs @@ -0,0 +1,502 @@ +use cosmwasm_std::WasmMsg::Execute; +use cosmwasm_std::{ + coin, ensure_eq, to_json_binary, Coin, DistributionMsg, GovMsg, Response, StakingMsg, + VoteOption, WeightedVoteOption, +}; +use cw2::set_contract_version; +use cw_storage_plus::Item; + +use cw_utils::{must_pay, nonpayable}; +use sylvia::types::{ExecCtx, InstantiateCtx, QueryCtx}; +use sylvia::{contract, schemars}; + +use crate::error::ContractError; +use crate::msg::{ConfigResponse, OwnerMsg}; +use crate::native_staking_callback; +use crate::state::Config; + +pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME"); +pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub struct NativeStakingProxyMock<'a> { + config: Item<'a, Config>, + burned: Item<'a, u128>, +} + +#[contract] +#[sv::error(ContractError)] +impl NativeStakingProxyMock<'_> { + pub const fn new() -> Self { + Self { + config: Item::new("config"), + burned: Item::new("burned"), + } + } + + /// The caller of the instantiation will be the native-staking contract. + /// We stake `funds.info` on the given validator + #[sv::msg(instantiate)] + pub fn instantiate( + &self, + ctx: InstantiateCtx, + denom: String, + owner: String, + validator: String, + ) -> Result { + let config = Config { + denom, + parent: ctx.info.sender.clone(), + owner: ctx.deps.api.addr_validate(&owner)?, + }; + self.config.save(ctx.deps.storage, &config)?; + set_contract_version(ctx.deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + + // Set burned stake to zero + self.burned.save(ctx.deps.storage, &0)?; + + // Stake info.funds on validator + let exec_ctx = ExecCtx { + deps: ctx.deps, + env: ctx.env, + info: ctx.info, + }; + let res = self.stake(exec_ctx, validator)?; + + // Set owner as recipient of future withdrawals + let set_withdrawal = DistributionMsg::SetWithdrawAddress { + address: config.owner.into_string(), + }; + + // Pass owner to caller's reply handler + let owner_msg = to_json_binary(&OwnerMsg { owner })?; + Ok(res.add_message(set_withdrawal).set_data(owner_msg)) + } + + /// Stakes the tokens from `info.funds` to the given validator. + /// Can only be called by the parent contract + #[sv::msg(exec)] + fn stake(&self, ctx: ExecCtx, validator: String) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.parent, ctx.info.sender, ContractError::Unauthorized {}); + + let amount = must_pay(&ctx.info, &cfg.denom)?; + + let amount = coin(amount.u128(), cfg.denom); + let msg = StakingMsg::Delegate { validator, amount }; + + Ok(Response::new().add_message(msg)) + } + + /// Burn `amount` tokens from the given validator, if set. + /// If `validator` is not set, undelegate evenly from all validators the user has stake. + /// Can only be called by the parent contract + #[sv::msg(exec)] + fn burn( + &self, + ctx: ExecCtx, + validator: Option, + amount: Coin, + ) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.parent, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + // Check denom + ensure_eq!( + amount.denom, + cfg.denom, + ContractError::InvalidDenom(amount.denom) + ); + + let delegations = match validator { + Some(validator) => { + match ctx + .deps + .querier + .query_delegation(ctx.env.contract.address.clone(), validator)? + .map(|full_delegation| { + ( + full_delegation.validator, + full_delegation.amount.amount.u128(), + ) + }) { + Some(delegation) => vec![delegation], + None => vec![], + } + } + None => ctx + .deps + .querier + .query_all_delegations(ctx.env.contract.address.clone())? + .iter() + .map(|delegation| { + ( + delegation.validator.clone(), + delegation.amount.amount.u128(), + ) + }) + .collect::>(), + }; + + // Error if no validators + if delegations.is_empty() { + return Err(ContractError::InsufficientDelegations( + ctx.env.contract.address.to_string(), + amount.amount, + )); + } + + let (burned, burns) = mesh_burn::distribute_burn(&delegations, amount.amount.u128()); + + // Bail if we don't have enough delegations + if burned < amount.amount.u128() { + return Err(ContractError::InsufficientDelegations( + ctx.env.contract.address.to_string(), + amount.amount, + )); + } + + // Build undelegate messages + // FIXME: Use an "immediate unbonding" message for undelegation + let mut undelegate_msgs = vec![]; + for (validator, burn_amount) in burns { + let undelegate_msg = StakingMsg::Undelegate { + validator: validator.to_string(), + amount: coin(burn_amount, &cfg.denom), + }; + undelegate_msgs.push(undelegate_msg); + } + + // Accounting trick to avoid burning stake + self.burned.update(ctx.deps.storage, |old| { + Ok::<_, ContractError>(old + amount.amount.u128()) + })?; + + Ok(Response::new().add_messages(undelegate_msgs)) + } + + /// Re-stakes the given amount from the one validator to another on behalf of the calling user. + /// Returns an error if the user doesn't have such stake + #[sv::msg(exec)] + fn restake( + &self, + ctx: ExecCtx, + src_validator: String, + dst_validator: String, + amount: Coin, + ) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + ensure_eq!( + amount.denom, + cfg.denom, + ContractError::InvalidDenom(amount.denom) + ); + + let msg = StakingMsg::Redelegate { + src_validator, + dst_validator, + amount, + }; + Ok(Response::new().add_message(msg)) + } + + /// Vote with the user's stake (over all delegations) + #[sv::msg(exec)] + fn vote( + &self, + ctx: ExecCtx, + proposal_id: u64, + vote: VoteOption, + ) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + let msg = GovMsg::Vote { proposal_id, vote }; + Ok(Response::new().add_message(msg)) + } + + /// Vote with the user's stake (over all delegations) + #[sv::msg(exec)] + fn vote_weighted( + &self, + ctx: ExecCtx, + proposal_id: u64, + vote: Vec, + ) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + let msg = GovMsg::VoteWeighted { + proposal_id, + options: vote, + }; + Ok(Response::new().add_message(msg)) + } + + /// If the caller has any delegations, withdraw all rewards from those delegations and + /// send the tokens to the caller. + /// NOTE: must make sure not to release unbonded tokens + #[sv::msg(exec)] + fn withdraw_rewards(&self, ctx: ExecCtx) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + // Withdraw all delegations to the owner (already set as withdrawal address in instantiate) + let msgs: Vec<_> = ctx + .deps + .querier + .query_all_delegations(ctx.env.contract.address)? + .into_iter() + .map(|delegation| DistributionMsg::WithdrawDelegatorReward { + validator: delegation.validator, + }) + .collect(); + let res = Response::new().add_messages(msgs); + Ok(res) + } + + /// Unstakes the given amount from the given validator on behalf of the calling user. + /// Returns an error if the user doesn't have such stake. + /// After the unbonding period, it will allow the user to claim the tokens (returning to vault) + #[sv::msg(exec)] + fn unstake( + &self, + ctx: ExecCtx, + validator: String, + amount: Coin, + ) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + ensure_eq!( + amount.denom, + cfg.denom, + ContractError::InvalidDenom(amount.denom) + ); + + let msg = StakingMsg::Undelegate { validator, amount }; + Ok(Response::new().add_message(msg)) + } + + /// Releases any tokens that have fully unbonded from a previous unstake. + /// This will go back to the parent via `release_proxy_stake`. + /// Errors if the proxy doesn't have any liquid tokens + #[sv::msg(exec)] + fn release_unbonded(&self, ctx: ExecCtx) -> Result { + let cfg = self.config.load(ctx.deps.storage)?; + ensure_eq!(cfg.owner, ctx.info.sender, ContractError::Unauthorized {}); + + nonpayable(&ctx.info)?; + + // Simply assumes all of our liquid assets are from unbondings + let balance = ctx + .deps + .querier + .query_balance(ctx.env.contract.address, cfg.denom)?; + // But discount burned stake + // FIXME: this is not accurate, as it doesn't take into account the unbonding period + let burned = self.burned.load(ctx.deps.storage)?; + let balance = coin(balance.amount.u128().saturating_sub(burned), &balance.denom); + + // Short circuit if there are no funds to send + if balance.amount.is_zero() { + return Ok(Response::new()); + } + + // Send them to the parent contract via `release_proxy_stake` + let msg = to_json_binary(&native_staking_callback::sv::ExecMsg::ReleaseProxyStake {})?; + + let wasm_msg = Execute { + contract_addr: cfg.parent.to_string(), + msg, + funds: vec![balance], + }; + Ok(Response::new().add_message(wasm_msg)) + } + + #[sv::msg(query)] + fn config(&self, ctx: QueryCtx) -> Result { + Ok(self.config.load(ctx.deps.storage)?) + } +} + +// Some unit tests, due to mt limitations / unsupported msgs +#[cfg(test)] +mod tests { + use super::*; + use cosmwasm_std::DistributionMsg::SetWithdrawAddress; + use cosmwasm_std::GovMsg::{Vote, VoteWeighted}; + use cosmwasm_std::{CosmosMsg, Decimal, DepsMut}; + + use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; + use cosmwasm_std::VoteOption::Yes; + use cw_utils::PaymentError; + + static OSMO: &str = "uosmo"; + static CREATOR: &str = "staking"; // The creator of the proxy contract(s) is the staking contract + static OWNER: &str = "user"; + static VALIDATOR: &str = "validator"; + + fn do_instantiate(deps: DepsMut) -> (ExecCtx, NativeStakingProxyMock) { + let contract = NativeStakingProxyMock::new(); + let mut ctx = InstantiateCtx { + deps, + env: mock_env(), + info: mock_info(CREATOR, &[coin(100, OSMO)]), + }; + contract + .instantiate( + ctx.branch(), + OSMO.to_owned(), + OWNER.to_owned(), + VALIDATOR.to_owned(), + ) + .unwrap(); + let exec_ctx = ExecCtx { + deps: ctx.deps, + info: mock_info(OWNER, &[]), + env: ctx.env, + }; + (exec_ctx, contract) + } + + // Extra checks of instantiate returned messages and data + #[test] + fn instantiating() { + let mut deps = mock_dependencies(); + let contract = NativeStakingProxyMock::new(); + let mut ctx = InstantiateCtx { + deps: deps.as_mut(), + env: mock_env(), + info: mock_info(CREATOR, &[coin(100, OSMO)]), + }; + let res = contract + .instantiate( + ctx.branch(), + OSMO.to_owned(), + OWNER.to_owned(), + VALIDATOR.to_owned(), + ) + .unwrap(); + + // Assert returned messages + assert_eq!( + res.messages[0].msg, + CosmosMsg::Staking(StakingMsg::Delegate { + validator: VALIDATOR.to_owned(), + amount: coin(100, OSMO) + }) + ); + assert_eq!( + res.messages[1].msg, + CosmosMsg::Distribution(SetWithdrawAddress { + address: OWNER.to_owned(), + }) + ); + + // Assert data payload + assert_eq!( + res.data.unwrap(), + to_json_binary(&OwnerMsg { + owner: OWNER.to_owned(), + }) + .unwrap() + ); + } + + #[test] + fn voting() { + let mut deps = mock_dependencies(); + let (mut ctx, contract) = do_instantiate(deps.as_mut()); + + // The owner can vote + let proposal_id = 1; + let vote = Yes; + let res = contract + .vote(ctx.branch(), proposal_id, vote.clone()) + .unwrap(); + assert_eq!(1, res.messages.len()); + // assert it's a governance vote + assert_eq!( + res.messages[0].msg, + cosmwasm_std::CosmosMsg::Gov(Vote { + proposal_id, + vote: vote.clone() + }) + ); + + // But not send funds + ctx.info = mock_info(OWNER, &[coin(1, OSMO)]); + let res = contract.vote(ctx.branch(), proposal_id, vote.clone()); + assert!(matches!( + res.unwrap_err(), + ContractError::Payment(PaymentError::NonPayable {}) + )); + + // Nobody else can vote + ctx.info = mock_info("somebody", &[]); + let res = contract.vote(ctx.branch(), proposal_id, vote.clone()); + assert!(matches!(res.unwrap_err(), ContractError::Unauthorized {})); + + // Not even the creator + ctx.info = mock_info(CREATOR, &[]); + let res = contract.vote(ctx, proposal_id, vote); + assert!(matches!(res.unwrap_err(), ContractError::Unauthorized {})); + } + + #[test] + fn weighted_voting() { + let mut deps = mock_dependencies(); + let (mut ctx, contract) = do_instantiate(deps.as_mut()); + + // The owner can weighted vote + let proposal_id = 2; + let vote = vec![WeightedVoteOption { + option: Yes, + weight: Decimal::percent(50), + }]; + let res = contract + .vote_weighted(ctx.branch(), proposal_id, vote.clone()) + .unwrap(); + assert_eq!(1, res.messages.len()); + // Assert it's a weighted governance vote + assert_eq!( + res.messages[0].msg, + cosmwasm_std::CosmosMsg::Gov(VoteWeighted { + proposal_id, + options: vote.clone() + }) + ); + + // But not send funds + ctx.info = mock_info(OWNER, &[coin(1, OSMO)]); + let res = contract.vote_weighted(ctx.branch(), proposal_id, vote.clone()); + assert!(matches!( + res.unwrap_err(), + ContractError::Payment(PaymentError::NonPayable {}) + )); + + // Nobody else can vote + ctx.info = mock_info("somebody", &[]); + let res = contract.vote_weighted(ctx.branch(), proposal_id, vote.clone()); + assert!(matches!(res.unwrap_err(), ContractError::Unauthorized {})); + + // Not even the creator + ctx.info = mock_info(CREATOR, &[]); + let res = contract.vote_weighted(ctx, proposal_id, vote); + assert!(matches!(res.unwrap_err(), ContractError::Unauthorized {})); + } +} diff --git a/contracts/provider/native-staking-proxy/src/multitest.rs b/contracts/provider/native-staking-proxy/src/multitest.rs index 90baa916..b0e684f4 100644 --- a/contracts/provider/native-staking-proxy/src/multitest.rs +++ b/contracts/provider/native-staking-proxy/src/multitest.rs @@ -10,9 +10,8 @@ use mesh_vault::mock::sv::mt::VaultMockProxy; use mesh_vault::mock::VaultMock; use mesh_vault::msg::LocalStakingInfo; -use crate::contract; -use crate::contract::sv::mt::NativeStakingProxyContractProxy; -use crate::contract::NativeStakingProxyContract; +use crate::mock::sv::mt::NativeStakingProxyMockProxy; +use crate::mock::NativeStakingProxyMock; use crate::msg::ConfigResponse; const OSMO: &str = "uosmo"; @@ -62,7 +61,7 @@ fn setup<'app>( ) -> AnyResult>> { let vault_code = mesh_vault::mock::sv::mt::CodeId::store_code(app); let staking_code = mesh_native_staking::contract::sv::mt::CodeId::store_code(app); - let staking_proxy_code = contract::sv::mt::CodeId::store_code(app); + let staking_proxy_code = crate::mock::sv::mt::CodeId::store_code(app); // Instantiate vault msg let staking_init_info = mesh_vault::msg::StakingInitInfo { @@ -126,7 +125,7 @@ fn instantiation() { setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Check config @@ -170,7 +169,7 @@ fn staking() { let vault = setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Stake some more @@ -216,7 +215,7 @@ fn restaking() { setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Restake 30% to a different validator @@ -255,7 +254,7 @@ fn unstaking() { setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Unstake 50% @@ -310,7 +309,7 @@ fn burning() { setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Burn 10%, from validator @@ -377,7 +376,7 @@ fn burning_multiple_delegations() { setup(&app, owner, user, &validators).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Burn 15%, no validator specified @@ -458,7 +457,7 @@ fn releasing_unbonded() { let vault = setup(&app, owner, user, &[validator]).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Unstake 100% @@ -514,7 +513,7 @@ fn withdrawing_rewards() { let original_user_funds = app.app().wrap().query_balance(user, OSMO).unwrap(); // Access staking proxy instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // Advance time enough for rewards to accrue diff --git a/contracts/provider/native-staking/src/multitest.rs b/contracts/provider/native-staking/src/multitest.rs index fde0c43a..1463a9e8 100644 --- a/contracts/provider/native-staking/src/multitest.rs +++ b/contracts/provider/native-staking/src/multitest.rs @@ -6,10 +6,10 @@ use cw_multi_test::{App as MtApp, StakingInfo}; use sylvia::multitest::{App, Proxy}; use mesh_apis::local_staking_api::sv::mt::LocalStakingApiProxy; -use mesh_native_staking_proxy::contract::sv::mt::{ - CodeId as NativeStakingProxyCodeId, NativeStakingProxyContractProxy, +use mesh_native_staking_proxy::mock::sv::mt::{ + CodeId as NativeStakingProxyCodeId, NativeStakingProxyMockProxy, }; -use mesh_native_staking_proxy::contract::NativeStakingProxyContract; +use mesh_native_staking_proxy::mock::NativeStakingProxyMock; use mesh_sync::ValueRange; use mesh_vault::mock::sv::mt::VaultMockProxy; use mesh_vault::msg::LocalStakingInfo; @@ -291,7 +291,7 @@ fn releasing_proxy_stake() { ); // Access staking instance - let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyContract<'_>> = + let staking_proxy: Proxy<'_, MtApp, NativeStakingProxyMock<'_>> = Proxy::new(Addr::unchecked(proxy_addr), &app); // User bonds some funds to the vault diff --git a/contracts/provider/vault/src/multitest.rs b/contracts/provider/vault/src/multitest.rs index 9e8b897a..fc2f9485 100644 --- a/contracts/provider/vault/src/multitest.rs +++ b/contracts/provider/vault/src/multitest.rs @@ -8,8 +8,8 @@ use mesh_external_staking::state::SlashRatio; use mesh_external_staking::state::Stake; use mesh_native_staking::contract::sv::mt::NativeStakingContractProxy; use mesh_native_staking::contract::NativeStakingContract; -use mesh_native_staking_proxy::contract::sv::mt::NativeStakingProxyContractProxy; -use mesh_native_staking_proxy::contract::NativeStakingProxyContract; +use mesh_native_staking_proxy::mock::sv::mt::NativeStakingProxyMockProxy; +use mesh_native_staking_proxy::mock::NativeStakingProxyMock; use mesh_sync::Tx::InFlightStaking; use mesh_sync::{Tx, ValueRange}; use sylvia::multitest::{App, Proxy}; @@ -126,7 +126,7 @@ fn setup_inner<'app>( let staking_init_info = if local_staking { let native_staking_code = mesh_native_staking::contract::sv::mt::CodeId::store_code(app); let native_staking_proxy_code = - mesh_native_staking_proxy::contract::sv::mt::CodeId::store_code(app); + mesh_native_staking_proxy::mock::sv::mt::CodeId::store_code(app); let native_staking_inst_msg = mesh_native_staking::contract::sv::InstantiateMsg { denom: OSMO.to_string(), @@ -262,7 +262,7 @@ fn proxy_for_user<'a>( local_staking: &Proxy<'_, MtApp, NativeStakingContract<'_>>, user: &str, app: &'a App, -) -> Proxy<'a, MtApp, NativeStakingProxyContract<'a>> { +) -> Proxy<'a, MtApp, NativeStakingProxyMock<'a>> { let proxy_addr = local_staking .proxy_by_owner(user.to_string()) .unwrap() 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..86bdac64 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,17 @@ 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, + /// 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. + normalize_amount: Coin, + inverted_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 39023732..a22ee338 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,18 @@ pub trait VirtualStakingApi { amount: Coin, ) -> Result, Self::Error>; + /// 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, + 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/msg.rs b/packages/bindings/src/msg.rs index 70e94ffe..0e74a3d7 100644 --- a/packages/bindings/src/msg.rs +++ b/packages/bindings/src/msg.rs @@ -30,6 +30,16 @@ 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 }, + /// 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, + delegator: String, + validator: String, + }, + /// Delete all scheduled tasks after zero max cap and unbond all delegations + DeleteAllScheduledTasks {}, } impl VirtualStakeMsg { @@ -54,6 +64,29 @@ 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(), + } + } + + pub fn delete_all_scheduled_tasks() -> VirtualStakeMsg { + VirtualStakeMsg::DeleteAllScheduledTasks {} + } } impl From for CosmosMsg { @@ -87,6 +120,16 @@ pub enum ProviderMsg { /// If these conditions are met, it will instantly unbond /// amount.amount tokens from the vault contract. Unbond { delegator: String, amount: Coin }, + /// Unstake ensures that amount.denom is the native staking denom and + /// the calling contract is the native staking proxy contract. + /// + /// If these conditions are met, it will instantly unstake + /// amount.amount tokens from the native staking proxy contract. + Unstake { + delegator: String, + validator: String, + amount: Coin, + }, } impl ProviderMsg { @@ -111,6 +154,23 @@ impl ProviderMsg { amount: coin, } } + + pub fn unstake( + denom: &str, + delegator: &str, + validator: &str, + amount: impl Into, + ) -> ProviderMsg { + let coin = Coin { + amount: amount.into(), + denom: denom.into(), + }; + ProviderMsg::Unstake { + delegator: delegator.to_string(), + validator: validator.to_string(), + amount: coin, + } + } } impl From for CosmosMsg { diff --git a/packages/bindings/src/query.rs b/packages/bindings/src/query.rs index 2db2bdb7..64d53d13 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, CustomQuery, QuerierWrapper, QueryRequest, StdResult, Uint128}; #[cw_serde] #[derive(QueryResponses)] @@ -25,6 +25,10 @@ pub enum VirtualStakeQuery { /// Returns total delegations of the give validator #[returns(TotalDelegationResponse)] TotalDelegation { contract: String, validator: String }, + + /// 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 @@ -50,6 +54,17 @@ pub struct SlashRatioResponse { pub struct TotalDelegationResponse { pub delegation: Coin, } +#[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 {} @@ -90,4 +105,15 @@ impl<'a> TokenQuerier<'a> { }; self.querier.query(&total_delegations_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 ba0eb0e8..20652cd2 100644 --- a/packages/virtual-staking-mock/src/lib.rs +++ b/packages/virtual-staking-mock/src/lib.rs @@ -2,8 +2,8 @@ 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, + 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}; @@ -135,6 +135,10 @@ impl Module for VirtualStakingModule { Err(anyhow::anyhow!("bonded amount exceeded")) } } + mesh_bindings::VirtualStakeMsg::UpdateDelegation { .. } => Ok(AppResponse::default()), + mesh_bindings::VirtualStakeMsg::DeleteAllScheduledTasks { .. } => { + Ok(AppResponse::default()) + } } } @@ -188,6 +192,11 @@ impl Module for VirtualStakingModule { storage, (Addr::unchecked(&contract), Addr::unchecked(&validator)), )?)?, + mesh_bindings::VirtualStakeQuery::AllDelegations { .. } => { + to_json_binary(&AllDelegationsResponse { + delegations: vec![], + })? + } }; Ok(to_json_binary(&result)?)