From 23373e753a3d05dac65635a30a6341029c1a8d99 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 13 May 2024 19:38:45 +0300 Subject: [PATCH 01/22] update readme with code ids --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 81f30b4d..9ed0ab0e 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,12 @@ ## Code ids -- auctions manager = `904` -- auction = `903` -- oracle = `906` -- rebalancer = `901` -- services manager = `905` -- account = `902` +- auctions manager = `1234` +- auction = `1239` +- oracle = `1236` +- rebalancer = `1233` +- services manager = `1237` +- account = `1238` ## Owner / Admin From 53dec8f7875caa53b3a27f295528705ca1eb6ee4 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Tue, 14 May 2024 15:43:13 +0300 Subject: [PATCH 02/22] fix failed query parsing bug --- contracts/account/src/contract.rs | 4 ++-- contracts/services_manager/src/contract.rs | 3 +-- packages/valence-macros/src/lib.rs | 2 +- .../valence-package/src/event_indexing.rs | 4 ++-- packages/valence-package/src/helpers.rs | 19 +++++++++---------- tests/rust-tests/src/suite/suite.rs | 2 +- tests/rust-tests/src/suite/suite_auction.rs | 3 ++- .../rust-tests/src/test_service_management.rs | 4 ++-- .../src/tests_rebalancer/test_rebalancing.rs | 1 + 9 files changed, 21 insertions(+), 21 deletions(-) diff --git a/contracts/account/src/contract.rs b/contracts/account/src/contract.rs index f980c950..d2df6c10 100644 --- a/contracts/account/src/contract.rs +++ b/contracts/account/src/contract.rs @@ -202,7 +202,7 @@ pub fn execute( let msgs = msgs_into_sub_msgs(msgs, atomic); let event = ValenceEvent::AccountSendFundsByService { - service_name: info.sender.to_string(), + service_addr: info.sender.to_string(), msgs: msgs.clone(), atomic, }; @@ -220,7 +220,7 @@ pub fn execute( let msgs = msgs_into_sub_msgs(msgs, atomic); let event = ValenceEvent::AccountExecuteByService { - service_name: info.sender.to_string(), + service_addr: info.sender.to_string(), msgs: msgs.clone(), atomic, }; diff --git a/contracts/services_manager/src/contract.rs b/contracts/services_manager/src/contract.rs index e063be6b..83a277a6 100644 --- a/contracts/services_manager/src/contract.rs +++ b/contracts/services_manager/src/contract.rs @@ -223,8 +223,7 @@ mod admin { pub fn query(deps: Deps, _env: Env, msg: ServicesManagerQueryMsg) -> StdResult { match msg { ServicesManagerQueryMsg::IsService { addr } => { - let is_service = - ADDR_TO_SERVICES.may_load(deps.storage, deps.api.addr_validate(&addr)?)?; + let is_service = ADDR_TO_SERVICES.has(deps.storage, deps.api.addr_validate(&addr)?); to_json_binary(&is_service) } ServicesManagerQueryMsg::GetServiceAddr { service } => { diff --git a/packages/valence-macros/src/lib.rs b/packages/valence-macros/src/lib.rs index 9317ebbb..308be9e5 100644 --- a/packages/valence-macros/src/lib.rs +++ b/packages/valence-macros/src/lib.rs @@ -169,7 +169,7 @@ pub fn valence_services_manager_query_msgs( let quote = quote! { enum ServicesManagerQueryMsg { /// Check if address is of a service - #[returns(Option)] + #[returns(bool)] IsService { addr: String, }, diff --git a/packages/valence-package/src/event_indexing.rs b/packages/valence-package/src/event_indexing.rs index 124d50e4..63e7444d 100644 --- a/packages/valence-package/src/event_indexing.rs +++ b/packages/valence-package/src/event_indexing.rs @@ -54,12 +54,12 @@ where service_name: String, }, AccountSendFundsByService { - service_name: String, + service_addr: String, msgs: Vec, atomic: bool, }, AccountExecuteByService { - service_name: String, + service_addr: String, msgs: Vec, atomic: bool, }, diff --git a/packages/valence-package/src/helpers.rs b/packages/valence-package/src/helpers.rs index 4d20be77..acbf1e21 100644 --- a/packages/valence-package/src/helpers.rs +++ b/packages/valence-package/src/helpers.rs @@ -53,16 +53,15 @@ pub fn sender_is_a_service( deps: DepsMut, info: &MessageInfo, manager_addr: String, -) -> Result { - match deps.querier.query_wasm_smart::>( - manager_addr, - &ServicesManagerQueryMsg::IsService { - addr: info.sender.to_string(), - }, - )? { - Some(addr) => Ok(deps.api.addr_validate(&addr)?), - None => Err(ValenceError::UnauthorizedService), - } +) -> Result { + deps.querier + .query_wasm_smart::( + manager_addr, + &ServicesManagerQueryMsg::IsService { + addr: info.sender.to_string(), + }, + ) + .map_err(|e| ValenceError::Std(e)) } /// Verify the sender is the admin of the contract diff --git a/tests/rust-tests/src/suite/suite.rs b/tests/rust-tests/src/suite/suite.rs index 0ab935db..71beb825 100644 --- a/tests/rust-tests/src/suite/suite.rs +++ b/tests/rust-tests/src/suite/suite.rs @@ -595,7 +595,7 @@ impl Suite { ) } - pub fn query_is_service_on_manager(&self, addr: &str) -> Result, StdError> { + pub fn query_is_service_on_manager(&self, addr: &str) -> Result { self.app.wrap().query_wasm_smart( self.manager_addr.clone(), &valence_package::msgs::core_query::ServicesManagerQueryMsg::IsService { diff --git a/tests/rust-tests/src/suite/suite_auction.rs b/tests/rust-tests/src/suite/suite_auction.rs index 27038ac3..f1f1beef 100644 --- a/tests/rust-tests/src/suite/suite_auction.rs +++ b/tests/rust-tests/src/suite/suite_auction.rs @@ -235,7 +235,8 @@ impl Suite { let pair1 = Pair::from((ATOM.to_string(), NTRN.to_string())); let pair2 = Pair::from((NTRN.to_string(), ATOM.to_string())); - self.rebalance(None).unwrap(); + let res = self.rebalance(None).unwrap(); + println!("{:?}", res); // Its fine if we can't update price yet let _ = self.update_price(pair1.clone()); diff --git a/tests/rust-tests/src/test_service_management.rs b/tests/rust-tests/src/test_service_management.rs index 1baf30c7..c0a85f77 100644 --- a/tests/rust-tests/src/test_service_management.rs +++ b/tests/rust-tests/src/test_service_management.rs @@ -443,7 +443,7 @@ fn test_manager_queries() { let is_service = suite .query_is_service_on_manager(suite.rebalancer_addr.as_str()) .unwrap(); - assert!(is_service.is_some()); + assert!(is_service); // suite // .query_service_addr_from_manager(ValenceServices::Test) @@ -498,7 +498,7 @@ fn test_remove_service() { let is_service = suite .query_is_service_on_manager(suite.rebalancer_addr.as_str()) .unwrap(); - assert!(is_service.is_none()); + assert!(!is_service); } #[test] diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index a1d733d7..2d2b6f05 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -57,6 +57,7 @@ fn test_basic_p_controller() { //get new balance balance = suite.get_balance(0, ATOM); + println!("balance: {balance}, expected: {expected_balance}",); // assert that the balance is as expected assert_eq!(balance.amount, expected_balance); } From 23723524f08e8823b9bc661917f717f99d52235c Mon Sep 17 00:00:00 2001 From: Art3mix Date: Tue, 14 May 2024 16:23:13 +0300 Subject: [PATCH 03/22] fix empty msgs sent to the account --- .../services/rebalancer/src/rebalance.rs | 10 +++++--- packages/valence-package/src/helpers.rs | 2 +- tests/rust-tests/src/suite/suite_auction.rs | 3 +-- .../src/tests_rebalancer/test_rebalancing.rs | 24 ++++++++++++++++++- 4 files changed, 32 insertions(+), 7 deletions(-) diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index bba7f0e8..64fd0a23 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -271,7 +271,8 @@ pub fn do_rebalance( // is independent of other trade msg // This means 1 trade might fail while another pass, which means rebalance strategy was not executed 100% this cycle // but this will be corrected on the next rebalance cycle. - let msg = SubMsg::reply_on_error( + let msg = if !msgs.is_empty() { + Some(SubMsg::reply_on_error( WasmMsg::Execute { contract_addr: account.to_string(), msg: to_json_binary( @@ -283,7 +284,10 @@ pub fn do_rebalance( funds: vec![], }, REPLY_DEFAULT_REBALANCE, - ); + )) + } else { + None + }; // We edit config to save data for the next rebalance calculation config.last_rebalance = env.block.time; @@ -294,7 +298,7 @@ pub fn do_rebalance( trades, }; - Ok(RebalanceResponse::new(config, Some(msg), event, false)) + Ok(RebalanceResponse::new(config, msg, event, false)) } /// Set the min amount an auction is willing to accept for a specific token diff --git a/packages/valence-package/src/helpers.rs b/packages/valence-package/src/helpers.rs index acbf1e21..b902f6a0 100644 --- a/packages/valence-package/src/helpers.rs +++ b/packages/valence-package/src/helpers.rs @@ -61,7 +61,7 @@ pub fn sender_is_a_service( addr: info.sender.to_string(), }, ) - .map_err(|e| ValenceError::Std(e)) + .map_err(ValenceError::Std) } /// Verify the sender is the admin of the contract diff --git a/tests/rust-tests/src/suite/suite_auction.rs b/tests/rust-tests/src/suite/suite_auction.rs index f1f1beef..27038ac3 100644 --- a/tests/rust-tests/src/suite/suite_auction.rs +++ b/tests/rust-tests/src/suite/suite_auction.rs @@ -235,8 +235,7 @@ impl Suite { let pair1 = Pair::from((ATOM.to_string(), NTRN.to_string())); let pair2 = Pair::from((NTRN.to_string(), ATOM.to_string())); - let res = self.rebalance(None).unwrap(); - println!("{:?}", res); + self.rebalance(None).unwrap(); // Its fine if we can't update price yet let _ = self.update_price(pair1.clone()); diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index 2d2b6f05..6274b10e 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -1,7 +1,7 @@ use std::{collections::HashSet, str::FromStr}; use auction_package::Pair; -use cosmwasm_std::{Decimal, Uint128}; +use cosmwasm_std::{Decimal, Event, Uint128}; use valence_package::services::rebalancer::PID; @@ -98,3 +98,25 @@ fn test_min_balance_more_than_balance() { let new_balance = suite.get_balance(0, ATOM); assert_eq!(old_balance, new_balance) } + +/// Make sure that we are not trying to send a message to the account when we don't have any trades +#[test] +fn test_no_msg_sent_when_no_trades() { + let mut config = SuiteBuilder::get_default_rebalancer_register_data(); + // Set config to have min_balance for ATOM + let mut targets = SuiteBuilder::get_default_targets(); + targets[0].bps = 9999; + targets[1].bps = 1; + + config.targets = HashSet::from_iter(targets.iter().cloned()); + + let mut suite = SuiteBuilder::default() + .with_rebalancer_data(vec![config]) + .build_default(); + + let res = suite.rebalance(None).unwrap(); + let has_event = res.has_event( + &Event::new("wasm-valence-event").add_attribute("action", "account-send-funds-by-service"), + ); + assert!(!has_event); +} From 3bf0ab01494d545f16f2ee574d8732697e991562 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 23 May 2024 13:32:10 +0300 Subject: [PATCH 04/22] schemas and enw script --- README.md | 12 +- contracts/account/schema/valence-account.json | 2574 +---------------- .../schema/auctions-manager.json | 102 +- .../schema/services-manager.json | 7 +- scripts/migrate.sh | 116 + scripts/upload.sh | 5 +- 6 files changed, 205 insertions(+), 2611 deletions(-) create mode 100755 scripts/migrate.sh diff --git a/README.md b/README.md index 9ed0ab0e..afeebb5a 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,12 @@ ## Code ids -- auctions manager = `1234` -- auction = `1239` -- oracle = `1236` -- rebalancer = `1233` -- services manager = `1237` -- account = `1238` +- auctions manager = `1263` +- auction = `1262` +- oracle = `1261` +- rebalancer = `1260` +- services manager = `1259` +- account = `1258` ## Owner / Admin diff --git a/contracts/account/schema/valence-account.json b/contracts/account/schema/valence-account.json index cdf1cc3d..cce22093 100644 --- a/contracts/account/schema/valence-account.json +++ b/contracts/account/schema/valence-account.json @@ -928,2577 +928,9 @@ "responses": { "get_admin": { "$schema": "http://json-schema.org/draft-07/schema#", - "title": "EventIndex_for_Empty", - "oneOf": [ - { - "type": "object", - "required": [ - "account-creation" - ], - "properties": { - "account-creation": { - "type": "object", - "required": [ - "admin", - "referral" - ], - "properties": { - "admin": { - "description": "The admin address of the account", - "type": "string" - }, - "referral": { - "description": "where the account was created from (native, 3rd-party, etc)", - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-register-service" - ], - "properties": { - "account-register-service": { - "type": "object", - "required": [ - "service_name" - ], - "properties": { - "data": { - "anyOf": [ - { - "$ref": "#/definitions/Binary" - }, - { - "type": "null" - } - ] - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-update-service" - ], - "properties": { - "account-update-service": { - "type": "object", - "required": [ - "data", - "service_name" - ], - "properties": { - "data": { - "$ref": "#/definitions/Binary" - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-deregister-service" - ], - "properties": { - "account-deregister-service": { - "type": "object", - "required": [ - "service_name" - ], - "properties": { - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-pause-service" - ], - "properties": { - "account-pause-service": { - "type": "object", - "required": [ - "service_name" - ], - "properties": { - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-resume-service" - ], - "properties": { - "account-resume-service": { - "type": "object", - "required": [ - "service_name" - ], - "properties": { - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-send-funds-by-service" - ], - "properties": { - "account-send-funds-by-service": { - "type": "object", - "required": [ - "atomic", - "msgs", - "service_name" - ], - "properties": { - "atomic": { - "type": "boolean" - }, - "msgs": { - "type": "array", - "items": { - "$ref": "#/definitions/SubMsg_for_Empty" - } - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-execute-by-service" - ], - "properties": { - "account-execute-by-service": { - "type": "object", - "required": [ - "atomic", - "msgs", - "service_name" - ], - "properties": { - "atomic": { - "type": "boolean" - }, - "msgs": { - "type": "array", - "items": { - "$ref": "#/definitions/SubMsg_for_Empty" - } - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-execute-by-admin" - ], - "properties": { - "account-execute-by-admin": { - "type": "object", - "required": [ - "msgs" - ], - "properties": { - "msgs": { - "type": "array", - "items": { - "$ref": "#/definitions/CosmosMsg_for_Empty" - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-start-admin-change" - ], - "properties": { - "account-start-admin-change": { - "type": "object", - "required": [ - "admin" - ], - "properties": { - "admin": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-cancel-admin-change" - ], - "properties": { - "account-cancel-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "account-approve-admin-change" - ], - "properties": { - "account-approve-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-update-price" - ], - "properties": { - "oracle-update-price": { - "type": "object", - "required": [ - "pair", - "price", - "source" - ], - "properties": { - "pair": { - "$ref": "#/definitions/Pair" - }, - "price": { - "$ref": "#/definitions/Decimal" - }, - "source": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-add-path" - ], - "properties": { - "oracle-add-path": { - "type": "object", - "required": [ - "pair", - "path" - ], - "properties": { - "pair": { - "$ref": "#/definitions/Pair" - }, - "path": { - "type": "array", - "items": { - "$ref": "#/definitions/Empty" - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-update-path" - ], - "properties": { - "oracle-update-path": { - "type": "object", - "required": [ - "pair", - "path" - ], - "properties": { - "pair": { - "$ref": "#/definitions/Pair" - }, - "path": { - "type": "array", - "items": { - "$ref": "#/definitions/Empty" - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-update-config" - ], - "properties": { - "oracle-update-config": { - "type": "object", - "required": [ - "config" - ], - "properties": { - "config": { - "$ref": "#/definitions/Empty" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-start-admin-change" - ], - "properties": { - "oracle-start-admin-change": { - "type": "object", - "required": [ - "admin" - ], - "properties": { - "admin": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-cancel-admin-change" - ], - "properties": { - "oracle-cancel-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "oracle-approve-admin-change" - ], - "properties": { - "oracle-approve-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-update-auction-code-id" - ], - "properties": { - "auction-manager-update-auction-code-id": { - "type": "object", - "required": [ - "code_id" - ], - "properties": { - "code_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-update-oracle" - ], - "properties": { - "auction-manager-update-oracle": { - "type": "object", - "required": [ - "oracle_addr" - ], - "properties": { - "oracle_addr": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-migrate-auction" - ], - "properties": { - "auction-manager-migrate-auction": { - "type": "object", - "required": [ - "code_id", - "msg", - "pair" - ], - "properties": { - "code_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "msg": { - "$ref": "#/definitions/Empty" - }, - "pair": { - "$ref": "#/definitions/Pair" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-update-min-amount" - ], - "properties": { - "auction-manager-update-min-amount": { - "type": "object", - "required": [ - "denom", - "min_amount" - ], - "properties": { - "denom": { - "type": "string" - }, - "min_amount": { - "$ref": "#/definitions/MinAmount" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-start-admin-change" - ], - "properties": { - "auction-manager-start-admin-change": { - "type": "object", - "required": [ - "admin" - ], - "properties": { - "admin": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-cancel-admin-change" - ], - "properties": { - "auction-manager-cancel-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-manager-approve-admin-change" - ], - "properties": { - "auction-manager-approve-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-init" - ], - "properties": { - "auction-init": { - "type": "object", - "required": [ - "config", - "strategy" - ], - "properties": { - "config": { - "$ref": "#/definitions/AuctionConfig" - }, - "strategy": { - "$ref": "#/definitions/AuctionStrategy" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-auction-funds" - ], - "properties": { - "auction-auction-funds": { - "type": "object", - "required": [ - "address", - "amount", - "auction_id" - ], - "properties": { - "address": { - "type": "string" - }, - "amount": { - "$ref": "#/definitions/Uint128" - }, - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-withdraw-funds" - ], - "properties": { - "auction-withdraw-funds": { - "type": "object", - "required": [ - "address", - "amount", - "auction_id" - ], - "properties": { - "address": { - "type": "string" - }, - "amount": { - "$ref": "#/definitions/Uint128" - }, - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-do-bid" - ], - "properties": { - "auction-do-bid": { - "type": "object", - "required": [ - "auction_id", - "bidder", - "bought_amount", - "price", - "refunded_amount" - ], - "properties": { - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "bidder": { - "type": "string" - }, - "bought_amount": { - "description": "How much of token.0 the bidder bought", - "allOf": [ - { - "$ref": "#/definitions/Uint128" - } - ] - }, - "price": { - "$ref": "#/definitions/Decimal" - }, - "refunded_amount": { - "description": "If bidder sent too much and we couldn't \"swap\" all, then we refund him the rest", - "allOf": [ - { - "$ref": "#/definitions/Uint128" - } - ] - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-pause" - ], - "properties": { - "auction-pause": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-resume" - ], - "properties": { - "auction-resume": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-update-strategy" - ], - "properties": { - "auction-update-strategy": { - "type": "object", - "required": [ - "strategy" - ], - "properties": { - "strategy": { - "$ref": "#/definitions/AuctionStrategy" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-update-chain-halt-config" - ], - "properties": { - "auction-update-chain-halt-config": { - "type": "object", - "required": [ - "halt_config" - ], - "properties": { - "halt_config": { - "$ref": "#/definitions/ChainHaltConfig" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-update-price-freshness-strategy" - ], - "properties": { - "auction-update-price-freshness-strategy": { - "type": "object", - "required": [ - "strategy" - ], - "properties": { - "strategy": { - "$ref": "#/definitions/PriceFreshnessStrategy" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-open" - ], - "properties": { - "auction-open": { - "type": "object", - "required": [ - "auction", - "auction_id" - ], - "properties": { - "auction": { - "$ref": "#/definitions/Empty" - }, - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-open-refund" - ], - "properties": { - "auction-open-refund": { - "type": "object", - "required": [ - "auction_id", - "min_amount", - "refund_amount", - "total_users" - ], - "properties": { - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "min_amount": { - "$ref": "#/definitions/Uint128" - }, - "refund_amount": { - "$ref": "#/definitions/Uint128" - }, - "total_users": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "auction-close" - ], - "properties": { - "auction-close": { - "type": "object", - "required": [ - "accounts", - "auction_id", - "is_closed", - "price" - ], - "properties": { - "accounts": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "auction_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "is_closed": { - "type": "boolean" - }, - "price": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-add-service" - ], - "properties": { - "services-manager-add-service": { - "type": "object", - "required": [ - "addr", - "service_name" - ], - "properties": { - "addr": { - "type": "string" - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-update-service" - ], - "properties": { - "services-manager-update-service": { - "type": "object", - "required": [ - "addr", - "service_name" - ], - "properties": { - "addr": { - "type": "string" - }, - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-remove-service" - ], - "properties": { - "services-manager-remove-service": { - "type": "object", - "required": [ - "service_name" - ], - "properties": { - "service_name": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-update-code-id-whitelist" - ], - "properties": { - "services-manager-update-code-id-whitelist": { - "type": "object", - "required": [ - "to_add", - "to_remove" - ], - "properties": { - "to_add": { - "type": "array", - "items": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "to_remove": { - "type": "array", - "items": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-withdraw" - ], - "properties": { - "services-manager-withdraw": { - "type": "object", - "required": [ - "amount" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Coin" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-start-admin-change" - ], - "properties": { - "services-manager-start-admin-change": { - "type": "object", - "required": [ - "admin" - ], - "properties": { - "admin": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-cancel-admin-change" - ], - "properties": { - "services-manager-cancel-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "services-manager-approve-admin-change" - ], - "properties": { - "services-manager-approve-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-register" - ], - "properties": { - "rebalancer-register": { - "type": "object", - "required": [ - "account", - "config" - ], - "properties": { - "account": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/RebalancerConfig" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-deregister" - ], - "properties": { - "rebalancer-deregister": { - "type": "object", - "required": [ - "account" - ], - "properties": { - "account": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update" - ], - "properties": { - "rebalancer-update": { - "type": "object", - "required": [ - "account", - "config" - ], - "properties": { - "account": { - "type": "string" - }, - "config": { - "$ref": "#/definitions/RebalancerConfig" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-pause" - ], - "properties": { - "rebalancer-pause": { - "type": "object", - "required": [ - "account", - "reason" - ], - "properties": { - "account": { - "type": "string" - }, - "reason": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-resume" - ], - "properties": { - "rebalancer-resume": { - "type": "object", - "required": [ - "account" - ], - "properties": { - "account": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-system-status" - ], - "properties": { - "rebalancer-update-system-status": { - "type": "object", - "required": [ - "status" - ], - "properties": { - "status": { - "$ref": "#/definitions/SystemRebalanceStatus" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-denom-whitelist" - ], - "properties": { - "rebalancer-update-denom-whitelist": { - "type": "object", - "required": [ - "denoms" - ], - "properties": { - "denoms": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-base-denom-whitelist" - ], - "properties": { - "rebalancer-update-base-denom-whitelist": { - "type": "object", - "required": [ - "base_denoms" - ], - "properties": { - "base_denoms": { - "type": "array", - "items": { - "$ref": "#/definitions/BaseDenom" - }, - "uniqueItems": true - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-services-manager" - ], - "properties": { - "rebalancer-update-services-manager": { - "type": "object", - "required": [ - "addr" - ], - "properties": { - "addr": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-auctions-manager" - ], - "properties": { - "rebalancer-update-auctions-manager": { - "type": "object", - "required": [ - "addr" - ], - "properties": { - "addr": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-cycle-period" - ], - "properties": { - "rebalancer-update-cycle-period": { - "type": "object", - "required": [ - "period" - ], - "properties": { - "period": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-update-fees" - ], - "properties": { - "rebalancer-update-fees": { - "type": "object", - "required": [ - "fees" - ], - "properties": { - "fees": { - "$ref": "#/definitions/ServiceFeeConfig" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-start-admin-change" - ], - "properties": { - "rebalancer-start-admin-change": { - "type": "object", - "required": [ - "admin" - ], - "properties": { - "admin": { - "type": "string" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-cancel-admin-change" - ], - "properties": { - "rebalancer-cancel-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-approve-admin-change" - ], - "properties": { - "rebalancer-approve-admin-change": { - "type": "object", - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-cycle" - ], - "properties": { - "rebalancer-cycle": { - "type": "object", - "required": [ - "cycled_over", - "limit" - ], - "properties": { - "cycled_over": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "limit": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-account-rebalance" - ], - "properties": { - "rebalancer-account-rebalance": { - "type": "object", - "required": [ - "account", - "total_value", - "trades" - ], - "properties": { - "account": { - "type": "string" - }, - "total_value": { - "$ref": "#/definitions/Decimal" - }, - "trades": { - "type": "array", - "items": { - "$ref": "#/definitions/RebalanceTrade" - } - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "rebalancer-account-rebalance-pause" - ], - "properties": { - "rebalancer-account-rebalance-pause": { - "type": "object", - "required": [ - "account", - "total_value" - ], - "properties": { - "account": { - "type": "string" - }, - "total_value": { - "$ref": "#/definitions/Decimal" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - ], - "definitions": { - "Addr": { - "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", - "type": "string" - }, - "AuctionConfig": { - "type": "object", - "required": [ - "chain_halt_config", - "is_paused", - "pair", - "price_freshness_strategy" - ], - "properties": { - "chain_halt_config": { - "$ref": "#/definitions/ChainHaltConfig" - }, - "is_paused": { - "type": "boolean" - }, - "pair": { - "$ref": "#/definitions/Pair" - }, - "price_freshness_strategy": { - "$ref": "#/definitions/PriceFreshnessStrategy" - } - }, - "additionalProperties": false - }, - "AuctionStrategy": { - "type": "object", - "required": [ - "end_price_perc", - "start_price_perc" - ], - "properties": { - "end_price_perc": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "start_price_perc": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - "BankMsg": { - "description": "The message types of the bank module.\n\nSee https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto", - "oneOf": [ - { - "description": "Sends native tokens from the contract to the given address.\n\nThis is translated to a [MsgSend](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto#L19-L28). `from_address` is automatically filled with the current contract's address.", - "type": "object", - "required": [ - "send" - ], - "properties": { - "send": { - "type": "object", - "required": [ - "amount", - "to_address" - ], - "properties": { - "amount": { - "type": "array", - "items": { - "$ref": "#/definitions/Coin" - } - }, - "to_address": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "This will burn the given coins from the contract's account. There is no Cosmos SDK message that performs this, but it can be done by calling the bank keeper. Important if a contract controls significant token supply that must be retired.", - "type": "object", - "required": [ - "burn" - ], - "properties": { - "burn": { - "type": "object", - "required": [ - "amount" - ], - "properties": { - "amount": { - "type": "array", - "items": { - "$ref": "#/definitions/Coin" - } - } - } - } - }, - "additionalProperties": false - } - ] - }, - "BaseDenom": { - "type": "object", - "required": [ - "denom", - "min_balance_limit" - ], - "properties": { - "denom": { - "type": "string" - }, - "min_balance_limit": { - "$ref": "#/definitions/Uint128" - } - }, - "additionalProperties": false - }, - "Binary": { - "description": "Binary is a wrapper around Vec to add base64 de/serialization with serde. It also adds some helper methods to help encode inline.\n\nThis is only needed as serde-json-{core,wasm} has a horrible encoding for Vec. See also .", - "type": "string" - }, - "ChainHaltConfig": { - "type": "object", - "required": [ - "block_avg", - "cap" - ], - "properties": { - "block_avg": { - "description": "seconds each block is generated", - "allOf": [ - { - "$ref": "#/definitions/Decimal" - } - ] - }, - "cap": { - "description": "Time in seconds of how much of a halt we accept", - "type": "integer", - "format": "uint128", - "minimum": 0.0 - } - }, - "additionalProperties": false - }, - "Coin": { - "type": "object", - "required": [ - "amount", - "denom" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "denom": { - "type": "string" - } - } - }, - "CosmosMsg_for_Empty": { - "oneOf": [ - { - "type": "object", - "required": [ - "bank" - ], - "properties": { - "bank": { - "$ref": "#/definitions/BankMsg" - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "custom" - ], - "properties": { - "custom": { - "$ref": "#/definitions/Empty" - } - }, - "additionalProperties": false - }, - { - "description": "A Stargate message encoded the same way as a protobuf [Any](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto). This is the same structure as messages in `TxBody` from [ADR-020](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-020-protobuf-transaction-encoding.md)", - "type": "object", - "required": [ - "stargate" - ], - "properties": { - "stargate": { - "type": "object", - "required": [ - "type_url", - "value" - ], - "properties": { - "type_url": { - "type": "string" - }, - "value": { - "$ref": "#/definitions/Binary" - } - } - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "ibc" - ], - "properties": { - "ibc": { - "$ref": "#/definitions/IbcMsg" - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "wasm" - ], - "properties": { - "wasm": { - "$ref": "#/definitions/WasmMsg" - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "gov" - ], - "properties": { - "gov": { - "$ref": "#/definitions/GovMsg" - } - }, - "additionalProperties": false - } - ] - }, - "Decimal": { - "description": "A fixed-point decimal value with 18 fractional digits, i.e. Decimal(1_000_000_000_000_000_000) == 1.0\n\nThe greatest possible value that can be represented is 340282366920938463463.374607431768211455 (which is (2^128 - 1) / 10^18)", - "type": "string" - }, - "Empty": { - "description": "An empty struct that serves as a placeholder in different places, such as contracts that don't set a custom message.\n\nIt is designed to be expressable in correct JSON and JSON Schema but contains no meaningful data. Previously we used enums without cases, but those cannot represented as valid JSON Schema (https://github.com/CosmWasm/cosmwasm/issues/451)", - "type": "object" - }, - "GovMsg": { - "description": "This message type allows the contract interact with the [x/gov] module in order to cast votes.\n\n[x/gov]: https://github.com/cosmos/cosmos-sdk/tree/v0.45.12/x/gov\n\n## Examples\n\nCast a simple vote:\n\n``` # use cosmwasm_std::{ # HexBinary, # Storage, Api, Querier, DepsMut, Deps, entry_point, Env, StdError, MessageInfo, # Response, QueryResponse, # }; # type ExecuteMsg = (); use cosmwasm_std::{GovMsg, VoteOption};\n\n#[entry_point] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result { // ... Ok(Response::new().add_message(GovMsg::Vote { proposal_id: 4, vote: VoteOption::Yes, })) } ```\n\nCast a weighted vote:\n\n``` # use cosmwasm_std::{ # HexBinary, # Storage, Api, Querier, DepsMut, Deps, entry_point, Env, StdError, MessageInfo, # Response, QueryResponse, # }; # type ExecuteMsg = (); # #[cfg(feature = \"cosmwasm_1_2\")] use cosmwasm_std::{Decimal, GovMsg, VoteOption, WeightedVoteOption};\n\n# #[cfg(feature = \"cosmwasm_1_2\")] #[entry_point] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result { // ... Ok(Response::new().add_message(GovMsg::VoteWeighted { proposal_id: 4, options: vec![ WeightedVoteOption { option: VoteOption::Yes, weight: Decimal::percent(65), }, WeightedVoteOption { option: VoteOption::Abstain, weight: Decimal::percent(35), }, ], })) } ```", - "oneOf": [ - { - "description": "This maps directly to [MsgVote](https://github.com/cosmos/cosmos-sdk/blob/v0.42.5/proto/cosmos/gov/v1beta1/tx.proto#L46-L56) in the Cosmos SDK with voter set to the contract address.", - "type": "object", - "required": [ - "vote" - ], - "properties": { - "vote": { - "type": "object", - "required": [ - "proposal_id", - "vote" - ], - "properties": { - "proposal_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "vote": { - "description": "The vote option.\n\nThis should be called \"option\" for consistency with Cosmos SDK. Sorry for that. See .", - "allOf": [ - { - "$ref": "#/definitions/VoteOption" - } - ] - } - } - } - }, - "additionalProperties": false - } - ] - }, - "IbcMsg": { - "description": "These are messages in the IBC lifecycle. Only usable by IBC-enabled contracts (contracts that directly speak the IBC protocol via 6 entry points)", - "oneOf": [ - { - "description": "Sends bank tokens owned by the contract to the given address on another chain. The channel must already be established between the ibctransfer module on this chain and a matching module on the remote chain. We cannot select the port_id, this is whatever the local chain has bound the ibctransfer module to.", - "type": "object", - "required": [ - "transfer" - ], - "properties": { - "transfer": { - "type": "object", - "required": [ - "amount", - "channel_id", - "timeout", - "to_address" - ], - "properties": { - "amount": { - "description": "packet data only supports one coin https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/ibc/applications/transfer/v1/transfer.proto#L11-L20", - "allOf": [ - { - "$ref": "#/definitions/Coin" - } - ] - }, - "channel_id": { - "description": "existing channel to send the tokens over", - "type": "string" - }, - "timeout": { - "description": "when packet times out, measured on remote chain", - "allOf": [ - { - "$ref": "#/definitions/IbcTimeout" - } - ] - }, - "to_address": { - "description": "address on the remote chain to receive these tokens", - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Sends an IBC packet with given data over the existing channel. Data should be encoded in a format defined by the channel version, and the module on the other side should know how to parse this.", - "type": "object", - "required": [ - "send_packet" - ], - "properties": { - "send_packet": { - "type": "object", - "required": [ - "channel_id", - "data", - "timeout" - ], - "properties": { - "channel_id": { - "type": "string" - }, - "data": { - "$ref": "#/definitions/Binary" - }, - "timeout": { - "description": "when packet times out, measured on remote chain", - "allOf": [ - { - "$ref": "#/definitions/IbcTimeout" - } - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "This will close an existing channel that is owned by this contract. Port is auto-assigned to the contract's IBC port", - "type": "object", - "required": [ - "close_channel" - ], - "properties": { - "close_channel": { - "type": "object", - "required": [ - "channel_id" - ], - "properties": { - "channel_id": { - "type": "string" - } - } - } - }, - "additionalProperties": false - } - ] - }, - "IbcTimeout": { - "description": "In IBC each package must set at least one type of timeout: the timestamp or the block height. Using this rather complex enum instead of two timeout fields we ensure that at least one timeout is set.", - "type": "object", - "properties": { - "block": { - "anyOf": [ - { - "$ref": "#/definitions/IbcTimeoutBlock" - }, - { - "type": "null" - } - ] - }, - "timestamp": { - "anyOf": [ - { - "$ref": "#/definitions/Timestamp" - }, - { - "type": "null" - } - ] - } - } - }, - "IbcTimeoutBlock": { - "description": "IBCTimeoutHeight Height is a monotonically increasing data type that can be compared against another Height for the purposes of updating and freezing clients. Ordering is (revision_number, timeout_height)", - "type": "object", - "required": [ - "height", - "revision" - ], - "properties": { - "height": { - "description": "block height after which the packet times out. the height within the given revision", - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "revision": { - "description": "the version that the client is currently on (e.g. after resetting the chain this could increment 1 as height drops to 0)", - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - } - }, - "MinAmount": { - "type": "object", - "required": [ - "send", - "start_auction" - ], - "properties": { - "send": { - "description": "Minimum amount that is allowed to send to the auction", - "allOf": [ - { - "$ref": "#/definitions/Uint128" - } - ] - }, - "start_auction": { - "description": "Minimum amount that auction can start from\n\nIf auction amount is below this amount, it will not start the auction and will refund sent funds back to the sender", - "allOf": [ - { - "$ref": "#/definitions/Uint128" - } - ] - } - }, - "additionalProperties": false - }, - "Pair": { - "type": "array", - "items": [ - { - "type": "string" - }, - { - "type": "string" - } - ], - "maxItems": 2, - "minItems": 2 - }, - "ParsedPID": { - "type": "object", - "required": [ - "d", - "i", - "p" - ], - "properties": { - "d": { - "$ref": "#/definitions/Decimal" - }, - "i": { - "$ref": "#/definitions/Decimal" - }, - "p": { - "$ref": "#/definitions/Decimal" - } - }, - "additionalProperties": false - }, - "ParsedTarget": { - "description": "A parsed target struct that contains all info about a single denom target", - "type": "object", - "required": [ - "denom", - "last_i", - "percentage" - ], - "properties": { - "denom": { - "description": "The name of the denom", - "type": "string" - }, - "last_i": { - "description": "The last I value we got from the last rebalance PID calculation.", - "allOf": [ - { - "$ref": "#/definitions/SignedDecimal" - } - ] - }, - "last_input": { - "description": "The input we got from the last rebalance.", - "anyOf": [ - { - "$ref": "#/definitions/Decimal" - }, - { - "type": "null" - } - ] - }, - "min_balance": { - "description": "The minimum balance the account should hold for this denom. Can only be a single one for an account", - "anyOf": [ - { - "$ref": "#/definitions/Uint128" - }, - { - "type": "null" - } - ] - }, - "percentage": { - "description": "The percentage of the total balance we want to have in this denom", - "allOf": [ - { - "$ref": "#/definitions/Decimal" - } - ] - } - }, - "additionalProperties": false - }, - "PriceFreshnessStrategy": { - "description": "Gives us the strategy we should use for when the data is not fresh. \"multiplier\" list is sorted in descending order, so after we check the list, if the data is fresh, the multiplier is 1.\n\nEx: smallest day in the list is \"0.5\" (12 hours), so the multiplier will be 1 if the data is updated in the last 12 hours.", - "type": "object", - "required": [ - "limit", - "multipliers" - ], - "properties": { - "limit": { - "description": "Amount of days price considered no longer fresh", - "allOf": [ - { - "$ref": "#/definitions/Decimal" - } - ] - }, - "multipliers": { - "description": "Multiplier per day of unfresh data (older than day, multipler) for when data is older than 2 days, we add: (\"2\", \"1.5\")", - "type": "array", - "items": { - "type": "array", - "items": [ - { - "$ref": "#/definitions/Decimal" - }, - { - "$ref": "#/definitions/Decimal" - } - ], - "maxItems": 2, - "minItems": 2 - } - } - }, - "additionalProperties": false - }, - "RebalanceTrade": { - "type": "object", - "required": [ - "amount", - "pair" - ], - "properties": { - "amount": { - "$ref": "#/definitions/Uint128" - }, - "pair": { - "$ref": "#/definitions/Pair" - } - }, - "additionalProperties": false - }, - "RebalancerConfig": { - "type": "object", - "required": [ - "base_denom", - "has_min_balance", - "last_rebalance", - "max_limit", - "pid", - "target_override_strategy", - "targets" - ], - "properties": { - "base_denom": { - "description": "The base denom we will be calculating everything based on", - "type": "string" - }, - "has_min_balance": { - "type": "boolean" - }, - "last_rebalance": { - "description": "When the last rebalance happened.", - "allOf": [ - { - "$ref": "#/definitions/Timestamp" - } - ] - }, - "max_limit": { - "description": "Percentage from the total balance that we are allowed to sell in 1 rebalance cycle.", - "allOf": [ - { - "$ref": "#/definitions/Decimal" - } - ] - }, - "pid": { - "description": "The PID parameters the account want to rebalance with", - "allOf": [ - { - "$ref": "#/definitions/ParsedPID" - } - ] - }, - "target_override_strategy": { - "$ref": "#/definitions/TargetOverrideStrategy" - }, - "targets": { - "description": "A vector of targets to rebalance for this account", - "type": "array", - "items": { - "$ref": "#/definitions/ParsedTarget" - } - }, - "trustee": { - "description": "the address that can pause and resume the service", - "anyOf": [ - { - "$ref": "#/definitions/Addr" - }, - { - "type": "null" - } - ] - } - }, - "additionalProperties": false - }, - "ReplyOn": { - "description": "Use this to define when the contract gets a response callback. If you only need it for errors or success you can select just those in order to save gas.", - "oneOf": [ - { - "description": "Always perform a callback after SubMsg is processed", - "type": "string", - "enum": [ - "always" - ] - }, - { - "description": "Only callback if SubMsg returned an error, no callback on success case", - "type": "string", - "enum": [ - "error" - ] - }, - { - "description": "Only callback if SubMsg was successful, no callback on error case", - "type": "string", - "enum": [ - "success" - ] - }, - { - "description": "Never make a callback - this is like the original CosmosMsg semantics", - "type": "string", - "enum": [ - "never" - ] - } - ] - }, - "ServiceFeeConfig": { - "type": "object", - "required": [ - "denom", - "register_fee", - "resume_fee" - ], - "properties": { - "denom": { - "type": "string" - }, - "register_fee": { - "$ref": "#/definitions/Uint128" - }, - "resume_fee": { - "$ref": "#/definitions/Uint128" - } - }, - "additionalProperties": false - }, - "SignedDecimal": { - "description": "A helper struct to have a signed decimal This allows us to keep track if the number is positive or negative\n\nOur usecse / example: In the rebalancer, when we are doing the rebalance calculation, we can either have a positive number or a negetive number. positive number means we need to buy the asset, while negetive menas we need to sell.\n\nThis struct makes it easier for us to do the calculation, and act upon the sign only after the calculation is done, in order to know if we should buy or sell.", - "type": "array", - "items": [ - { - "$ref": "#/definitions/Decimal" - }, - { - "type": "boolean" - } - ], - "maxItems": 2, - "minItems": 2 - }, - "SubMsg_for_Empty": { - "description": "A submessage that will guarantee a `reply` call on success or error, depending on the `reply_on` setting. If you do not need to process the result, use regular messages instead.\n\nNote: On error the submessage execution will revert any partial state changes due to this message, but not revert any state changes in the calling contract. If this is required, it must be done manually in the `reply` entry point.", - "type": "object", - "required": [ - "id", - "msg", - "reply_on" - ], - "properties": { - "gas_limit": { - "description": "Gas limit measured in [Cosmos SDK gas](https://github.com/CosmWasm/cosmwasm/blob/main/docs/GAS.md).", - "type": [ - "integer", - "null" - ], - "format": "uint64", - "minimum": 0.0 - }, - "id": { - "description": "An arbitrary ID chosen by the contract. This is typically used to match `Reply`s in the `reply` entry point to the submessage.", - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "msg": { - "$ref": "#/definitions/CosmosMsg_for_Empty" - }, - "reply_on": { - "$ref": "#/definitions/ReplyOn" - } - } - }, - "SystemRebalanceStatus": { - "oneOf": [ - { - "type": "object", - "required": [ - "not_started" - ], - "properties": { - "not_started": { - "type": "object", - "required": [ - "cycle_start" - ], - "properties": { - "cycle_start": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "processing" - ], - "properties": { - "processing": { - "type": "object", - "required": [ - "cycle_started", - "prices", - "start_from" - ], - "properties": { - "cycle_started": { - "$ref": "#/definitions/Timestamp" - }, - "prices": { - "type": "array", - "items": { - "type": "array", - "items": [ - { - "$ref": "#/definitions/Pair" - }, - { - "$ref": "#/definitions/Decimal" - } - ], - "maxItems": 2, - "minItems": 2 - } - }, - "start_from": { - "$ref": "#/definitions/Addr" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, - { - "type": "object", - "required": [ - "finished" - ], - "properties": { - "finished": { - "type": "object", - "required": [ - "next_cycle" - ], - "properties": { - "next_cycle": { - "$ref": "#/definitions/Timestamp" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - } - ] - }, - "TargetOverrideStrategy": { - "description": "The strategy we will use when overriding targets", - "type": "string", - "enum": [ - "proportional", - "priority" - ] - }, - "Timestamp": { - "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", - "allOf": [ - { - "$ref": "#/definitions/Uint64" - } - ] - }, - "Uint128": { - "description": "A thin wrapper around u128 that is using strings for JSON encoding/decoding, such that the full u128 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u128` to get the value out:\n\n``` # use cosmwasm_std::Uint128; let a = Uint128::from(123u128); assert_eq!(a.u128(), 123);\n\nlet b = Uint128::from(42u64); assert_eq!(b.u128(), 42);\n\nlet c = Uint128::from(70u32); assert_eq!(c.u128(), 70); ```", - "type": "string" - }, - "Uint64": { - "description": "A thin wrapper around u64 that is using strings for JSON encoding/decoding, such that the full u64 range can be used for clients that convert JSON numbers to floats, like JavaScript and jq.\n\n# Examples\n\nUse `from` to create instances of this and `u64` to get the value out:\n\n``` # use cosmwasm_std::Uint64; let a = Uint64::from(42u64); assert_eq!(a.u64(), 42);\n\nlet b = Uint64::from(70u32); assert_eq!(b.u64(), 70); ```", - "type": "string" - }, - "VoteOption": { - "type": "string", - "enum": [ - "yes", - "no", - "abstain", - "no_with_veto" - ] - }, - "WasmMsg": { - "description": "The message types of the wasm module.\n\nSee https://github.com/CosmWasm/wasmd/blob/v0.14.0/x/wasm/internal/types/tx.proto", - "oneOf": [ - { - "description": "Dispatches a call to another contract at a known address (with known ABI).\n\nThis is translated to a [MsgExecuteContract](https://github.com/CosmWasm/wasmd/blob/v0.14.0/x/wasm/internal/types/tx.proto#L68-L78). `sender` is automatically filled with the current contract's address.", - "type": "object", - "required": [ - "execute" - ], - "properties": { - "execute": { - "type": "object", - "required": [ - "contract_addr", - "funds", - "msg" - ], - "properties": { - "contract_addr": { - "type": "string" - }, - "funds": { - "type": "array", - "items": { - "$ref": "#/definitions/Coin" - } - }, - "msg": { - "description": "msg is the json-encoded ExecuteMsg struct (as raw Binary)", - "allOf": [ - { - "$ref": "#/definitions/Binary" - } - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Instantiates a new contracts from previously uploaded Wasm code.\n\nThe contract address is non-predictable. But it is guaranteed that when emitting the same Instantiate message multiple times, multiple instances on different addresses will be generated. See also Instantiate2.\n\nThis is translated to a [MsgInstantiateContract](https://github.com/CosmWasm/wasmd/blob/v0.29.2/proto/cosmwasm/wasm/v1/tx.proto#L53-L71). `sender` is automatically filled with the current contract's address.", - "type": "object", - "required": [ - "instantiate" - ], - "properties": { - "instantiate": { - "type": "object", - "required": [ - "code_id", - "funds", - "label", - "msg" - ], - "properties": { - "admin": { - "type": [ - "string", - "null" - ] - }, - "code_id": { - "type": "integer", - "format": "uint64", - "minimum": 0.0 - }, - "funds": { - "type": "array", - "items": { - "$ref": "#/definitions/Coin" - } - }, - "label": { - "description": "A human-readable label for the contract.\n\nValid values should: - not be empty - not be bigger than 128 bytes (or some chain-specific limit) - not start / end with whitespace", - "type": "string" - }, - "msg": { - "description": "msg is the JSON-encoded InstantiateMsg struct (as raw Binary)", - "allOf": [ - { - "$ref": "#/definitions/Binary" - } - ] - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Migrates a given contracts to use new wasm code. Passes a MigrateMsg to allow us to customize behavior.\n\nOnly the contract admin (as defined in wasmd), if any, is able to make this call.\n\nThis is translated to a [MsgMigrateContract](https://github.com/CosmWasm/wasmd/blob/v0.14.0/x/wasm/internal/types/tx.proto#L86-L96). `sender` is automatically filled with the current contract's address.", - "type": "object", - "required": [ - "migrate" - ], - "properties": { - "migrate": { - "type": "object", - "required": [ - "contract_addr", - "msg", - "new_code_id" - ], - "properties": { - "contract_addr": { - "type": "string" - }, - "msg": { - "description": "msg is the json-encoded MigrateMsg struct that will be passed to the new code", - "allOf": [ - { - "$ref": "#/definitions/Binary" - } - ] - }, - "new_code_id": { - "description": "the code_id of the new logic to place in the given contract", - "type": "integer", - "format": "uint64", - "minimum": 0.0 - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Sets a new admin (for migrate) on the given contract. Fails if this contract is not currently admin of the target contract.", - "type": "object", - "required": [ - "update_admin" - ], - "properties": { - "update_admin": { - "type": "object", - "required": [ - "admin", - "contract_addr" - ], - "properties": { - "admin": { - "type": "string" - }, - "contract_addr": { - "type": "string" - } - } - } - }, - "additionalProperties": false - }, - { - "description": "Clears the admin on the given contract, so no more migration possible. Fails if this contract is not currently admin of the target contract.", - "type": "object", - "required": [ - "clear_admin" - ], - "properties": { - "clear_admin": { - "type": "object", - "required": [ - "contract_addr" - ], - "properties": { - "contract_addr": { - "type": "string" - } - } - } - }, - "additionalProperties": false - } - ] - } - } + "title": "Addr", + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" } } } diff --git a/contracts/auction/auctions_manager/schema/auctions-manager.json b/contracts/auction/auctions_manager/schema/auctions-manager.json index 05197ebd..1edfc80f 100644 --- a/contracts/auction/auctions_manager/schema/auctions-manager.json +++ b/contracts/auction/auctions_manager/schema/auctions-manager.json @@ -8,7 +8,8 @@ "type": "object", "required": [ "auction_code_id", - "min_auction_amount" + "min_auction_amount", + "server_addr" ], "properties": { "auction_code_id": { @@ -31,6 +32,9 @@ "maxItems": 2, "minItems": 2 } + }, + "server_addr": { + "type": "string" } }, "additionalProperties": false, @@ -164,6 +168,18 @@ } }, "additionalProperties": false + }, + { + "type": "object", + "required": [ + "server" + ], + "properties": { + "server": { + "$ref": "#/definitions/ServerMsgs" + } + }, + "additionalProperties": false } ], "definitions": { @@ -210,31 +226,6 @@ }, "additionalProperties": false }, - { - "type": "object", - "required": [ - "open_auction" - ], - "properties": { - "open_auction": { - "type": "object", - "required": [ - "pair", - "params" - ], - "properties": { - "pair": { - "$ref": "#/definitions/Pair" - }, - "params": { - "$ref": "#/definitions/NewAuctionParams" - } - }, - "additionalProperties": false - } - }, - "additionalProperties": false - }, { "type": "object", "required": [ @@ -452,6 +443,27 @@ }, "additionalProperties": false }, + { + "type": "object", + "required": [ + "change_server_addr" + ], + "properties": { + "change_server_addr": { + "type": "object", + "required": [ + "addr" + ], + "properties": { + "addr": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + }, { "type": "object", "required": [ @@ -714,6 +726,35 @@ }, "additionalProperties": false }, + "ServerMsgs": { + "oneOf": [ + { + "type": "object", + "required": [ + "open_auction" + ], + "properties": { + "open_auction": { + "type": "object", + "required": [ + "pair", + "params" + ], + "properties": { + "pair": { + "$ref": "#/definitions/Pair" + }, + "params": { + "$ref": "#/definitions/NewAuctionParams" + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + ] + }, "Timestamp": { "description": "A point in time in nanosecond precision.\n\nThis type can represent times from 1970-01-01T00:00:00Z to 2554-07-21T23:34:33Z.\n\n## Examples\n\n``` # use cosmwasm_std::Timestamp; let ts = Timestamp::from_nanos(1_000_000_202); assert_eq!(ts.nanos(), 1_000_000_202); assert_eq!(ts.seconds(), 1); assert_eq!(ts.subsec_nanos(), 202);\n\nlet ts = ts.plus_seconds(2); assert_eq!(ts.nanos(), 3_000_000_202); assert_eq!(ts.seconds(), 3); assert_eq!(ts.subsec_nanos(), 202); ```", "allOf": [ @@ -739,7 +780,8 @@ { "type": "string", "enum": [ - "get_admin" + "get_admin", + "get_server_addr" ] }, { @@ -1119,6 +1161,12 @@ "type": "string" } } + }, + "get_server_addr": { + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Addr", + "description": "A human readable address.\n\nIn Cosmos, this is typically bech32 encoded. But for multi-chain smart contracts no assumptions should be made other than being UTF-8 encoded and of reasonable length.\n\nThis type represents a validated address. It can be created in the following ways 1. Use `Addr::unchecked(input)` 2. Use `let checked: Addr = deps.api.addr_validate(input)?` 3. Use `let checked: Addr = deps.api.addr_humanize(canonical_addr)?` 4. Deserialize from JSON. This must only be done from JSON that was validated before such as a contract's state. `Addr` must not be used in messages sent by the user because this would result in unvalidated instances.\n\nThis type is immutable. If you really need to mutate it (Really? Are you sure?), create a mutable copy using `let mut mutable = Addr::to_string()` and operate on that `String` instance.", + "type": "string" } } } diff --git a/contracts/services_manager/schema/services-manager.json b/contracts/services_manager/schema/services-manager.json index e32ecd70..cde0462d 100644 --- a/contracts/services_manager/schema/services-manager.json +++ b/contracts/services_manager/schema/services-manager.json @@ -676,11 +676,8 @@ }, "is_service": { "$schema": "http://json-schema.org/draft-07/schema#", - "title": "Nullable_String", - "type": [ - "string", - "null" - ] + "title": "Boolean", + "type": "boolean" } } } diff --git a/scripts/migrate.sh b/scripts/migrate.sh new file mode 100755 index 00000000..e27f6566 --- /dev/null +++ b/scripts/migrate.sh @@ -0,0 +1,116 @@ +#!/bin/bash + +COMMAND=$1 +shift + +BINARY="neutrond" +GAS_PRICES="0.075untrn" +EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 --output json -y" + +# addresses +ADMIN_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" +REBALANCER_ADDR="neutron1qs6mzpmcw3dvg5l8nyywetcj326scszdj7v4pfk55xwshd4prqnqfwc0z2" +ORACLE_ADDR="neutron1pkk88zqjd478x3maws3mv7qugylhsu0sjkejj3k2w02wwhp6fqgsl7m0js" +SERVICES_MANAGER_ADDR="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s69quypupa" +AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" + +# Code ids +REBALANCER_CODE_ID=1260 +ORACLE_CODE_ID=1261 +SERVICES_MANAGER_CODE_ID=1259 +AUCTIONS_MANAGER_CODE_ID=1263 +AUCTION_CODE_ID=1262 +ACCOUNT_CODE_ID=1258 + +# array of pairs we have to migrate +declare -a PAIRS=( + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","untrn"]' + '["untrn","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","untrn"]' + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' + '["untrn","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","untrn"]' + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' + '["untrn","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' +) + +# default migrate message where there is no state change +NO_STATE_MIGRATE_MSG=$( + jq -n \ + '{no_state_change: {}}' +) + +# migrate each contract using a differetn command (arg) +if [[ "$COMMAND" == 'services-manager' ]]; then + + $BINARY tx wasm migrate $SERVICES_MANAGER_ADDR $SERVICES_MANAGER_CODE_ID "$NO_STATE_MIGRATE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + +elif [[ "$COMMAND" == 'rebalancer' ]]; then + + $BINARY tx wasm migrate $REBALANCER_ADDR $REBALANCER_CODE_ID "$NO_STATE_MIGRATE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + +elif [[ "$COMMAND" == 'auctions-manager' ]]; then + + $BINARY tx wasm migrate $AUCTIONS_MANAGER_ADDR $AUCTIONS_MANAGER_CODE_ID "$NO_STATE_MIGRATE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + +elif [[ "$COMMAND" == 'oracle' ]]; then + + $BINARY tx wasm migrate $ORACLE_ADDR $ORACLE_CODE_ID "$NO_STATE_MIGRATE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + +elif [[ "$COMMAND" == 'all-auctions' ]]; then + + for pair in "${PAIRS[@]}"; do + echo "Migrating pair: $pair" + + EXECUTE_MSG=$( + jq -n \ + --argjson pair $pair \ + --argjson code_id $AUCTION_CODE_ID \ + '{admin:{ + migrate_auction: { + pair: $pair, + code_id: $code_id, + msg: {"no_state_change": {}} + } + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + sleep 8 + done + +elif [[ "$COMMAND" == 'code-id-updates' ]]; then + # We need to update our contracts to include the new code ids we are using + + EXECUTE_MSG=$( + jq -n \ + --argjson code_id $AUCTION_CODE_ID \ + '{admin: { + update_auction_id:{ + code_id: $code_id + } + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + sleep 8 + + EXECUTE_MSG=$( + jq -n \ + --argjson code_id $ACCOUNT_CODE_ID \ + '{admin: { + update_code_id_whitelist: { + to_add: [$code_id], + to_remove: [] + } + }}' + ) + $BINARY tx wasm execute $SERVICES_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR $EXECUTE_FLAGS + +else + echo "Unknown command" +fi diff --git a/scripts/upload.sh b/scripts/upload.sh index c649d99c..e97614ee 100755 --- a/scripts/upload.sh +++ b/scripts/upload.sh @@ -16,15 +16,16 @@ elif [[ "$CHAIN" == 'neutron' || "$CHAIN" == 'ntrn' ]]; then BINARY="neutrond" GAS_PRICES="0.075untrn" OWNER_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" + AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" else echo "Unknown chain" fi if [ -z "$INIT_BY" ]; then - ADDRESSES="$OWNER_ADDR" + ADDRESSES="$OWNER_ADDR,$AUCTIONS_MANAGER_ADDR" else - ADDRESSES="$OWNER_ADDR,$INIT_BY" + ADDRESSES="$OWNER_ADDR,$AUCTIONS_MANAGER_ADDR,$INIT_BY" fi EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 --output json --instantiate-anyof-addresses $ADDRESSES -y" From 3f4424e984edc7a1e37153e5c9b585451e71bbd7 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 23 May 2024 13:40:34 +0300 Subject: [PATCH 05/22] fixed not saved targets bug --- .../services/rebalancer/src/rebalance.rs | 6 ++++++ .../src/tests_rebalancer/test_rebalancing.rs | 19 ++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 64fd0a23..d81c8581 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -259,6 +259,12 @@ pub fn do_rebalance( let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?; + // Save targets to our config + config.targets = target_helpers + .iter_mut() + .map(|th| th.target.clone()) + .collect(); + // get minimum amount we can send to each auction set_auction_min_amounts(deps, auction_manager, &mut to_sell, min_amount_limits)?; diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index 6274b10e..f91b1413 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -6,7 +6,7 @@ use cosmwasm_std::{Decimal, Event, Uint128}; use valence_package::services::rebalancer::PID; use crate::suite::{ - suite::{ATOM, NTRN}, + suite::{Suite, ATOM, NTRN}, suite_builder::SuiteBuilder, }; @@ -120,3 +120,20 @@ fn test_no_msg_sent_when_no_trades() { ); assert!(!has_event); } + +#[test] +fn test_targets_saved_after_rebalance() { + let mut suite = Suite::default(); + + let config = suite + .query_rebalancer_config(suite.account_addrs.first().unwrap().clone()) + .unwrap(); + assert!(config.targets[0].last_input.is_none()); + + suite.rebalance(None).unwrap(); + + let config = suite + .query_rebalancer_config(suite.account_addrs.first().unwrap().clone()) + .unwrap(); + assert!(config.targets[0].last_input.is_some()); +} From 8a1e7d60f2bd14f76437e3cf6f91ade7d28d7baa Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 23 May 2024 13:53:36 +0300 Subject: [PATCH 06/22] fix --- tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index 48491553..f54d9634 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -2,7 +2,6 @@ use std::{collections::HashSet, str::FromStr}; use auction_package::Pair; use cosmwasm_std::{Decimal, Event, Uint128}; -use cosmwasm_std::{Decimal, Event, Uint128}; use valence_package::services::rebalancer::PID; From 1d22baac318157827cb1dc828d7dafb8fdf15104 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 23 May 2024 15:27:01 +0300 Subject: [PATCH 07/22] fix --- tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index f54d9634..a88a66ca 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -58,7 +58,7 @@ fn test_basic_p_controller() { //get new balance balance = suite.get_balance(0, ATOM); println!("balance: {balance}, expected: {expected_balance}",); - println!("balance: {balance}, expected: {expected_balance}",); + // assert that the balance is as expected assert_eq!(balance.amount, expected_balance); } From 7497bf98afc959575e532259f6ebe81e72bd58aa Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 23 May 2024 16:36:05 +0300 Subject: [PATCH 08/22] fmt --- tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs index a88a66ca..8235d733 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_rebalancing.rs @@ -58,7 +58,7 @@ fn test_basic_p_controller() { //get new balance balance = suite.get_balance(0, ATOM); println!("balance: {balance}, expected: {expected_balance}",); - + // assert that the balance is as expected assert_eq!(balance.amount, expected_balance); } From b2bde1384fbbd4e4a13f43ce148e83ba9d48cab6 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Fri, 7 Jun 2024 14:45:49 +0300 Subject: [PATCH 09/22] add error event --- Cargo.lock | 20 +++++++++---------- Cargo.toml | 2 +- contracts/services/rebalancer/src/helpers.rs | 2 ++ .../services/rebalancer/src/rebalance.rs | 4 ++++ 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3085cf01..42c63048 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -138,7 +138,7 @@ dependencies = [ [[package]] name = "auction" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "auction-package", @@ -155,7 +155,7 @@ dependencies = [ [[package]] name = "auction-package" -version = "0.1.0" +version = "0.1.4" dependencies = [ "cosmwasm-schema", "cosmwasm-std", @@ -167,7 +167,7 @@ dependencies = [ [[package]] name = "auctions-manager" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "auction", @@ -908,7 +908,7 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "price-oracle" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "astroport 2.9.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1012,7 +1012,7 @@ dependencies = [ [[package]] name = "rebalancer" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "auction", @@ -1165,7 +1165,7 @@ dependencies = [ [[package]] name = "services-manager" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "cosmwasm-schema", @@ -1335,7 +1335,7 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "valence-account" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "cosmwasm-schema", @@ -1351,7 +1351,7 @@ dependencies = [ [[package]] name = "valence-macros" -version = "0.1.0" +version = "0.1.4" dependencies = [ "cosmwasm-schema", "cosmwasm-std", @@ -1362,7 +1362,7 @@ dependencies = [ [[package]] name = "valence-package" -version = "0.1.0" +version = "0.1.4" dependencies = [ "auction-package", "cosmwasm-schema", @@ -1376,7 +1376,7 @@ dependencies = [ [[package]] name = "valence-tests" -version = "0.1.0" +version = "0.1.4" dependencies = [ "anyhow", "astroport 2.9.5 (git+https://github.com/astroport-fi/astroport-core.git?tag=v2.9.5)", diff --git a/Cargo.toml b/Cargo.toml index 997fbe7c..d3faaef5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ [workspace.package] edition = "2021" license = "BSL" -version = "0.1.0" +version = "0.1.4" repository = "https://github.com/timewave-computer/valence-services" rust-version = "1.66" diff --git a/contracts/services/rebalancer/src/helpers.rs b/contracts/services/rebalancer/src/helpers.rs index 207b3abf..0ad23220 100644 --- a/contracts/services/rebalancer/src/helpers.rs +++ b/contracts/services/rebalancer/src/helpers.rs @@ -1,3 +1,4 @@ +use cosmwasm_schema::cw_serde; use cosmwasm_std::{Decimal, SubMsg, Uint128}; use serde::Serialize; use valence_package::{ @@ -29,6 +30,7 @@ pub struct TargetHelper { pub auction_min_amount: Decimal, } +#[cw_serde] pub struct RebalanceResponse { pub config: RebalancerConfig, pub msg: Option, diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index d81c8581..67991e48 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -139,6 +139,10 @@ pub fn execute_system_rebalance( should_pause, }) = rebalance_res else { + account_events.push( + Event::new("rebalancer-error") + .add_attribute("error", rebalance_res.unwrap_err().to_string()), + ); continue; }; From 126edfb7af687f67c2c05cac078aa70462ccdaaa Mon Sep 17 00:00:00 2001 From: Art3mix Date: Fri, 7 Jun 2024 21:41:20 +0300 Subject: [PATCH 10/22] add script to manually auction funds and update code ids --- scripts/auction_funds.sh | 95 ++++++++++++++++++++++++++++++++++++++++ scripts/migrate.sh | 12 ++--- 2 files changed, 101 insertions(+), 6 deletions(-) create mode 100755 scripts/auction_funds.sh diff --git a/scripts/auction_funds.sh b/scripts/auction_funds.sh new file mode 100755 index 00000000..4cdf4c90 --- /dev/null +++ b/scripts/auction_funds.sh @@ -0,0 +1,95 @@ +BINARY="neutrond" +GAS_PRICES="0.075untrn" +EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 --output json -y" + +ADMIN_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" +AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" + +NTRN_AMOUNT="1000001untrn" #1 NTRN +ATOM_AMOUNT="100001ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9" #0.1 ATOM +USDC_AMOUNT="1000001ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81" #1 USDC +NEWT_AMOUNT="13000001factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt" #13k NEWT + +declare -a NTRN_PAIRS=( + '["untrn","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["untrn","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' + '["untrn","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' +) + +declare -a ATOM_PAIRS=( + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","untrn"]' + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' + '["ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' +) + +declare -a USDC_PAIRS=( + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","untrn"]' + '["ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81","factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt"]' +) + +declare -a NEWT_PAIRS=( + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","ibc/C4CFF46FD6DE35CA4CF4CE031E643C8FDC9BA4B99AE598E9B0ED98FE3A2319F9"]' + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","untrn"]' + '["factory/neutron1p8d89wvxyjcnawmgw72klknr3lg9gwwl6ypxda/newt","ibc/B559A80D62249C8AA07A380E2A2BEA6E5CA9A6F079C912C3A9E9B494105E4F81"]' +) + +for pair in "${NTRN_PAIRS[@]}"; do + echo "Auctioning $NTRN_AMOUNT for pair: $pair" + + EXECUTE_MSG=$( + jq -n \ + --argjson pair $pair \ + '{auction_funds:{ + pair: $pair, + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR --amount $NTRN_AMOUNT $EXECUTE_FLAGS + sleep 9 +done + +for pair in "${ATOM_PAIRS[@]}"; do + echo "Auctioning $ATOM_AMOUNT for pair: $pair" + + EXECUTE_MSG=$( + jq -n \ + --argjson pair $pair \ + '{auction_funds:{ + pair: $pair, + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR --amount $ATOM_AMOUNT $EXECUTE_FLAGS + sleep 9 +done + +for pair in "${USDC_PAIRS[@]}"; do + echo "Auctioning $USDC_AMOUNT for pair: $pair" + + EXECUTE_MSG=$( + jq -n \ + --argjson pair $pair \ + '{auction_funds:{ + pair: $pair, + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR --amount $USDC_AMOUNT $EXECUTE_FLAGS + sleep 9 +done + +for pair in "${NEWT_PAIRS[@]}"; do + echo "Auctioning $NEWT_AMOUNT for pair: $pair" + + EXECUTE_MSG=$( + jq -n \ + --argjson pair $pair \ + '{auction_funds:{ + pair: $pair, + }}' + ) + + $BINARY tx wasm execute $AUCTIONS_MANAGER_ADDR "$EXECUTE_MSG" --from $ADMIN_ADDR --amount $NEWT_AMOUNT $EXECUTE_FLAGS + sleep 9 +done diff --git a/scripts/migrate.sh b/scripts/migrate.sh index e27f6566..d2202181 100755 --- a/scripts/migrate.sh +++ b/scripts/migrate.sh @@ -15,12 +15,12 @@ SERVICES_MANAGER_ADDR="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" # Code ids -REBALANCER_CODE_ID=1260 -ORACLE_CODE_ID=1261 -SERVICES_MANAGER_CODE_ID=1259 -AUCTIONS_MANAGER_CODE_ID=1263 -AUCTION_CODE_ID=1262 -ACCOUNT_CODE_ID=1258 +REBALANCER_CODE_ID=1406 +ORACLE_CODE_ID=1407 +SERVICES_MANAGER_CODE_ID=1405 +AUCTIONS_MANAGER_CODE_ID=1404 +AUCTION_CODE_ID=1408 +ACCOUNT_CODE_ID=1403 # array of pairs we have to migrate declare -a PAIRS=( From df2465657b424477203b9daaa678673b14dc1bd7 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Sun, 9 Jun 2024 12:52:45 +0300 Subject: [PATCH 11/22] update optimize --- README.md | 12 ++++++------ devtools/optimize.sh | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index afeebb5a..a727d41c 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,12 @@ ## Code ids -- auctions manager = `1263` -- auction = `1262` -- oracle = `1261` -- rebalancer = `1260` -- services manager = `1259` -- account = `1258` +- auctions manager = `1404` +- auction = `1408` +- oracle = `1407` +- rebalancer = `1406` +- services manager = `1405` +- account = `1403` ## Owner / Admin diff --git a/devtools/optimize.sh b/devtools/optimize.sh index b9860659..9505d790 100755 --- a/devtools/optimize.sh +++ b/devtools/optimize.sh @@ -5,11 +5,11 @@ if [[ $(uname -m) =~ "arm64" ]]; then \ docker run --rm -v "$(pwd)":/code \ --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/optimizer-arm64:0.15.0 + cosmwasm/optimizer-arm64:0.16.0 else docker run --rm -v "$(pwd)":/code \ --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ - cosmwasm/optimizer:0.15.1 + cosmwasm/optimizer:0.16.0 fi From 4199b92a99fa40704389b6fbda54590632a686ea Mon Sep 17 00:00:00 2001 From: Art3mix Date: Sun, 9 Jun 2024 16:36:58 +0300 Subject: [PATCH 12/22] fix --- README.md | 2 +- .../services/rebalancer/src/rebalance.rs | 34 +++++++++++-------- scripts/migrate.sh | 2 +- 3 files changed, 22 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index a727d41c..7ffb2123 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ - auctions manager = `1404` - auction = `1408` - oracle = `1407` -- rebalancer = `1406` +- rebalancer = `1426` - services manager = `1405` - account = `1403` diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 67991e48..264b5a16 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -169,7 +169,7 @@ pub fn execute_system_rebalance( msgs.push(msg); } } - + // We checked if we finished looping over all accounts or not // and set the status based on that let status = if configs_len <= limit { @@ -258,7 +258,8 @@ pub fn do_rebalance( env.block.time.seconds() - config.last_rebalance.seconds(), 0, )?; - (diff / Decimal::from_atomics(cycle_period, 0)?).min(Decimal::new(MAX_PID_DT_VALUE.into())) + (diff.checked_div(Decimal::from_atomics(cycle_period, 0)?))? + .min(Decimal::new(MAX_PID_DT_VALUE.into())) }; let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?; @@ -327,7 +328,7 @@ pub(crate) fn set_auction_min_amounts( { Some(min_amount) => { sell_token.auction_min_amount = - Decimal::from_atomics(min_amount.1, 0)? / sell_token.price; + Decimal::from_atomics(min_amount.1, 0)?.checked_div(sell_token.price)?; } None => { match MIN_AUCTION_AMOUNT.query( @@ -339,8 +340,8 @@ pub(crate) fn set_auction_min_amounts( send: min_send_amount, .. }) => { - sell_token.auction_min_amount = - Decimal::from_atomics(min_send_amount, 0)? / sell_token.price; + sell_token.auction_min_amount = Decimal::from_atomics(min_send_amount, 0)? + .checked_div(sell_token.price)?; min_amount_limits.push((sell_token.target.denom.clone(), min_send_amount)); Ok(()) } @@ -420,7 +421,8 @@ fn get_inputs( // Get current balance of the target, and calculate the value // safe if balance is 0, 0 / price = 0 let current_balance = deps.querier.query_balance(account, target.denom.clone())?; - let balance_value = Decimal::from_atomics(current_balance.amount, 0)? / price; + let balance_value = + Decimal::from_atomics(current_balance.amount, 0)?.checked_div(price)?; total_value += balance_value; targets_helpers.push(TargetHelper { @@ -520,7 +522,7 @@ pub fn verify_targets( let (new_target_perc, mut leftover_perc) = if min_balance_target >= total_value { (Decimal::one(), Decimal::zero()) } else { - let perc = min_balance_target / total_value; + let perc = min_balance_target.checked_div(total_value)?; (perc, Decimal::one() - perc) }; @@ -529,23 +531,23 @@ pub fn verify_targets( let updated_targets = targets .into_iter() - .map(|mut t| { + .map(|mut t| -> Result { // If our target is the min_balance target, we update perc, and return t. if t.target.denom == target.target.denom { t.target.percentage = new_target_perc; - return t; + return Ok(t); }; // If leftover perc is 0, we set the perc as zero for this target if leftover_perc.is_zero() { t.target.percentage = Decimal::zero(); - return t; + return Ok(t); } // Calc new perc based on chosen strategy and new min_balance perc match config.target_override_strategy { TargetOverrideStrategy::Proportional => { - let old_perc = t.target.percentage / old_leftover_perc; + let old_perc = t.target.percentage.checked_div(old_leftover_perc)?; t.target.percentage = old_perc * leftover_perc; } TargetOverrideStrategy::Priority => { @@ -559,9 +561,9 @@ pub fn verify_targets( } new_total_perc += t.target.percentage; - t + Ok(t) }) - .collect(); + .collect::, ContractError>>()?; // If the new percentage is smaller then 0.9999 or higher then 1, we have something wrong in calculation if new_total_perc > Decimal::one() @@ -697,6 +699,10 @@ fn generate_trades_msgs( // If our sell results in less then min_balance, we sell the difference to hit min_balance let diff = token_sell.balance_amount - min_balance; + if diff.is_zero() { + return; + } + // Unwrap should be safe here because diff should be a small number // and directly related to users balance token_sell.value_to_trade = @@ -709,7 +715,7 @@ fn generate_trades_msgs( token_sell.value_to_trade = Decimal::zero(); return; } - + // If we hit our max sell limit, we only sell the limit left // otherwise, we keep track of how much we already sold if token_sell.value_to_trade > max_sell { diff --git a/scripts/migrate.sh b/scripts/migrate.sh index e27f6566..93e6a620 100755 --- a/scripts/migrate.sh +++ b/scripts/migrate.sh @@ -15,7 +15,7 @@ SERVICES_MANAGER_ADDR="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" # Code ids -REBALANCER_CODE_ID=1260 +REBALANCER_CODE_ID=1426 ORACLE_CODE_ID=1261 SERVICES_MANAGER_CODE_ID=1259 AUCTIONS_MANAGER_CODE_ID=1263 From f2637657419274064f166525cafc6f009c7cef52 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 10 Jun 2024 10:04:22 +0300 Subject: [PATCH 13/22] bump std version --- Cargo.lock | 22 +++++++++++----------- Cargo.toml | 4 ++-- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3085cf01..71a25b70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -293,9 +293,9 @@ checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" [[package]] name = "cosmwasm-crypto" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6b4c3f9c4616d6413d4b5fc4c270a4cc32a374b9be08671e80e1a019f805d8f" +checksum = "dd50718a2b6830ce9eb5d465de5a018a12e71729d66b70807ce97e6dd14f931d" dependencies = [ "digest 0.10.7", "ecdsa", @@ -307,18 +307,18 @@ dependencies = [ [[package]] name = "cosmwasm-derive" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c586ced10c3b00e809ee664a895025a024f60d65d34fe4c09daed4a4db68a3f3" +checksum = "242e98e7a231c122e08f300d9db3262d1007b51758a8732cd6210b3e9faa4f3a" dependencies = [ "syn 1.0.109", ] [[package]] name = "cosmwasm-schema" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8467874827d384c131955ff6f4d47d02e72a956a08eb3c0ff24f8c903a5517b4" +checksum = "7879036156092ad1c22fe0d7316efc5a5eceec2bc3906462a2560215f2a2f929" dependencies = [ "cosmwasm-schema-derive", "schemars", @@ -329,9 +329,9 @@ dependencies = [ [[package]] name = "cosmwasm-schema-derive" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6db85d98ac80922aef465e564d5b21fa9cfac5058cb62df7f116c3682337393" +checksum = "0bb57855fbfc83327f8445ae0d413b1a05ac0d68c396ab4d122b2abd7bb82cb6" dependencies = [ "proc-macro2", "quote", @@ -340,9 +340,9 @@ dependencies = [ [[package]] name = "cosmwasm-std" -version = "1.5.4" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712fe58f39d55c812f7b2c84e097cdede3a39d520f89b6dc3153837e31741927" +checksum = "78c1556156fdf892a55cced6115968b961eaaadd6f724a2c2cb7d1e168e32dd3" dependencies = [ "base64", "bech32 0.9.1", @@ -950,7 +950,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19de2de2a00075bf566bee3bd4db014b11587e84184d3f7a791bc17f1a8e9e48" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.12.1", "proc-macro2", "quote", "syn 2.0.60", diff --git a/Cargo.toml b/Cargo.toml index 997fbe7c..83574f60 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,8 +51,8 @@ valence-macros = { path = "packages/valence-macros" } valence-package = { path = "packages/valence-package" } auction-package = { path = "packages/auction-package" } -cosmwasm-schema = "1.5.4" -cosmwasm-std = { version = "1.5.4", features = ["ibc3"] } +cosmwasm-schema = "1.5.5" +cosmwasm-std = { version = "1.5.5", features = ["ibc3"] } cw-storage-plus = "1.2.0" cw-utils = "1.0.3" cw2 = "1.1.2" From e142fb52f67fe6e26d7bb2dd3b6fc82264fb8f41 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 10 Jun 2024 13:28:12 +0300 Subject: [PATCH 14/22] only update target with last_i and last_input --- .../services/rebalancer/src/rebalance.rs | 23 ++++++++++++------- .../src/tests_rebalancer/test_limits.rs | 10 ++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 264b5a16..56cea03e 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -169,7 +169,7 @@ pub fn execute_system_rebalance( msgs.push(msg); } } - + // We checked if we finished looping over all accounts or not // and set the status based on that let status = if configs_len <= limit { @@ -264,11 +264,18 @@ pub fn do_rebalance( let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?; - // Save targets to our config - config.targets = target_helpers - .iter_mut() - .map(|th| th.target.clone()) - .collect(); + // Update targets in config only the last data we need for the next rebalance calculation + config.targets.iter_mut().for_each(|target| { + let Some(target_helper) = target_helpers + .iter() + .find(|th| th.target.denom == target.denom) + else { + return; + }; + + target.last_i = target_helper.target.last_i; + target.last_input = target_helper.target.last_input; + }); // get minimum amount we can send to each auction set_auction_min_amounts(deps, auction_manager, &mut to_sell, min_amount_limits)?; @@ -702,7 +709,7 @@ fn generate_trades_msgs( if diff.is_zero() { return; } - + // Unwrap should be safe here because diff should be a small number // and directly related to users balance token_sell.value_to_trade = @@ -715,7 +722,7 @@ fn generate_trades_msgs( token_sell.value_to_trade = Decimal::zero(); return; } - + // If we hit our max sell limit, we only sell the limit left // otherwise, we keep track of how much we already sold if token_sell.value_to_trade > max_sell { diff --git a/tests/rust-tests/src/tests_rebalancer/test_limits.rs b/tests/rust-tests/src/tests_rebalancer/test_limits.rs index 7ccf8cd6..16dc6424 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_limits.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_limits.rs @@ -72,6 +72,8 @@ fn test_min_balance() { .with_rebalancer_data(vec![config]) .build_default(); + let old_config = suite.query_rebalancer_config(suite.get_account_addr(0)).unwrap(); + for _ in 0..10 { suite.resolve_cycle(); } @@ -80,6 +82,14 @@ fn test_min_balance() { // Balance should be equal or greater then our set minimum assert!(balance_atom.amount < Uint128::new(1000)); assert!(balance_atom.amount >= Uint128::new(950)); + + let new_config = suite.query_rebalancer_config(suite.get_account_addr(0)).unwrap(); + + new_config.targets.iter().for_each(|new_target| { + let target = old_config.targets.iter().find(|t| t.denom == new_target.denom).unwrap(); + + assert!(new_target.percentage == target.percentage); + }); } #[test] From 306697ad24176c1768f0c9d0be6319a1dd234748 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Thu, 13 Jun 2024 17:50:05 +0300 Subject: [PATCH 15/22] added live data debugging --- Cargo.lock | 288 ++++++++++++++++-- Cargo.toml | 2 +- README.md | 4 +- .../auction/price_oracle/src/contract.rs | 11 +- contracts/auction/price_oracle/src/msg.rs | 6 +- .../services/rebalancer/src/rebalance.rs | 2 +- contracts/services/rebalancer/src/state.rs | 2 +- scripts/migrate.sh | 6 +- tests/rust-tests/Cargo.toml | 1 + tests/rust-tests/src/lib.rs | 3 + .../rust-tests/src/live_debugging/helpers.rs | 5 + tests/rust-tests/src/live_debugging/mod.rs | 20 ++ .../src/live_debugging/suite_builder.rs | 74 +++++ .../src/live_debugging/suite_helpers.rs | 288 ++++++++++++++++++ .../live_debugging/test_specific_config.rs | 155 ++++++++++ tests/rust-tests/src/live_debugging/types.rs | 114 +++++++ .../src/suite/instantiates/oracle.rs | 15 + .../src/suite/instantiates/rebalancer.rs | 6 + tests/rust-tests/src/suite/suite_auction.rs | 12 +- tests/rust-tests/src/tests_rebalancer/mod.rs | 2 + .../src/tests_rebalancer/test_limits.rs | 14 +- .../src/tests_rebalancer/tests_unit.rs | 34 ++- 22 files changed, 1005 insertions(+), 59 deletions(-) create mode 100644 tests/rust-tests/src/live_debugging/helpers.rs create mode 100644 tests/rust-tests/src/live_debugging/mod.rs create mode 100644 tests/rust-tests/src/live_debugging/suite_builder.rs create mode 100644 tests/rust-tests/src/live_debugging/suite_helpers.rs create mode 100644 tests/rust-tests/src/live_debugging/test_specific_config.rs create mode 100644 tests/rust-tests/src/live_debugging/types.rs diff --git a/Cargo.lock b/Cargo.lock index 4954da64..fc8fdf02 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,11 +13,26 @@ dependencies = [ "version_check", ] +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "anyhow" -version = "1.0.82" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "astroport" @@ -250,6 +265,12 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56953345e39537a3e18bdaeba4cb0c58a78c1f61f361dc0fa7c5c7340ae87c5f" +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + [[package]] name = "bytemuck" version = "1.14.0" @@ -268,12 +289,32 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +[[package]] +name = "cc" +version = "1.0.99" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" + [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-targets 0.52.5", +] + [[package]] name = "colored" version = "2.0.4" @@ -291,6 +332,12 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" +[[package]] +name = "core-foundation-sys" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" + [[package]] name = "cosmwasm-crypto" version = "1.5.5" @@ -422,9 +469,9 @@ dependencies = [ [[package]] name = "cw-multi-test" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ffa9e3bae206540c084198e5be5aea2ecb1f2597f79dc09263b528ea0604788" +checksum = "91fc33b1d65c102d72f46548c64dca423c337e528d6747d0c595316aa65f887b" dependencies = [ "anyhow", "bech32 0.11.0", @@ -432,7 +479,7 @@ dependencies = [ "cw-storage-plus 1.2.0", "cw-utils 1.0.3", "derivative", - "itertools 0.12.1", + "itertools 0.13.0", "prost", "schemars", "serde", @@ -793,6 +840,29 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "iana-time-zone" +version = "0.1.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "integer-sqrt" version = "0.1.5" @@ -831,12 +901,30 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +dependencies = [ + "wasm-bindgen", +] + [[package]] name = "k256" version = "0.13.1" @@ -869,6 +957,12 @@ version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + [[package]] name = "num-traits" version = "0.2.18" @@ -935,9 +1029,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.12.4" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0f5d036824e4761737860779c906171497f6d55681139d8312388f8fe398922" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" dependencies = [ "bytes", "prost-derive", @@ -945,9 +1039,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.12.4" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19de2de2a00075bf566bee3bd4db014b11587e84184d3f7a791bc17f1a8e9e48" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" dependencies = [ "anyhow", "itertools 0.12.1", @@ -1070,9 +1164,9 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "schemars" -version = "0.8.16" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29" +checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" dependencies = [ "dyn-clone", "schemars_derive", @@ -1082,14 +1176,14 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.8.16" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967" +checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 1.0.109", + "syn 2.0.60", ] [[package]] @@ -1114,9 +1208,9 @@ checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" [[package]] name = "serde" -version = "1.0.198" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" dependencies = [ "serde_derive", ] @@ -1132,9 +1226,9 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.198" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" dependencies = [ "proc-macro2", "quote", @@ -1143,13 +1237,13 @@ dependencies = [ [[package]] name = "serde_derive_internals" -version = "0.26.0" +version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.60", ] [[package]] @@ -1291,18 +1385,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.59" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.59" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", @@ -1389,6 +1483,7 @@ dependencies = [ "auction", "auction-package", "auctions-manager", + "chrono", "colored", "cosmwasm-schema", "cosmwasm-std", @@ -1418,13 +1513,76 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.60", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.60", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.5", +] + [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", ] [[package]] @@ -1433,13 +1591,29 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] [[package]] @@ -1448,42 +1622,90 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + [[package]] name = "zeroize" version = "1.6.0" diff --git a/Cargo.toml b/Cargo.toml index caeea4bb..878237ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,5 +61,5 @@ thiserror = "1.0.31" schemars = "0.8.10" # dev-dependencies -cw-multi-test = "1.1.0" +cw-multi-test = "1.2.0" anyhow = { version = "1.0.51" } diff --git a/README.md b/README.md index 7ffb2123..34ba0895 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ - auctions manager = `1404` - auction = `1408` -- oracle = `1407` -- rebalancer = `1426` +- oracle = `1446` +- rebalancer = `1442` - services manager = `1405` - account = `1403` diff --git a/contracts/auction/price_oracle/src/contract.rs b/contracts/auction/price_oracle/src/contract.rs index cd36a705..1307a54b 100644 --- a/contracts/auction/price_oracle/src/contract.rs +++ b/contracts/auction/price_oracle/src/contract.rs @@ -7,7 +7,9 @@ use auction_package::states::{ADMIN, PAIRS, PRICES, TWAP_PRICES}; use auction_package::Price; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; -use cosmwasm_std::{to_json_binary, Binary, Decimal, Deps, DepsMut, Env, MessageInfo, Response}; +use cosmwasm_std::{ + to_json_binary, Binary, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdResult, +}; use cw2::set_contract_version; use valence_package::event_indexing::{ValenceEvent, ValenceGenericEvent}; @@ -311,6 +313,13 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result { + let prices = PRICES + .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) + .collect::>>()?; + + Ok(to_json_binary(&prices)?) + } QueryMsg::GetConfig => { let config = CONFIG.load(deps.storage)?; Ok(to_json_binary(&config)?) diff --git a/contracts/auction/price_oracle/src/msg.rs b/contracts/auction/price_oracle/src/msg.rs index 4e15ef2c..2c1550ab 100644 --- a/contracts/auction/price_oracle/src/msg.rs +++ b/contracts/auction/price_oracle/src/msg.rs @@ -1,4 +1,4 @@ -use auction_package::{helpers::GetPriceResponse, Pair}; +use auction_package::{Pair, Price}; use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::{Addr, Decimal}; use cw_utils::Expiration; @@ -46,8 +46,10 @@ pub enum ExecuteMsg { #[derive(QueryResponses)] pub enum QueryMsg { /// Get the minimum amount users can auction - #[returns(GetPriceResponse)] + #[returns(Price)] GetPrice { pair: Pair }, + #[returns(Vec<(Pair, Price)>)] + GetAllPrices, #[returns(Config)] GetConfig, #[returns(Addr)] diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 56cea03e..54102047 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -518,7 +518,7 @@ pub fn verify_targets( // Safe to unwrap here, because we only enter the function is there is a min_balance target // and we error out if we don't find the target above. let min_balance = Decimal::from_atomics(target.target.min_balance.unwrap(), 0)?; - let min_balance_target = min_balance * target.price; + let min_balance_target = min_balance / target.price; let real_target = total_value * target.target.percentage; // if the target is below the minimum balance target diff --git a/contracts/services/rebalancer/src/state.rs b/contracts/services/rebalancer/src/state.rs index 4a685391..16164ec3 100644 --- a/contracts/services/rebalancer/src/state.rs +++ b/contracts/services/rebalancer/src/state.rs @@ -11,7 +11,7 @@ pub(crate) const DENOM_WHITELIST: Item> = Item::new("token_white /// Base denom whitelist pub(crate) const BASE_DENOM_WHITELIST: Item> = Item::new("base_token_whitelist"); /// Storage to keep all configs of all registered accounts -pub(crate) const CONFIGS: Map = Map::new("configs"); +pub const CONFIGS: Map = Map::new("configs"); /// Storage to keep the current status of the system rebalance pub(crate) const SYSTEM_REBALANCE_STATUS: Item = Item::new("system_rebalance_status"); diff --git a/scripts/migrate.sh b/scripts/migrate.sh index 93e6a620..665ec9b8 100755 --- a/scripts/migrate.sh +++ b/scripts/migrate.sh @@ -10,13 +10,13 @@ EXECUTE_FLAGS="--gas-prices $GAS_PRICES --gas auto --gas-adjustment 1.4 --output # addresses ADMIN_ADDR="neutron1phx0sz708k3t6xdnyc98hgkyhra4tp44et5s68" REBALANCER_ADDR="neutron1qs6mzpmcw3dvg5l8nyywetcj326scszdj7v4pfk55xwshd4prqnqfwc0z2" -ORACLE_ADDR="neutron1pkk88zqjd478x3maws3mv7qugylhsu0sjkejj3k2w02wwhp6fqgsl7m0js" +ORACLE_ADDR="neutron1s8uqyh0mmh8g66s2dectf56c08y6fvusp39undp8kf4v678ededsy6tstf" SERVICES_MANAGER_ADDR="neutron1gantvpnat0la8kkkzrnj48d5d8wxdjllh5r2w4r2hcrpwy00s69quypupa" AUCTIONS_MANAGER_ADDR="neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz" # Code ids -REBALANCER_CODE_ID=1426 -ORACLE_CODE_ID=1261 +REBALANCER_CODE_ID=1442 +ORACLE_CODE_ID=1446 SERVICES_MANAGER_CODE_ID=1259 AUCTIONS_MANAGER_CODE_ID=1263 AUCTION_CODE_ID=1262 diff --git a/tests/rust-tests/Cargo.toml b/tests/rust-tests/Cargo.toml index 030c923e..677855b5 100644 --- a/tests/rust-tests/Cargo.toml +++ b/tests/rust-tests/Cargo.toml @@ -30,6 +30,7 @@ auction-package = { workspace = true } auctions-manager = { workspace = true } auction = { workspace = true } price-oracle = { workspace = true } +chrono = "0.4.38" # Astro astroport = { git = "https://github.com/astroport-fi/astroport-core.git", tag = "v2.9.5" } diff --git a/tests/rust-tests/src/lib.rs b/tests/rust-tests/src/lib.rs index 3c0f634f..b316c728 100644 --- a/tests/rust-tests/src/lib.rs +++ b/tests/rust-tests/src/lib.rs @@ -11,3 +11,6 @@ mod tests_auctions; #[cfg(test)] mod tests_account; + +#[cfg(test)] +mod live_debugging; diff --git a/tests/rust-tests/src/live_debugging/helpers.rs b/tests/rust-tests/src/live_debugging/helpers.rs new file mode 100644 index 00000000..cb85ea19 --- /dev/null +++ b/tests/rust-tests/src/live_debugging/helpers.rs @@ -0,0 +1,5 @@ +pub fn concat(namespace: &[u8], key: &[u8]) -> Vec { + let mut k = namespace.to_vec(); + k.extend_from_slice(key); + k +} \ No newline at end of file diff --git a/tests/rust-tests/src/live_debugging/mod.rs b/tests/rust-tests/src/live_debugging/mod.rs new file mode 100644 index 00000000..42365ad6 --- /dev/null +++ b/tests/rust-tests/src/live_debugging/mod.rs @@ -0,0 +1,20 @@ +#[cfg(test)] +mod test_specific_config; + +#[cfg(test)] +mod types; + +#[cfg(test)] +mod suite_builder; + +#[cfg(test)] +mod suite_helpers; + +#[cfg(test)] +mod helpers; + +const NAMESPACE_WASM: &[u8] = b"wasm"; + +const REBALANCER_ADDR: &str = "neutron1qs6mzpmcw3dvg5l8nyywetcj326scszdj7v4pfk55xwshd4prqnqfwc0z2"; +const ORACLE_ADDR: &str = "neutron1s8uqyh0mmh8g66s2dectf56c08y6fvusp39undp8kf4v678ededsy6tstf"; +const AUCTIONS_MANAGER_ADDR: &str = "neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz"; diff --git a/tests/rust-tests/src/live_debugging/suite_builder.rs b/tests/rust-tests/src/live_debugging/suite_builder.rs new file mode 100644 index 00000000..a9c71b69 --- /dev/null +++ b/tests/rust-tests/src/live_debugging/suite_builder.rs @@ -0,0 +1,74 @@ +use std::{collections::HashMap, hash::Hash}; + +use auction_package::Pair; +use cosmwasm_std::{BlockInfo, Coin}; +use valence_package::services::rebalancer::RebalancerConfig; + +use crate::suite::{suite::Suite, suite_builder::SuiteBuilder}; + +use super::types::{Prices, WhitelistDenoms}; + +impl SuiteBuilder { + pub fn build_live_debug( + block_info: BlockInfo, + whitelists: WhitelistDenoms, + prices: Prices, + balances: Vec, + config: RebalancerConfig, + ) -> Suite { + let mut builder = SuiteBuilder::default(); + + // Get init app + let mut app = builder.set_app(); + + // Update our mocked block info with the correct info from mainnet + app.update_block(|b| *b = block_info.clone()); + + // Upload contracts + builder.upload_contracts(&mut app); + + // init oracle, auctions manager and auctions + let (auctions_manager_addr, oracle_addr, auction_addrs) = + builder.ld_init_auctions(&mut app, whitelists.denom_whitelist.clone(), prices); + + // init services manager + let manager_addr = builder.init_manager(&mut app); + + // init and register rebalancer + let rebalancer_addr = builder.ld_init_rebalancer( + &mut app, + auctions_manager_addr.clone(), + manager_addr.clone(), + whitelists.clone(), + ); + + let account_addr = builder.ld_init_accounts( + &mut app, + whitelists.denom_whitelist.clone(), + manager_addr.clone(), + rebalancer_addr.clone(), + balances, + config, + ); + + Suite { + app, + admin: builder.admin, + owner: builder.owner, + trustee: builder.trustee, + mm: builder.mm, + auctions_manager_addr, + oracle_addr, + manager_addr, + rebalancer_addr, + account_addrs: vec![account_addr], + auction_addrs, + pair: Pair::from(( + whitelists.denom_whitelist[0].clone(), + whitelists.denom_whitelist[1].clone(), + )), + account_code_id: builder.account_code_id, + astro_pools: HashMap::new(), + } + } +} diff --git a/tests/rust-tests/src/live_debugging/suite_helpers.rs b/tests/rust-tests/src/live_debugging/suite_helpers.rs new file mode 100644 index 00000000..722ab576 --- /dev/null +++ b/tests/rust-tests/src/live_debugging/suite_helpers.rs @@ -0,0 +1,288 @@ +use std::{ + collections::{hash_map::RandomState, BTreeMap, HashMap, HashSet}, + process::Command, +}; + +use auction_package::{states::{MinAmount, PRICES}, AuctionStrategy, Pair}; +use cosmwasm_std::{from_json, to_json_binary, to_json_vec, Addr, Coin, Storage}; +use cw_multi_test::{App, Executor}; +use cw_storage_plus::Prefixer; +use rebalancer::state::CONFIGS; +use valence_package::services::{ + rebalancer::{RebalancerConfig, Target}, + ValenceServices, +}; + +use crate::suite::{ + instantiates::{ + AccountInstantiate, AuctionInstantiate, AuctionsManagerInstantiate, OracleInstantiate, + RebalancerInstantiate, + }, + suite_builder::SuiteBuilder, +}; + +use super::{ + helpers::concat, + types::{MinLimitsRes, Prices, WhitelistDenoms}, + AUCTIONS_MANAGER_ADDR, NAMESPACE_WASM, REBALANCER_ADDR, +}; + +impl SuiteBuilder { + pub fn ld_init_auctions( + &mut self, + app: &mut App, + whitelist_denoms: Vec, + prices: Prices, + ) -> (Addr, Addr, HashMap<(String, String), Addr>) { + // init auction manager + let auctions_manager_addr = self.init_auctions_manager( + app, + AuctionsManagerInstantiate::new(self.auction_code_id, self.mm.to_string()).into(), + ); + + // init the oracle + let price_oracle_addr = self.init_oracle( + app, + OracleInstantiate::default(auctions_manager_addr.clone()) + .change_seconds_allow_manual_change(1) + .into(), + ); + + // add oracle addr to the manager + app.execute_contract( + self.admin.clone(), + auctions_manager_addr.clone(), + &auctions_manager::msg::ExecuteMsg::Admin(Box::new( + auctions_manager::msg::AdminMsgs::UpdateOracle { + oracle_addr: price_oracle_addr.to_string(), + }, + )), + &[], + ) + .unwrap(); + + // get min limits of each denom + let min_limits = SuiteBuilder::get_auction_min_amounts(&whitelist_denoms); + + let mut auctions_addrs: HashMap<(String, String), Addr> = HashMap::new(); + // create auction for each whitelisted pair of denoms + whitelist_denoms.iter().for_each(|denom_1| { + whitelist_denoms.iter().for_each(|denom_2| { + if denom_1 == denom_2 { + return; + } + + let pair = Pair::from((denom_1.clone(), denom_2.clone())); + let auction_init_msg = AuctionInstantiate::new( + pair.clone(), + AuctionStrategy { + start_price_perc: 5000, + end_price_perc: 5000, + }, + ); + let min_amount = min_limits.get(denom_1).unwrap().clone(); + app.execute_contract( + self.admin.clone(), + auctions_manager_addr.clone(), + &auctions_manager::msg::ExecuteMsg::Admin(Box::new( + auctions_manager::msg::AdminMsgs::NewAuction { + msg: auction_init_msg.into(), + label: "auction".to_string(), + min_amount: Some(min_amount), + }, + )), + &[], + ) + .unwrap(); + + // Get the addr of the auction + let auction_addr: Addr = app + .wrap() + .query_wasm_smart( + auctions_manager_addr.clone(), + &auction_package::msgs::AuctionsManagerQueryMsg::GetPairAddr { + pair: pair.clone(), + }, + ) + .unwrap(); + + auctions_addrs.insert(pair.clone().into(), auction_addr); + + // Update the price of the auction + let price = prices.iter().find(|(p, _)| p == &pair).unwrap().1.clone(); + let mut oracle_storage = app.contract_storage_mut(&price_oracle_addr); + PRICES.save(oracle_storage.as_mut(), pair, &price).unwrap(); + // app.execute_contract( + // self.admin.clone(), + // price_oracle_addr.clone(), + // &price_oracle::msg::ExecuteMsg::ManualPriceUpdate { + // pair: pair.clone(), + // price: price.price, + // }, + // &[], + // ) + // .unwrap(); + }) + }); + + (auctions_manager_addr, price_oracle_addr, auctions_addrs) + } + + pub fn ld_init_rebalancer( + &mut self, + app: &mut App, + auctions_manager_addr: Addr, + manager_addr: Addr, + whitelists: WhitelistDenoms, + ) -> Addr { + // init rebalancer + let rebalancer_instantiate_msg: rebalancer::msg::InstantiateMsg = + RebalancerInstantiate::default(manager_addr.as_str(), auctions_manager_addr.as_str()) + .change_denom_whitelist(whitelists.denom_whitelist) + .change_base_denom_whitelist(whitelists.base_denom_whitelist) + .into(); + + let rebalancer_addr = app + .instantiate_contract( + self.rebalancer_code_id, + self.admin.clone(), + &rebalancer_instantiate_msg, + &[], + "rebalancer", + Some(self.admin.to_string()), + ) + .unwrap(); + + app.execute_contract( + self.admin.clone(), + manager_addr, + &valence_package::msgs::core_execute::ServicesManagerExecuteMsg::Admin( + valence_package::msgs::core_execute::ServicesManagerAdminMsg::AddService { + name: ValenceServices::Rebalancer, + addr: rebalancer_addr.to_string(), + }, + ), + &[], + ) + .unwrap(); + + rebalancer_addr + } + + /// Init an account and register it to the rebalancer + pub fn ld_init_accounts( + &mut self, + app: &mut App, + whitelist_denoms: Vec, + manager_addr: Addr, + rebalancer_addr: Addr, + account_balances: Vec, + account_config: RebalancerConfig, + ) -> Addr { + let account_init_msg: valence_account::msg::InstantiateMsg = + AccountInstantiate::new(manager_addr.as_str()).into(); + + // Instantiate the account contract + let account_addr = app + .instantiate_contract( + self.account_code_id, + self.owner.clone(), + &account_init_msg, + &[], + format!("account"), + Some(self.owner.to_string()), + ) + .unwrap(); + + // update account balance based on mainnet balance + app.init_modules(|router, _api, storage| { + router + .bank + .init_balance(storage, &account_addr, account_balances) + .unwrap(); + }); + + // register to the rebalancer with some mock data first + let targets: HashSet = HashSet::from_iter( + [ + Target { + denom: whitelist_denoms[0].to_string(), + bps: 7500, + min_balance: None, + }, + Target { + denom: whitelist_denoms[1].to_string(), + bps: 2500, + min_balance: None, + }, + ] + .into_iter(), + ); + + let mut mock_rebalancer_data = SuiteBuilder::get_default_rebalancer_register_data(); + mock_rebalancer_data.base_denom = "untrn".to_string(); + mock_rebalancer_data.targets = targets; + + app.execute_contract( + self.owner.clone(), + account_addr.clone(), + &valence_package::msgs::core_execute::AccountBaseExecuteMsg::RegisterToService { + service_name: ValenceServices::Rebalancer, + data: Some(to_json_binary(&mock_rebalancer_data).unwrap()), + }, + &[], + ) + .unwrap(); + + // Update config in place with mainnet config + let mut contract_storage = app.contract_storage_mut(&rebalancer_addr); + CONFIGS + .save( + contract_storage.as_mut(), + account_addr.clone(), + &account_config, + ) + .unwrap(); + + // app.init_modules(|_router, _api, storage| { + // let namespace = concat(NAMESPACE_WASM, b"contract_data/"); + // let namespace = concat(&namespace, REBALANCER_ADDR.as_bytes()); + // let storage_key = concat(&namespace, b"configs"); + // let account_key = concat(&storage_key, account_addr.as_bytes()); + // storage.set(&account_key, &to_json_vec(&account_config).unwrap()); + // }); + + account_addr + } +} + +impl SuiteBuilder { + pub fn get_auction_min_amounts(denoms: &Vec) -> BTreeMap { + BTreeMap::from_iter(denoms.iter().map(|denom| { + let q_string = format!("{{\"get_min_limit\": {{\"denom\": \"{}\"}}}}", denom); + let min_limits_output = Command::new("neutrond") + .args([ + "q", + "wasm", + "contract-state", + "smart", + AUCTIONS_MANAGER_ADDR, + ]) + .arg(q_string) + .args(["--node", "https://neutron-tw-rpc.polkachu.com:443"]) + .args(["--chain-id", "neutron-1"]) + .args(["--output", "json"]) + .output() + .expect("Failed getting auctions min limits"); + + ( + denom.clone(), + from_json::( + String::from_utf8_lossy(&min_limits_output.stdout).to_string(), + ) + .unwrap() + .data, + ) + })) + } +} diff --git a/tests/rust-tests/src/live_debugging/test_specific_config.rs b/tests/rust-tests/src/live_debugging/test_specific_config.rs new file mode 100644 index 00000000..fb9de5d1 --- /dev/null +++ b/tests/rust-tests/src/live_debugging/test_specific_config.rs @@ -0,0 +1,155 @@ +// Test a specific config of an account with the state of the system +// This test should give us an idea of how the next rebalance would work, and give us +// a manualy way to check what trades the rebalancer is calculating +// best for debuging live data without without for a cycle + +// The state of the system includes: +// - the specific account config +// - the account balances +// - all prices from oracle + +// To get the data we want, we want to do those queries: +// - account config = neutrond query wasm contract-state smart neutron1qs6mzpmcw3dvg5l8nyywetcj326scszdj7v4pfk55xwshd4prqnqfwc0z2 '{"get_config": {"addr": "[ACCOUNT_ADDR]"}}' +// - account balances = neutrond q bank balances [ACCOUNT_ADDR] +// - prices = neutrond query wasm contract-state smart neutron1s8uqyh0mmh8g66s2dectf56c08y6fvusp39undp8kf4v678ededsy6tstf '"get_all_prices"' + +// NOTE - we are taking the data live, so make sure to have the neutrond set up correctly with the correct version +use std::process::Command; + +use cosmwasm_std::{from_json, BlockInfo}; +use valence_package::services::rebalancer::RebalancerConfig; + +use crate::{ + live_debugging::{ + types::{AllPricesRes, Block, BlockRes, ConfigRes, Prices, WhitelistDenoms, WhitelistDenomsRes}, + ORACLE_ADDR, REBALANCER_ADDR, + }, + suite::suite_builder::SuiteBuilder, +}; + +use super::types::Balances; + +const ACCOUNT_ADDR: &str = "neutron1wcv0c8ktmjgtj0a5dt6zdteer2nsyawqtnm5kxt7su5063dudz8qasjl97"; +const HEIGHT: &str = ""; + +#[ignore = "Debugging"] +#[test] +fn live_debugging() { + // If we have specifig height, query by that height + let mut height_arg = vec![]; + let mut block_height = vec![]; + if !HEIGHT.is_empty() { + height_arg = vec!["--height", HEIGHT]; + block_height = vec![HEIGHT]; + } + + // query mainnet for the balances of the account + let block_output = Command::new("neutrond") + .args(["q", "block"]) + // .args(["--node", ""]) + .args(["--chain-id", "neutron-1"]) + .args(block_height.to_vec()) + .output() + .expect("Failed getting balances"); + + let block_info: BlockInfo = + from_json::(String::from_utf8_lossy(&block_output.stdout).to_string()) + .unwrap() + .block.header.into(); + + // query mainnet for the balances of the account + let balances_output = Command::new("neutrond") + .args(["q", "bank", "balances", ACCOUNT_ADDR]) + // .args(["--node", ""]) + .args(["--chain-id", "neutron-1"]) + .args(["--output", "json"]) + .args(height_arg.to_vec()) + .output() + .expect("Failed getting balances"); + + let balances: Balances = + from_json(String::from_utf8_lossy(&balances_output.stdout).to_string()).unwrap(); + + // Query mainnet for the config of the account + let q_string = format!("{{\"get_config\": {{\"addr\": \"{}\"}}}}", ACCOUNT_ADDR); + let config_output = Command::new("neutrond") + .args(["q", "wasm", "contract-state", "smart", REBALANCER_ADDR]) + .arg(q_string) + // .args(["--node", ""]) + .args(["--chain-id", "neutron-1"]) + .args(["--output", "json"]) + .args(height_arg.to_vec()) + .output() + .expect("Failed getting config"); + + let config: RebalancerConfig = + from_json::(String::from_utf8_lossy(&config_output.stdout).to_string()) + .unwrap() + .data; + + // Query mainnet for all prices from oracle + let q_string: &str = "\"get_all_prices\""; + let prices_output = Command::new("neutrond") + .args(["q", "wasm", "contract-state", "smart", ORACLE_ADDR]) + .arg(q_string) + // .args(["--node", ]) + .args(["--chain-id", "neutron-1"]) + .args(["--output", "json"]) + .args(height_arg.to_vec()) + .output() + .expect("Failed getting all prices"); + + let prices: Prices = + from_json::(String::from_utf8_lossy(&prices_output.stdout).to_string()) + .unwrap() + .data; + + // Query mainnet for the whitelist denoms + let q_string: &str = "\"get_white_lists\""; + let whitelists_output = Command::new("neutrond") + .args(["q", "wasm", "contract-state", "smart", REBALANCER_ADDR]) + .arg(q_string) + // .args(["--node", ""]) + .args(["--chain-id", "neutron-1"]) + .args(["--output", "json"]) + .args(height_arg.to_vec()) + .output() + .expect("Failed getting whitelists"); + + let whitelists: WhitelistDenoms = from_json::( + String::from_utf8_lossy(&whitelists_output.stdout).to_string(), + ) + .unwrap() + .data; + + // print the data we get from mainnet for debugging + // println!("1. Balances: {:?}", balances); + // println!("2. Config: {:?}", config); + // println!("3. Prices: {:?}", prices); + // println!("whitelists: {:?}", whitelists); + + //---------------------- + // Start mocking + //---------------------- + + let mut suite = SuiteBuilder::build_live_debug( + block_info, + whitelists, + prices.clone(), + balances.balances, + config.clone(), + ); + let account_config = suite + .query_rebalancer_config(suite.account_addrs[0].clone()) + .unwrap(); + let all_prices = suite.query_oracle_all_prices(); + + // make sure the config is set in our mock rebalancer + assert_eq!(account_config, config); + // make sure prices in oracle are matching mainnet prices + assert_eq!(all_prices, prices); + + // After we confirmed everything is in place, we can do rebalance, and read the response (events should tell us the info we need) + let res = suite.rebalance(None).unwrap(); + println!("Rebalance response: {:?}", res); +} diff --git a/tests/rust-tests/src/live_debugging/types.rs b/tests/rust-tests/src/live_debugging/types.rs new file mode 100644 index 00000000..ace178ec --- /dev/null +++ b/tests/rust-tests/src/live_debugging/types.rs @@ -0,0 +1,114 @@ +use std::str::FromStr; + +use auction_package::{states::MinAmount, Pair, Price}; +use chrono::{DateTime, NaiveDate, NaiveDateTime, Timelike}; +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{BlockInfo, Coin, Timestamp}; +use valence_package::services::rebalancer::{BaseDenom, RebalancerConfig}; + +#[derive( + cosmwasm_schema::serde::Serialize, + cosmwasm_schema::serde::Deserialize, + std::clone::Clone, + std::fmt::Debug, + std::cmp::PartialEq, + cosmwasm_schema::schemars::JsonSchema, +)] +#[allow(clippy::derive_partial_eq_without_eq)] // Allow users of `#[cw_serde]` to not implement Eq without clippy complaining +#[serde(crate = "::cosmwasm_schema::serde")] +#[schemars(crate = "::cosmwasm_schema::schemars")] +pub struct Balances { + pub balances: Vec, +} + +#[derive( + cosmwasm_schema::serde::Serialize, + cosmwasm_schema::serde::Deserialize, + std::clone::Clone, + std::fmt::Debug, + std::cmp::PartialEq, + cosmwasm_schema::schemars::JsonSchema, +)] +#[allow(clippy::derive_partial_eq_without_eq)] // Allow users of `#[cw_serde]` to not implement Eq without clippy complaining +#[serde(crate = "::cosmwasm_schema::serde")] +#[schemars(crate = "::cosmwasm_schema::schemars")] +pub struct BlockRes { + pub block: Block, +} + +#[derive( + cosmwasm_schema::serde::Serialize, + cosmwasm_schema::serde::Deserialize, + std::clone::Clone, + std::fmt::Debug, + std::cmp::PartialEq, + cosmwasm_schema::schemars::JsonSchema, +)] +#[allow(clippy::derive_partial_eq_without_eq)] // Allow users of `#[cw_serde]` to not implement Eq without clippy complaining +#[serde(crate = "::cosmwasm_schema::serde")] +#[schemars(crate = "::cosmwasm_schema::schemars")] +pub struct Block { + pub header: BlockInfoTemp, +} + +#[derive( + cosmwasm_schema::serde::Serialize, + cosmwasm_schema::serde::Deserialize, + std::clone::Clone, + std::fmt::Debug, + std::cmp::PartialEq, + cosmwasm_schema::schemars::JsonSchema, +)] +#[allow(clippy::derive_partial_eq_without_eq)] // Allow users of `#[cw_serde]` to not implement Eq without clippy complaining +#[serde(crate = "::cosmwasm_schema::serde")] +#[schemars(crate = "::cosmwasm_schema::schemars")] +pub struct BlockInfoTemp { + pub height: String, + pub time: String, + pub chain_id: String, +} + +impl From for BlockInfo { + fn from(block_info_temp: BlockInfoTemp) -> Self { + let seconds = + NaiveDateTime::parse_from_str(&block_info_temp.time, "%Y-%m-%dT%H:%M:%S%.9fZ") + .unwrap() + .and_utc() + .timestamp_nanos_opt() + .unwrap(); + + BlockInfo { + height: block_info_temp.height.parse().unwrap(), + time: Timestamp::from_nanos(seconds as u64), + chain_id: block_info_temp.chain_id, + } + } +} + +#[cw_serde] +pub struct ConfigRes { + pub data: RebalancerConfig, +} + +#[cw_serde] +pub struct AllPricesRes { + pub data: Prices, +} + +pub type Prices = Vec<(Pair, Price)>; + +#[cw_serde] +pub struct WhitelistDenomsRes { + pub data: WhitelistDenoms, +} + +#[cw_serde] +pub struct WhitelistDenoms { + pub denom_whitelist: Vec, + pub base_denom_whitelist: Vec, +} + +#[cw_serde] +pub struct MinLimitsRes { + pub data: MinAmount, +} diff --git a/tests/rust-tests/src/suite/instantiates/oracle.rs b/tests/rust-tests/src/suite/instantiates/oracle.rs index 6d6349d5..828a47de 100644 --- a/tests/rust-tests/src/suite/instantiates/oracle.rs +++ b/tests/rust-tests/src/suite/instantiates/oracle.rs @@ -10,6 +10,12 @@ impl From for price_oracle::msg::InstantiateMsg { } } +impl From<&mut OracleInstantiate> for price_oracle::msg::InstantiateMsg { + fn from(value: &mut OracleInstantiate) -> Self { + value.msg.clone() + } +} + impl OracleInstantiate { pub fn default(auctions_manager_addr: Addr) -> Self { Self::new(auctions_manager_addr) @@ -30,4 +36,13 @@ impl OracleInstantiate { self.msg.auctions_manager_addr = auctions_manager_addr.to_string(); self } + + /* Change functions */ + pub fn change_seconds_allow_manual_change( + &mut self, + seconds_allow_manual_change: u64, + ) -> &mut Self { + self.msg.seconds_allow_manual_change = seconds_allow_manual_change; + self + } } diff --git a/tests/rust-tests/src/suite/instantiates/rebalancer.rs b/tests/rust-tests/src/suite/instantiates/rebalancer.rs index 97b24e9f..1506ef7f 100644 --- a/tests/rust-tests/src/suite/instantiates/rebalancer.rs +++ b/tests/rust-tests/src/suite/instantiates/rebalancer.rs @@ -14,6 +14,12 @@ impl From for rebalancer::msg::InstantiateMsg { } } +impl From<&mut RebalancerInstantiate> for rebalancer::msg::InstantiateMsg { + fn from(value: &mut RebalancerInstantiate) -> Self { + value.msg.clone() + } +} + impl RebalancerInstantiate { pub fn default(services_manager: &str, auctions_manager: &str) -> Self { Self { diff --git a/tests/rust-tests/src/suite/suite_auction.rs b/tests/rust-tests/src/suite/suite_auction.rs index 27038ac3..ab731ef2 100644 --- a/tests/rust-tests/src/suite/suite_auction.rs +++ b/tests/rust-tests/src/suite/suite_auction.rs @@ -6,7 +6,7 @@ use auction_package::{ helpers::{ChainHaltConfig, GetPriceResponse}, msgs::AuctionsManagerQueryMsg, states::MinAmount, - AuctionStrategy, Pair, PriceFreshnessStrategy, + AuctionStrategy, Pair, Price, PriceFreshnessStrategy, }; use cosmwasm_std::{coin, coins, Addr, Coin, Decimal, Uint128}; use cw_multi_test::{AppResponse, Executor}; @@ -695,6 +695,16 @@ impl Suite { .unwrap() } + pub fn query_oracle_all_prices(&self) -> Vec<(Pair, Price)> { + self.app + .wrap() + .query_wasm_smart( + self.oracle_addr.clone(), + &price_oracle::msg::QueryMsg::GetAllPrices, + ) + .unwrap() + } + pub fn query_auction_price(&self, auction_addr: Addr) -> GetPriceResponse { self.app .wrap() diff --git a/tests/rust-tests/src/tests_rebalancer/mod.rs b/tests/rust-tests/src/tests_rebalancer/mod.rs index 0416d1b4..b9e2ff49 100644 --- a/tests/rust-tests/src/tests_rebalancer/mod.rs +++ b/tests/rust-tests/src/tests_rebalancer/mod.rs @@ -14,3 +14,5 @@ mod test_management; // Test limits of the rebalancer #[cfg(test)] mod test_limits; + + diff --git a/tests/rust-tests/src/tests_rebalancer/test_limits.rs b/tests/rust-tests/src/tests_rebalancer/test_limits.rs index 16dc6424..baf734f3 100644 --- a/tests/rust-tests/src/tests_rebalancer/test_limits.rs +++ b/tests/rust-tests/src/tests_rebalancer/test_limits.rs @@ -72,7 +72,9 @@ fn test_min_balance() { .with_rebalancer_data(vec![config]) .build_default(); - let old_config = suite.query_rebalancer_config(suite.get_account_addr(0)).unwrap(); + let old_config = suite + .query_rebalancer_config(suite.get_account_addr(0)) + .unwrap(); for _ in 0..10 { suite.resolve_cycle(); @@ -83,10 +85,16 @@ fn test_min_balance() { assert!(balance_atom.amount < Uint128::new(1000)); assert!(balance_atom.amount >= Uint128::new(950)); - let new_config = suite.query_rebalancer_config(suite.get_account_addr(0)).unwrap(); + let new_config = suite + .query_rebalancer_config(suite.get_account_addr(0)) + .unwrap(); new_config.targets.iter().for_each(|new_target| { - let target = old_config.targets.iter().find(|t| t.denom == new_target.denom).unwrap(); + let target = old_config + .targets + .iter() + .find(|t| t.denom == new_target.denom) + .unwrap(); assert!(new_target.percentage == target.percentage); }); diff --git a/tests/rust-tests/src/tests_rebalancer/tests_unit.rs b/tests/rust-tests/src/tests_rebalancer/tests_unit.rs index a8dcff19..a86042a0 100644 --- a/tests/rust-tests/src/tests_rebalancer/tests_unit.rs +++ b/tests/rust-tests/src/tests_rebalancer/tests_unit.rs @@ -375,6 +375,8 @@ fn test_verify_target_min_balance_over_balance() { assert_eq!(res[2].target.percentage, Decimal::bps(0)); } +// We have 100 ATOM so our total value is 100 +// we #[test] fn test_verify_target_priority() { let deps = mock_dependencies(); @@ -400,7 +402,7 @@ fn test_verify_target_priority() { target: ParsedTarget { denom: NTRN.to_string(), percentage: Decimal::bps(2500), - min_balance: Some(160_u128.into()), + min_balance: Some(25_u128.into()), last_input: None, last_i: SignedDecimal::zero(), }, @@ -433,31 +435,37 @@ fn test_verify_target_priority() { target_helpers.clone(), ) .unwrap(); + assert_eq!( res[0].target.percentage, - Decimal::from_str("0.133333333333333333").unwrap() + Decimal::from_str("0.333333333333333333").unwrap() ); - assert_eq!(res[1].target.percentage, Decimal::bps(8000)); + assert_eq!(res[1].target.percentage, Decimal::bps(5000)); assert_eq!( res[2].target.percentage, - Decimal::from_str("0.066666666666666666").unwrap() + Decimal::from_str("0.166666666666666666").unwrap() ); // Priority config.target_override_strategy = TargetOverrideStrategy::Priority; + // our total value is 100 + // min_balance is 25 (price is 0.5, which means 25 / 0.5 = 50 value) + // so we expect the result to be 50% of target 1 and 50% target 2 (target 3 is 0) let res = verify_targets( &config, Decimal::from_str("100").unwrap(), target_helpers.clone(), ) .unwrap(); - assert_eq!(res[0].target.percentage, Decimal::bps(2000)); - assert_eq!(res[1].target.percentage, Decimal::bps(8000)); + + assert_eq!(res[0].target.percentage, Decimal::bps(5000)); + assert_eq!(res[1].target.percentage, Decimal::bps(5000)); assert_eq!(res[2].target.percentage, Decimal::bps(0)); - target_helpers[2].target.min_balance = Some(500_u128.into()); - target_helpers[1].target.min_balance = None; + // total value is still 100 + // we set min_balance to be 20 meaning (price is 0.5, which means 25 / 0.5 = 50 value) + target_helpers[1].target.min_balance = Some(20_u128.into()); let res = verify_targets( &config, @@ -465,11 +473,12 @@ fn test_verify_target_priority() { target_helpers.clone(), ) .unwrap(); + assert_eq!(res[0].target.percentage, Decimal::bps(5000)); - assert_eq!(res[1].target.percentage, Decimal::bps(0)); - assert_eq!(res[2].target.percentage, Decimal::bps(5000)); + assert_eq!(res[1].target.percentage, Decimal::bps(4000)); + assert_eq!(res[2].target.percentage, Decimal::bps(1000)); - target_helpers[2].target.min_balance = Some(400_u128.into()); + target_helpers[1].target.min_balance = Some(400_u128.into()); let res = verify_targets( &config, @@ -477,6 +486,9 @@ fn test_verify_target_priority() { target_helpers.clone(), ) .unwrap(); + + println!("{:?}", res); + assert_eq!(res[0].target.percentage, Decimal::bps(5000)); assert_eq!(res[1].target.percentage, Decimal::bps(1000)); assert_eq!(res[2].target.percentage, Decimal::bps(4000)); From 151b6eaccea5af1f3586b64e9444880ef9057cea Mon Sep 17 00:00:00 2001 From: Art3mix Date: Fri, 14 Jun 2024 11:38:11 +0300 Subject: [PATCH 16/22] fix multiplication bug in calculating the D term --- contracts/services/rebalancer/src/rebalance.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 54102047..b1475109 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -259,7 +259,7 @@ pub fn do_rebalance( 0, )?; (diff.checked_div(Decimal::from_atomics(cycle_period, 0)?))? - .min(Decimal::new(MAX_PID_DT_VALUE.into())) + .min(Decimal::from_atomics(MAX_PID_DT_VALUE, 0)?) }; let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?; @@ -479,6 +479,7 @@ fn do_pid( Some(last_input) => signed_input - last_input.into(), None => SignedDecimal::zero(), }; + println!("d: {:?} | signed_d: {:?} | signed_dt: {:?}", d, signed_d, signed_dt); d = d * signed_d / signed_dt; let output = p + i - d; From eccb622da00488194cc7330caf4bf101997704a1 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Fri, 14 Jun 2024 13:54:32 +0300 Subject: [PATCH 17/22] fix the generate trades bug, and tidy code --- contracts/services/rebalancer/src/helpers.rs | 2 +- .../services/rebalancer/src/rebalance.rs | 34 +++++++----- .../rust-tests/src/live_debugging/helpers.rs | 5 -- tests/rust-tests/src/live_debugging/mod.rs | 8 +-- .../src/live_debugging/suite_builder.rs | 2 +- .../src/live_debugging/suite_helpers.rs | 54 ++++++++----------- .../live_debugging/test_specific_config.rs | 22 ++++++-- tests/rust-tests/src/live_debugging/types.rs | 4 +- tests/rust-tests/src/tests_rebalancer/mod.rs | 2 - .../src/tests_rebalancer/tests_unit.rs | 38 ++++++------- 10 files changed, 82 insertions(+), 89 deletions(-) delete mode 100644 tests/rust-tests/src/live_debugging/helpers.rs diff --git a/contracts/services/rebalancer/src/helpers.rs b/contracts/services/rebalancer/src/helpers.rs index 0ad23220..fd579d95 100644 --- a/contracts/services/rebalancer/src/helpers.rs +++ b/contracts/services/rebalancer/src/helpers.rs @@ -27,7 +27,7 @@ pub struct TargetHelper { /// can either be to sell or to buy, depends on the calculation pub value_to_trade: Decimal, /// The minimum value we can send to the auction - pub auction_min_amount: Decimal, + pub auction_min_send_value: Decimal, } #[cw_serde] diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index b1475109..868ec1a4 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -334,7 +334,7 @@ pub(crate) fn set_auction_min_amounts( .find(|min_amount| min_amount.0 == sell_token.target.denom) { Some(min_amount) => { - sell_token.auction_min_amount = + sell_token.auction_min_send_value = Decimal::from_atomics(min_amount.1, 0)?.checked_div(sell_token.price)?; } None => { @@ -347,8 +347,9 @@ pub(crate) fn set_auction_min_amounts( send: min_send_amount, .. }) => { - sell_token.auction_min_amount = Decimal::from_atomics(min_send_amount, 0)? - .checked_div(sell_token.price)?; + sell_token.auction_min_send_value = + Decimal::from_atomics(min_send_amount, 0)? + .checked_div(sell_token.price)?; min_amount_limits.push((sell_token.target.denom.clone(), min_send_amount)); Ok(()) } @@ -438,7 +439,7 @@ fn get_inputs( price, balance_value, value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }); Ok((total_value, targets_helpers)) @@ -479,7 +480,7 @@ fn do_pid( Some(last_input) => signed_input - last_input.into(), None => SignedDecimal::zero(), }; - println!("d: {:?} | signed_d: {:?} | signed_dt: {:?}", d, signed_d, signed_dt); + d = d * signed_d / signed_dt; let output = p + i - d; @@ -652,26 +653,26 @@ fn generate_trades_msgs( // check if the amount we intent to buy, is lower than min_amount of the sell token // if its not, it will be handled correctly by the main loop. // but if it is, it means we need to sell other token more then we intent to - if token_buy.value_to_trade < token_sell.auction_min_amount { + if token_buy.value_to_trade < token_sell.auction_min_send_value { // If the amount we try to sell, is below the auction_min_amount, we need to set it to zero // else we reduce the auction_min_amount value - if token_sell.value_to_trade < token_sell.auction_min_amount { + if token_sell.value_to_trade < token_sell.auction_min_send_value { token_sell.value_to_trade = Decimal::zero(); } else { - token_sell.value_to_trade -= token_sell.auction_min_amount; + token_sell.value_to_trade -= token_sell.auction_min_send_value; } let pair = Pair::from(( token_sell.target.denom.clone(), token_buy.target.denom.clone(), )); - let amount = (token_sell.auction_min_amount * token_sell.price).to_uint_ceil(); + let amount = (token_sell.auction_min_send_value * token_sell.price).to_uint_ceil(); let trade = RebalanceTrade::new(pair, amount); token_buy.value_to_trade = Decimal::zero(); if let Ok(msg) = construct_msg(deps, auction_manager.clone(), trade.clone()) { - max_sell -= token_sell.auction_min_amount; + max_sell -= token_sell.auction_min_send_value; msgs.push(msg); }; } @@ -719,18 +720,20 @@ fn generate_trades_msgs( } // If we intent to sell less then our minimum, we set to_trade to be 0 and continue - if token_sell.value_to_trade < token_sell.auction_min_amount { + if token_sell.value_to_trade < token_sell.auction_min_send_value { token_sell.value_to_trade = Decimal::zero(); return; } + // If our buy value is lower then our sell min_send value, we do nothing and continue. + if token_buy.value_to_trade < token_sell.auction_min_send_value { + return; + } + // If we hit our max sell limit, we only sell the limit left // otherwise, we keep track of how much we already sold if token_sell.value_to_trade > max_sell { token_sell.value_to_trade = max_sell; - max_sell = Decimal::zero(); - } else { - max_sell -= token_sell.value_to_trade; } let pair = Pair::from(( @@ -747,6 +750,7 @@ fn generate_trades_msgs( token_buy.value_to_trade = Decimal::zero(); let Ok(msg) = construct_msg(deps, auction_manager.clone(), trade.clone()) else { + max_sell -= token_buy.value_to_trade; return; }; @@ -761,6 +765,7 @@ fn generate_trades_msgs( token_sell.value_to_trade = Decimal::zero(); let Ok(msg) = construct_msg(deps, auction_manager.clone(), trade.clone()) else { + max_sell -= token_sell.value_to_trade; return; }; @@ -769,6 +774,7 @@ fn generate_trades_msgs( } }); }); + println!("msgs: {:?}", msgs); (msgs, trades) } diff --git a/tests/rust-tests/src/live_debugging/helpers.rs b/tests/rust-tests/src/live_debugging/helpers.rs deleted file mode 100644 index cb85ea19..00000000 --- a/tests/rust-tests/src/live_debugging/helpers.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub fn concat(namespace: &[u8], key: &[u8]) -> Vec { - let mut k = namespace.to_vec(); - k.extend_from_slice(key); - k -} \ No newline at end of file diff --git a/tests/rust-tests/src/live_debugging/mod.rs b/tests/rust-tests/src/live_debugging/mod.rs index 42365ad6..751c75cc 100644 --- a/tests/rust-tests/src/live_debugging/mod.rs +++ b/tests/rust-tests/src/live_debugging/mod.rs @@ -10,11 +10,7 @@ mod suite_builder; #[cfg(test)] mod suite_helpers; -#[cfg(test)] -mod helpers; - -const NAMESPACE_WASM: &[u8] = b"wasm"; - const REBALANCER_ADDR: &str = "neutron1qs6mzpmcw3dvg5l8nyywetcj326scszdj7v4pfk55xwshd4prqnqfwc0z2"; const ORACLE_ADDR: &str = "neutron1s8uqyh0mmh8g66s2dectf56c08y6fvusp39undp8kf4v678ededsy6tstf"; -const AUCTIONS_MANAGER_ADDR: &str = "neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz"; +const AUCTIONS_MANAGER_ADDR: &str = + "neutron13exc5wdc7y5qpqazc34djnu934lqvfw2dru30j52ahhjep6jzx8ssjxcyz"; diff --git a/tests/rust-tests/src/live_debugging/suite_builder.rs b/tests/rust-tests/src/live_debugging/suite_builder.rs index a9c71b69..41bc1916 100644 --- a/tests/rust-tests/src/live_debugging/suite_builder.rs +++ b/tests/rust-tests/src/live_debugging/suite_builder.rs @@ -1,4 +1,4 @@ -use std::{collections::HashMap, hash::Hash}; +use std::collections::HashMap; use auction_package::Pair; use cosmwasm_std::{BlockInfo, Coin}; diff --git a/tests/rust-tests/src/live_debugging/suite_helpers.rs b/tests/rust-tests/src/live_debugging/suite_helpers.rs index 722ab576..5c1ca6bc 100644 --- a/tests/rust-tests/src/live_debugging/suite_helpers.rs +++ b/tests/rust-tests/src/live_debugging/suite_helpers.rs @@ -1,12 +1,14 @@ use std::{ - collections::{hash_map::RandomState, BTreeMap, HashMap, HashSet}, + collections::{BTreeMap, HashMap, HashSet}, process::Command, }; -use auction_package::{states::{MinAmount, PRICES}, AuctionStrategy, Pair}; -use cosmwasm_std::{from_json, to_json_binary, to_json_vec, Addr, Coin, Storage}; +use auction_package::{ + states::{MinAmount, PRICES}, + AuctionStrategy, Pair, +}; +use cosmwasm_std::{from_json, to_json_binary, Addr, Coin}; use cw_multi_test::{App, Executor}; -use cw_storage_plus::Prefixer; use rebalancer::state::CONFIGS; use valence_package::services::{ rebalancer::{RebalancerConfig, Target}, @@ -22,9 +24,8 @@ use crate::suite::{ }; use super::{ - helpers::concat, types::{MinLimitsRes, Prices, WhitelistDenoms}, - AUCTIONS_MANAGER_ADDR, NAMESPACE_WASM, REBALANCER_ADDR, + AUCTIONS_MANAGER_ADDR, }; impl SuiteBuilder { @@ -112,16 +113,6 @@ impl SuiteBuilder { let price = prices.iter().find(|(p, _)| p == &pair).unwrap().1.clone(); let mut oracle_storage = app.contract_storage_mut(&price_oracle_addr); PRICES.save(oracle_storage.as_mut(), pair, &price).unwrap(); - // app.execute_contract( - // self.admin.clone(), - // price_oracle_addr.clone(), - // &price_oracle::msg::ExecuteMsg::ManualPriceUpdate { - // pair: pair.clone(), - // price: price.price, - // }, - // &[], - // ) - // .unwrap(); }) }); @@ -189,7 +180,7 @@ impl SuiteBuilder { self.owner.clone(), &account_init_msg, &[], - format!("account"), + "account".to_string(), Some(self.owner.to_string()), ) .unwrap(); @@ -203,21 +194,18 @@ impl SuiteBuilder { }); // register to the rebalancer with some mock data first - let targets: HashSet = HashSet::from_iter( - [ - Target { - denom: whitelist_denoms[0].to_string(), - bps: 7500, - min_balance: None, - }, - Target { - denom: whitelist_denoms[1].to_string(), - bps: 2500, - min_balance: None, - }, - ] - .into_iter(), - ); + let targets: HashSet = HashSet::from_iter([ + Target { + denom: whitelist_denoms[0].to_string(), + bps: 7500, + min_balance: None, + }, + Target { + denom: whitelist_denoms[1].to_string(), + bps: 2500, + min_balance: None, + }, + ]); let mut mock_rebalancer_data = SuiteBuilder::get_default_rebalancer_register_data(); mock_rebalancer_data.base_denom = "untrn".to_string(); @@ -257,7 +245,7 @@ impl SuiteBuilder { } impl SuiteBuilder { - pub fn get_auction_min_amounts(denoms: &Vec) -> BTreeMap { + pub fn get_auction_min_amounts(denoms: &[String]) -> BTreeMap { BTreeMap::from_iter(denoms.iter().map(|denom| { let q_string = format!("{{\"get_min_limit\": {{\"denom\": \"{}\"}}}}", denom); let min_limits_output = Command::new("neutrond") diff --git a/tests/rust-tests/src/live_debugging/test_specific_config.rs b/tests/rust-tests/src/live_debugging/test_specific_config.rs index fb9de5d1..13c94322 100644 --- a/tests/rust-tests/src/live_debugging/test_specific_config.rs +++ b/tests/rust-tests/src/live_debugging/test_specific_config.rs @@ -21,7 +21,7 @@ use valence_package::services::rebalancer::RebalancerConfig; use crate::{ live_debugging::{ - types::{AllPricesRes, Block, BlockRes, ConfigRes, Prices, WhitelistDenoms, WhitelistDenomsRes}, + types::{AllPricesRes, BlockRes, ConfigRes, Prices, WhitelistDenoms, WhitelistDenomsRes}, ORACLE_ADDR, REBALANCER_ADDR, }, suite::suite_builder::SuiteBuilder, @@ -32,7 +32,7 @@ use super::types::Balances; const ACCOUNT_ADDR: &str = "neutron1wcv0c8ktmjgtj0a5dt6zdteer2nsyawqtnm5kxt7su5063dudz8qasjl97"; const HEIGHT: &str = ""; -#[ignore = "Debugging"] +#[ignore = "For debugging mainnet data"] #[test] fn live_debugging() { // If we have specifig height, query by that height @@ -52,10 +52,12 @@ fn live_debugging() { .output() .expect("Failed getting balances"); - let block_info: BlockInfo = + let block_info: BlockInfo = from_json::(String::from_utf8_lossy(&block_output.stdout).to_string()) .unwrap() - .block.header.into(); + .block + .header + .into(); // query mainnet for the balances of the account let balances_output = Command::new("neutrond") @@ -151,5 +153,15 @@ fn live_debugging() { // After we confirmed everything is in place, we can do rebalance, and read the response (events should tell us the info we need) let res = suite.rebalance(None).unwrap(); - println!("Rebalance response: {:?}", res); + // println!("Rebalance response: {:?}", res); + + // print our events for debugging + res.events.iter().for_each(|event| { + if event.ty.contains("valence") { + println!( + "Type: {} | Data: {}", + event.attributes[1].value, event.attributes[2].value + ); + } + }); } diff --git a/tests/rust-tests/src/live_debugging/types.rs b/tests/rust-tests/src/live_debugging/types.rs index ace178ec..327ceb09 100644 --- a/tests/rust-tests/src/live_debugging/types.rs +++ b/tests/rust-tests/src/live_debugging/types.rs @@ -1,7 +1,5 @@ -use std::str::FromStr; - use auction_package::{states::MinAmount, Pair, Price}; -use chrono::{DateTime, NaiveDate, NaiveDateTime, Timelike}; +use chrono::NaiveDateTime; use cosmwasm_schema::cw_serde; use cosmwasm_std::{BlockInfo, Coin, Timestamp}; use valence_package::services::rebalancer::{BaseDenom, RebalancerConfig}; diff --git a/tests/rust-tests/src/tests_rebalancer/mod.rs b/tests/rust-tests/src/tests_rebalancer/mod.rs index b9e2ff49..0416d1b4 100644 --- a/tests/rust-tests/src/tests_rebalancer/mod.rs +++ b/tests/rust-tests/src/tests_rebalancer/mod.rs @@ -14,5 +14,3 @@ mod test_management; // Test limits of the rebalancer #[cfg(test)] mod test_limits; - - diff --git a/tests/rust-tests/src/tests_rebalancer/tests_unit.rs b/tests/rust-tests/src/tests_rebalancer/tests_unit.rs index a86042a0..7bc84380 100644 --- a/tests/rust-tests/src/tests_rebalancer/tests_unit.rs +++ b/tests/rust-tests/src/tests_rebalancer/tests_unit.rs @@ -31,7 +31,7 @@ fn test_verify_target_2_denoms() { balance_amount: Uint128::from_str("100").unwrap(), balance_value: Decimal::from_str("100").unwrap(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -45,7 +45,7 @@ fn test_verify_target_2_denoms() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, ]; @@ -114,7 +114,7 @@ fn test_verify_target_3_denoms() { balance_amount: Uint128::new(100), balance_value: Decimal::from_str("100").unwrap(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -128,7 +128,7 @@ fn test_verify_target_3_denoms() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -142,7 +142,7 @@ fn test_verify_target_3_denoms() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, ]; @@ -227,7 +227,7 @@ fn test_verify_target_leftover_strategy() { balance_amount: Uint128::new(100), balance_value: Decimal::from_str("100").unwrap(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -241,7 +241,7 @@ fn test_verify_target_leftover_strategy() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -255,7 +255,7 @@ fn test_verify_target_leftover_strategy() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, ]; @@ -337,7 +337,7 @@ fn test_verify_target_min_balance_over_balance() { balance_amount: Uint128::new(100), balance_value: Decimal::from_str("100").unwrap(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -351,7 +351,7 @@ fn test_verify_target_min_balance_over_balance() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -365,7 +365,7 @@ fn test_verify_target_min_balance_over_balance() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, ]; @@ -396,7 +396,7 @@ fn test_verify_target_priority() { balance_amount: Uint128::new(100), balance_value: Decimal::from_str("100").unwrap(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -410,7 +410,7 @@ fn test_verify_target_priority() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, TargetHelper { target: ParsedTarget { @@ -424,7 +424,7 @@ fn test_verify_target_priority() { balance_amount: Uint128::zero(), balance_value: Decimal::zero(), value_to_trade: Decimal::zero(), - auction_min_amount: Decimal::zero(), + auction_min_send_value: Decimal::zero(), }, ]; @@ -475,10 +475,10 @@ fn test_verify_target_priority() { .unwrap(); assert_eq!(res[0].target.percentage, Decimal::bps(5000)); - assert_eq!(res[1].target.percentage, Decimal::bps(4000)); + assert_eq!(res[1].target.percentage, Decimal::bps(4000)); // 40% is the min_balance we set (20 / 0.5) assert_eq!(res[2].target.percentage, Decimal::bps(1000)); - target_helpers[1].target.min_balance = Some(400_u128.into()); + target_helpers[1].target.min_balance = Some(40_u128.into()); let res = verify_targets( &config, @@ -489,7 +489,7 @@ fn test_verify_target_priority() { println!("{:?}", res); - assert_eq!(res[0].target.percentage, Decimal::bps(5000)); - assert_eq!(res[1].target.percentage, Decimal::bps(1000)); - assert_eq!(res[2].target.percentage, Decimal::bps(4000)); + assert_eq!(res[0].target.percentage, Decimal::bps(2000)); + assert_eq!(res[1].target.percentage, Decimal::bps(8000)); // 80% is the min_balance we set (40 / 0.5) + assert_eq!(res[2].target.percentage, Decimal::bps(0)); } From 21665091dd365912561f54a53d699e0537ba8ed6 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Fri, 14 Jun 2024 14:16:09 +0300 Subject: [PATCH 18/22] remove prints --- contracts/services/rebalancer/src/rebalance.rs | 1 - tests/rust-tests/src/live_debugging/test_specific_config.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index 868ec1a4..fffa013d 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -774,7 +774,6 @@ fn generate_trades_msgs( } }); }); - println!("msgs: {:?}", msgs); (msgs, trades) } diff --git a/tests/rust-tests/src/live_debugging/test_specific_config.rs b/tests/rust-tests/src/live_debugging/test_specific_config.rs index 13c94322..3a010664 100644 --- a/tests/rust-tests/src/live_debugging/test_specific_config.rs +++ b/tests/rust-tests/src/live_debugging/test_specific_config.rs @@ -29,7 +29,7 @@ use crate::{ use super::types::Balances; -const ACCOUNT_ADDR: &str = "neutron1wcv0c8ktmjgtj0a5dt6zdteer2nsyawqtnm5kxt7su5063dudz8qasjl97"; +const ACCOUNT_ADDR: &str = "neutron1yd27kgnsjkeddwtuy29q9yzrnd247v6hcml6swl54dfkcwuuytqs8ha94x"; const HEIGHT: &str = ""; #[ignore = "For debugging mainnet data"] From 414d86609049856538394c3e897bb4f9abc96b8a Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 17 Jun 2024 13:48:09 +0300 Subject: [PATCH 19/22] Keyne feedback --- contracts/auction/price_oracle/src/contract.rs | 9 ++++++--- contracts/auction/price_oracle/src/msg.rs | 5 ++++- contracts/services/rebalancer/src/rebalance.rs | 16 +++++++--------- .../src/live_debugging/test_specific_config.rs | 2 +- tests/rust-tests/src/suite/suite_auction.rs | 8 ++++++-- 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/contracts/auction/price_oracle/src/contract.rs b/contracts/auction/price_oracle/src/contract.rs index 1307a54b..65db8c85 100644 --- a/contracts/auction/price_oracle/src/contract.rs +++ b/contracts/auction/price_oracle/src/contract.rs @@ -4,13 +4,14 @@ use auction_package::helpers::{ approve_admin_change, cancel_admin_change, start_admin_change, verify_admin, }; use auction_package::states::{ADMIN, PAIRS, PRICES, TWAP_PRICES}; -use auction_package::Price; +use auction_package::{Pair, Price}; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ to_json_binary, Binary, Decimal, Deps, DepsMut, Env, MessageInfo, Response, StdResult, }; use cw2::set_contract_version; +use cw_storage_plus::Bound; use valence_package::event_indexing::{ValenceEvent, ValenceGenericEvent}; use crate::error::ContractError; @@ -313,9 +314,11 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result { + QueryMsg::GetAllPrices { from, limit } => { + let from = from.map(Bound::::exclusive); let prices = PRICES - .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) + .range(deps.storage, from, None, cosmwasm_std::Order::Ascending) + .take(limit.unwrap_or(10) as usize) .collect::>>()?; Ok(to_json_binary(&prices)?) diff --git a/contracts/auction/price_oracle/src/msg.rs b/contracts/auction/price_oracle/src/msg.rs index 2c1550ab..cf9fe177 100644 --- a/contracts/auction/price_oracle/src/msg.rs +++ b/contracts/auction/price_oracle/src/msg.rs @@ -49,7 +49,10 @@ pub enum QueryMsg { #[returns(Price)] GetPrice { pair: Pair }, #[returns(Vec<(Pair, Price)>)] - GetAllPrices, + GetAllPrices { + from: Option, + limit: Option, + }, #[returns(Config)] GetConfig, #[returns(Addr)] diff --git a/contracts/services/rebalancer/src/rebalance.rs b/contracts/services/rebalancer/src/rebalance.rs index fffa013d..50973e00 100644 --- a/contracts/services/rebalancer/src/rebalance.rs +++ b/contracts/services/rebalancer/src/rebalance.rs @@ -265,17 +265,15 @@ pub fn do_rebalance( let (mut to_sell, to_buy) = do_pid(total_value, &mut target_helpers, config.pid.clone(), dt)?; // Update targets in config only the last data we need for the next rebalance calculation - config.targets.iter_mut().for_each(|target| { - let Some(target_helper) = target_helpers + for target in config.targets.iter_mut() { + if let Some(target_helper) = target_helpers .iter() .find(|th| th.target.denom == target.denom) - else { - return; - }; - - target.last_i = target_helper.target.last_i; - target.last_input = target_helper.target.last_input; - }); + { + target.last_i = target_helper.target.last_i; + target.last_input = target_helper.target.last_input; + } + } // get minimum amount we can send to each auction set_auction_min_amounts(deps, auction_manager, &mut to_sell, min_amount_limits)?; diff --git a/tests/rust-tests/src/live_debugging/test_specific_config.rs b/tests/rust-tests/src/live_debugging/test_specific_config.rs index 3a010664..b2ebb2b7 100644 --- a/tests/rust-tests/src/live_debugging/test_specific_config.rs +++ b/tests/rust-tests/src/live_debugging/test_specific_config.rs @@ -144,7 +144,7 @@ fn live_debugging() { let account_config = suite .query_rebalancer_config(suite.account_addrs[0].clone()) .unwrap(); - let all_prices = suite.query_oracle_all_prices(); + let all_prices = suite.query_oracle_all_prices(None, None); // make sure the config is set in our mock rebalancer assert_eq!(account_config, config); diff --git a/tests/rust-tests/src/suite/suite_auction.rs b/tests/rust-tests/src/suite/suite_auction.rs index ab731ef2..29d9aafb 100644 --- a/tests/rust-tests/src/suite/suite_auction.rs +++ b/tests/rust-tests/src/suite/suite_auction.rs @@ -695,12 +695,16 @@ impl Suite { .unwrap() } - pub fn query_oracle_all_prices(&self) -> Vec<(Pair, Price)> { + pub fn query_oracle_all_prices( + &self, + from: Option, + limit: Option, + ) -> Vec<(Pair, Price)> { self.app .wrap() .query_wasm_smart( self.oracle_addr.clone(), - &price_oracle::msg::QueryMsg::GetAllPrices, + &price_oracle::msg::QueryMsg::GetAllPrices { from, limit }, ) .unwrap() } From ae1e06f488c2fd597b349f77d372a12815395195 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 17 Jun 2024 14:32:35 +0300 Subject: [PATCH 20/22] reset PID last calculation on config update --- contracts/services/rebalancer/src/contract.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/contracts/services/rebalancer/src/contract.rs b/contracts/services/rebalancer/src/contract.rs index 6414b189..f9f5184d 100644 --- a/contracts/services/rebalancer/src/contract.rs +++ b/contracts/services/rebalancer/src/contract.rs @@ -5,8 +5,7 @@ use auction_package::Pair; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ - to_json_binary, Addr, Binary, Coin, Decimal, Deps, DepsMut, Env, Event, MessageInfo, Reply, - Response, StdError, StdResult, Uint128, + to_json_binary, Addr, Binary, Coin, Decimal, Deps, DepsMut, Env, Event, MessageInfo, Reply, Response, StdError, StdResult, Uint128 }; use cw2::set_contract_version; use cw_storage_plus::Bound; @@ -16,6 +15,7 @@ use valence_package::helpers::{approve_admin_change, verify_services_manager, Op use valence_package::services::rebalancer::{ PauseData, RebalancerExecuteMsg, SystemRebalanceStatus, }; +use valence_package::signed_decimal::SignedDecimal; use valence_package::states::{QueryFeeAction, ADMIN, SERVICES_MANAGER, SERVICE_FEE_CONFIG}; use crate::error::ContractError; @@ -302,6 +302,12 @@ pub fn execute( if let Some(pid) = data.pid { config.pid = pid.into_parsed()?; + + // If PID is updated, we reset the last calculation because they are no longer valid + config.targets.iter_mut().for_each(|t| { + t.last_input = None; + t.last_i = SignedDecimal::zero(); + }); } if let Some(max_limit_option) = data.max_limit_bps { From 17418c3738144882e9be7c2458da7997eca03b29 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 17 Jun 2024 14:33:42 +0300 Subject: [PATCH 21/22] clippy --- contracts/services/rebalancer/src/contract.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contracts/services/rebalancer/src/contract.rs b/contracts/services/rebalancer/src/contract.rs index f9f5184d..0ca4f3be 100644 --- a/contracts/services/rebalancer/src/contract.rs +++ b/contracts/services/rebalancer/src/contract.rs @@ -5,7 +5,8 @@ use auction_package::Pair; #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ - to_json_binary, Addr, Binary, Coin, Decimal, Deps, DepsMut, Env, Event, MessageInfo, Reply, Response, StdError, StdResult, Uint128 + to_json_binary, Addr, Binary, Coin, Decimal, Deps, DepsMut, Env, Event, MessageInfo, Reply, + Response, StdError, StdResult, Uint128, }; use cw2::set_contract_version; use cw_storage_plus::Bound; From effd7428eda5472a528dcec63ab4cd0daf9857c0 Mon Sep 17 00:00:00 2001 From: Art3mix Date: Mon, 17 Jun 2024 14:34:44 +0300 Subject: [PATCH 22/22] fix misspell --- contracts/auction/auction/src/contract.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/auction/auction/src/contract.rs b/contracts/auction/auction/src/contract.rs index 6e068389..f7a7cc80 100644 --- a/contracts/auction/auction/src/contract.rs +++ b/contracts/auction/auction/src/contract.rs @@ -239,7 +239,7 @@ mod admin { // Verify the amount of funds we have to auction, is more then the start auction min amount let manager_addr = ADMIN.load(deps.storage)?; - let min_start_acution = MIN_AUCTION_AMOUNT + let min_start_auction = MIN_AUCTION_AMOUNT .query(&deps.querier, manager_addr, config.pair.0.clone())? .unwrap_or_default() .start_auction; @@ -251,12 +251,12 @@ mod admin { AUCTION_IDS.save(deps.storage, &auction_ids)?; // if its less, refund the funds to the users - if total_funds < min_start_acution { + if total_funds < min_start_auction { return do_refund( deps, auction_ids.curr, config.pair.0.clone(), - min_start_acution, + min_start_auction, total_funds, ); }