Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ICQ for unbonding queue #19

Merged
merged 2 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

172 changes: 123 additions & 49 deletions contracts/puppeteer/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,42 @@
use std::{str::FromStr, vec};

use crate::{
proto::cosmos::base::v1beta1::Coin as ProtoCoin,
proto::liquidstaking::{
distribution::v1beta1::MsgWithdrawDelegatorReward,
staking::v1beta1::{
MsgBeginRedelegate, MsgBeginRedelegateResponse, MsgDelegateResponse,
MsgRedeemTokensforShares, MsgRedeemTokensforSharesResponse, MsgTokenizeShares,
MsgTokenizeSharesResponse, MsgUndelegateResponse,
},
},
};
use cosmos_sdk_proto::cosmos::{
bank::v1beta1::MsgSend,
base::{abci::v1beta1::TxMsgData, v1beta1::Coin},
staking::v1beta1::{MsgDelegate, MsgUndelegate},
};
use cosmwasm_std::{
attr, ensure_eq, entry_point, to_json_binary, Addr, CosmosMsg, Deps, Reply, StdError, SubMsg,
Uint128, WasmMsg,
attr, ensure_eq, entry_point, to_json_binary, Addr, CosmosMsg, Deps, Order, Reply, StdError,
SubMsg, Uint128, WasmMsg,
};
use cosmwasm_std::{Binary, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;
use lido_helpers::answer::response;
use lido_puppeteer_base::{
error::{ContractError, ContractResult},
msg::{
QueryMsg, ReceiverExecuteMsg, ResponseAnswer, ResponseHookErrorMsg, ResponseHookMsg,
ResponseHookSuccessMsg, Transaction, TransferReadyBatchMsg,
},
proto::MsgIBCTransfer,
state::{
PuppeteerBase, ReplyMsg, TxState, TxStateStatus, UnbondingDelegation, ICA_ID, LOCAL_DENOM,
},
};
use lido_staking_base::{
msg::puppeteer::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryExtMsg},
state::puppeteer::{
Config, KVQueryType, BALANCES, DELEGATIONS, SUDO_IBC_TRANSFER_REPLY_ID,
SUDO_KV_BALANCE_REPLY_ID, SUDO_KV_DELEGATIONS_REPLY_ID, SUDO_PAYLOAD_REPLY_ID,
},
state::puppeteer::{Config, KVQueryType, BALANCES, DELEGATIONS},
};
use neutron_sdk::interchain_queries::v045::new_register_delegator_unbonding_delegations_query_msg;
use neutron_sdk::{
bindings::{
msg::{IbcFee, NeutronMsg},
Expand All @@ -33,30 +51,9 @@ use neutron_sdk::{
sudo::msg::{RequestPacket, RequestPacketTimeoutHeight, SudoMsg},
NeutronError, NeutronResult,
};

use lido_puppeteer_base::{
error::{ContractError, ContractResult},
msg::{
QueryMsg, ReceiverExecuteMsg, ResponseAnswer, ResponseHookErrorMsg, ResponseHookMsg,
ResponseHookSuccessMsg, Transaction, TransferReadyBatchMsg,
},
proto::MsgIBCTransfer,
state::{PuppeteerBase, TxState, TxStateStatus, ICA_ID, LOCAL_DENOM},
};

use prost::Message;
use std::{str::FromStr, vec};

use crate::{
proto::cosmos::base::v1beta1::Coin as ProtoCoin,
proto::liquidstaking::{
distribution::v1beta1::MsgWithdrawDelegatorReward,
staking::v1beta1::{
MsgBeginRedelegate, MsgBeginRedelegateResponse, MsgDelegateResponse,
MsgRedeemTokensforShares, MsgRedeemTokensforSharesResponse, MsgTokenizeShares,
MsgTokenizeSharesResponse, MsgUndelegateResponse,
},
},
};
pub type Puppeteer<'a> = PuppeteerBase<'a, Config, KVQueryType>;

const CONTRACT_NAME: &str = concat!("crates.io:lido-neutron-contracts__", env!("CARGO_PKG_NAME"));
Expand Down Expand Up @@ -114,6 +111,14 @@ pub fn query(
QueryExtMsg::Balances {} => {
to_json_binary(&BALANCES.load(deps.storage)?).map_err(ContractError::Std)
}
QueryExtMsg::UnbondingDelegations {} => to_json_binary(
&Puppeteer::default()
.unbonding_delegations
.range(deps.storage, None, None, Order::Ascending)
.map(|res| res.map(|(_key, value)| value))
.collect::<StdResult<Vec<_>>>()?,
)
.map_err(ContractError::Std),
},
_ => Puppeteer::default().query(deps, env, msg),
}
Expand Down Expand Up @@ -178,6 +183,9 @@ pub fn execute(
ExecuteMsg::RegisterDelegatorDelegationsQuery { validators } => {
register_delegations_query(deps, info, validators)
}
ExecuteMsg::RegisterDelegatorUnbondingDelegationsQuery { validators } => {
register_unbonding_delegations_query(deps, info, validators)
}
ExecuteMsg::RegisterBalanceQuery { denom } => register_balance_query(deps, denom),
ExecuteMsg::IBCTransfer { timeout, reply_to } => {
execute_ibc_transfer(deps, env, info, timeout, reply_to)
Expand Down Expand Up @@ -237,7 +245,7 @@ fn execute_ibc_transfer(
recipient: ica_address,
},
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;
Ok(Response::default().add_submessages(vec![submsg]))
}
Expand All @@ -253,7 +261,7 @@ fn register_delegations_query(
// remove old delegation query if any
let kv_queries = puppeteer_base
.kv_queries
.range(deps.storage, None, None, cosmwasm_std::Order::Ascending)
.range(deps.storage, None, None, Order::Ascending)
.collect::<Result<Vec<(u64, KVQueryType)>, _>>()?;
let mut messages = vec![];
for (query_id, query_type) in kv_queries {
Expand All @@ -270,7 +278,7 @@ fn register_delegations_query(
validators,
config.update_period,
)?,
SUDO_KV_DELEGATIONS_REPLY_ID,
ReplyMsg::KvDelegations.to_reply_id(),
);
deps.api.debug(&format!(
"WASMDEBUG: register_delegations_query {msg:?}",
Expand All @@ -279,6 +287,58 @@ fn register_delegations_query(
Ok(Response::new().add_messages(messages).add_submessage(msg))
}

fn register_unbonding_delegations_query(
deps: DepsMut<NeutronQuery>,
info: MessageInfo,
validators: Vec<String>,
) -> ContractResult<Response<NeutronMsg>> {
let puppeteer_base = Puppeteer::default();
let config = puppeteer_base.config.load(deps.storage)?;
ensure_eq!(config.owner, info.sender, ContractError::Unauthorized {});

cosmwasm_std::ensure!(
validators.len() < u16::MAX as usize,
StdError::generic_err("Too many validators provided")
);

// TODO: this code will leave behind many registered ICQs when called again
// we need to call RegisterDelegations and RegisterUnbondingDelegations together
// and update existing queries

let delegator = puppeteer_base.ica.get_address(deps.storage)?;
let msgs = validators
.into_iter()
.enumerate()
.map(|(i, validator)| {
puppeteer_base.unbonding_delegations_reply_id_storage.save(
deps.storage,
i as u16,
&UnbondingDelegation {
validator_address: validator.clone(),
query_id: 0,
unbonding_delegations: vec![],
last_updated_height: 0,
},
)?;

Ok(SubMsg::reply_on_success(
new_register_delegator_unbonding_delegations_query_msg(
config.connection_id.clone(),
delegator.clone(),
vec![validator],
config.update_period,
)?,
ReplyMsg::KvUnbondingDelegations {
validator_index: i as u16,
}
.to_reply_id(),
))
})
.collect::<ContractResult<Vec<_>>>()?;

Ok(Response::new().add_submessages(msgs))
}

fn register_balance_query(
deps: DepsMut<NeutronQuery>,
denom: String,
Expand All @@ -288,7 +348,7 @@ fn register_balance_query(
let ica = puppeteer_base.ica.get_address(deps.storage)?;
let msg = SubMsg::reply_on_success(
new_register_balance_query_msg(config.connection_id, ica, denom, config.update_period)?,
SUDO_KV_BALANCE_REPLY_ID,
ReplyMsg::KvBalance.to_reply_id(),
);
deps.api.debug(&format!(
"WASMDEBUG: register_balance_query {msg:?}",
Expand Down Expand Up @@ -334,7 +394,7 @@ fn execute_delegate(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;

Ok(Response::default().add_submessages(vec![submsg]))
Expand Down Expand Up @@ -391,7 +451,7 @@ fn execute_claim_rewards_and_optionaly_transfer(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;

Ok(Response::default().add_submessages(vec![submsg]))
Expand Down Expand Up @@ -436,7 +496,7 @@ fn execute_undelegate(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;

Ok(Response::default().add_submessages(vec![submsg]))
Expand Down Expand Up @@ -483,7 +543,7 @@ fn execute_redelegate(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;

Ok(Response::default().add_submessages(vec![submsg]))
Expand Down Expand Up @@ -527,7 +587,7 @@ fn execute_tokenize_share(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;

Ok(Response::default().add_submessages(vec![submsg]))
Expand Down Expand Up @@ -576,7 +636,7 @@ fn execute_redeem_share(
},
timeout,
reply_to,
SUDO_PAYLOAD_REPLY_ID,
ReplyMsg::SudoPayload.to_reply_id(),
)?;
Ok(Response::default()
.add_submessages(vec![submsg])
Expand Down Expand Up @@ -653,6 +713,9 @@ pub fn sudo(deps: DepsMut<NeutronQuery>, env: Env, msg: SudoMsg) -> NeutronResul
KVQueryType::Delegations => {
puppeteer_base.sudo_kv_query_result(deps, env, query_id, DELEGATIONS)
}
KVQueryType::UnbondingDelegations => {
puppeteer_base.sudo_unbonding_delegations_kv_query_result(deps, env, query_id)
}
}
}
SudoMsg::OpenAck {
Expand Down Expand Up @@ -913,22 +976,33 @@ fn sudo_timeout(
}

#[entry_point]
pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> StdResult<Response> {
pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
let puppeteer_base: PuppeteerBase<'_, Config, KVQueryType> = Puppeteer::default();
match msg.id {
SUDO_PAYLOAD_REPLY_ID => puppeteer_base.submit_tx_reply(deps, env, msg),
SUDO_IBC_TRANSFER_REPLY_ID => puppeteer_base.submit_ibc_transfer_reply(deps, env, msg),
SUDO_KV_BALANCE_REPLY_ID => {
match ReplyMsg::from_reply_id(msg.id) {
ReplyMsg::SudoPayload => puppeteer_base.submit_tx_reply(deps, msg),
ReplyMsg::IbcTransfer => puppeteer_base.submit_ibc_transfer_reply(deps, msg),
ReplyMsg::KvBalance => {
deps.api
.debug(&format!("WASMDEBUG: KV_BALANCE_REPLY_ID {:?}", msg));
puppeteer_base.register_kv_query_reply(deps, env, msg, KVQueryType::Balance)
puppeteer_base.register_kv_query_reply(deps, msg, KVQueryType::Balance)
}
SUDO_KV_DELEGATIONS_REPLY_ID => {
ReplyMsg::KvDelegations => {
deps.api
.debug(&format!("WASMDEBUG: DELEGATIONS_REPLY_ID {:?}", msg));
puppeteer_base.register_kv_query_reply(deps, env, msg, KVQueryType::Delegations)
puppeteer_base.register_kv_query_reply(deps, msg, KVQueryType::Delegations)
}
ReplyMsg::KvUnbondingDelegations { validator_index } => {
deps.api.debug(&format!(
"WASMDEBUG: UNBONDING_DELEGATIONS_REPLY_ID {:?}",
msg
));
puppeteer_base.register_unbonding_delegations_query_reply(
deps,
msg,
validator_index,
KVQueryType::UnbondingDelegations,
)
}
_ => Err(StdError::generic_err("Unknown reply id")),
}
}

Expand Down
1 change: 0 additions & 1 deletion contracts/strategy/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::contract::instantiate;

use cosmwasm_schema::cw_serde;
// use cosmwasm_schema::cw_serde;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{
to_json_binary, Addr, Attribute, Binary, Decimal, Deps, Empty, Env, Event, Response, StdResult,
Expand Down
20 changes: 2 additions & 18 deletions contracts/validators-stats/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
use bech32::{encode, ToBase32};
use cosmwasm_std::{
entry_point, to_json_binary, Decimal, Deps, Order, Reply, StdError, SubMsg, SubMsgResult,
};
use cosmwasm_std::{entry_point, to_json_binary, Decimal, Deps, Order, Reply, StdError, SubMsg};
use cosmwasm_std::{Binary, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;
use lido_helpers::query_id::get_query_id;
use lido_staking_base::msg::validatorsstats::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use lido_staking_base::state::validatorsstats::{
Config, MissedBlocks, ValidatorMissedBlocksForPeriod, ValidatorState, CONFIG, MISSED_BLOCKS,
SIGNING_INFO_QUERY_ID, SIGNING_INFO_REPLY_ID, STATE_MAP, VALCONS_TO_VALOPER,
VALIDATOR_PROFILE_QUERY_ID, VALIDATOR_PROFILE_REPLY_ID,
};
use neutron_sdk::bindings::msg::MsgRegisterInterchainQueryResponse;
use neutron_sdk::bindings::query::QueryRegisteredQueryResultResponse;
use neutron_sdk::interchain_queries::queries::get_raw_interchain_query_result;
use neutron_sdk::interchain_queries::types::KVReconstruct;
Expand Down Expand Up @@ -437,20 +435,6 @@ fn signing_info_reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Respons
Ok(Response::new())
}

fn get_query_id(msg_result: SubMsgResult) -> StdResult<u64> {
let res: MsgRegisterInterchainQueryResponse = serde_json_wasm::from_slice(
msg_result
.into_result()
.map_err(StdError::generic_err)?
.data
.ok_or_else(|| StdError::generic_err("no result"))?
.as_slice(),
)
.map_err(|e| StdError::generic_err(format!("failed to parse response: {e:?}")))?;

Ok(res.id)
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
deps.api.debug("WASMDEBUG: migrate");
Expand Down
2 changes: 1 addition & 1 deletion integration_tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This repository contains tests for Lido on Cosmos implementation.

### Prerequisites

- node v16.19+
- node v18.12+
- Docker engine
- yarn

Expand Down
3 changes: 2 additions & 1 deletion integration_tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"build-neutron-image": "./dockerfiles/neutron/build.sh",
"build-neutron-query-relayer-image": "./dockerfiles/neutron-query-relayer/build.sh",
"build-images": "./dockerfiles/build-all.sh && docker images",
"lint": "eslint ./src -f compact"
"lint": "eslint ./src -f compact",
"lint:fix": "eslint ./src -f compact --fix"
},
"dependencies": {
"@cosmjs/amino": "^0.32.1",
Expand Down
Loading
Loading