Skip to content

Commit

Permalink
get prices daily from auction or astroport, save prices locally, and …
Browse files Browse the repository at this point in the history
…get average from those prices
  • Loading branch information
Art3miX committed Nov 26, 2024
1 parent 7f26884 commit 8cbc7d1
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 18 deletions.
File renamed without changes.
35 changes: 29 additions & 6 deletions contracts/auction/price_oracle/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ use valence_package::event_indexing::{ValenceEvent, ValenceGenericEvent};

use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use crate::state::{Config, PriceStep, ASTRO_PRICE_PATHS, CONFIG};
use crate::state::{Config, PriceStep, ASTRO_PRICE_PATHS, CONFIG, LOCAL_PRICES};

const CONTRACT_NAME: &str = "crates.io:oracle";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

const TWAP_PRICE_MAX_LEN: usize = 10;

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
Expand Down Expand Up @@ -58,20 +60,22 @@ pub fn execute(

let config = CONFIG.load(deps.storage)?;

// We get the prices from the auction
let auction_addr = PAIRS
.query(
&deps.querier,
config.auction_manager_addr.clone(),
pair.clone(),
)?
.ok_or(ContractError::PairAuctionNotFound)?;
let twap_prices = TWAP_PRICES.query(&deps.querier, auction_addr)?;
let auction_twap_prices = TWAP_PRICES.query(&deps.querier, auction_addr)?;

let source;

let price = if can_update_price_from_auction(&config, &env, &twap_prices) {
// We get last price either form auction or astroport
let last_price = if can_update_price_from_auction(&config, &env, &auction_twap_prices) {
source = "auction";
get_avg_price(twap_prices)
auction_twap_prices[0].clone()
} else {
let steps = ASTRO_PRICE_PATHS
.load(deps.storage, pair.clone())
Expand All @@ -80,12 +84,31 @@ pub fn execute(
get_price_from_astroport(deps.as_ref(), &env, steps)?
};

// Update the oracle local prices and add last price
let mut local_prices = match LOCAL_PRICES.load(deps.storage, pair.clone()) {
Ok(prices) => prices,
Err(_) => VecDeque::new(),
};

// if we have the max amount of prices already, remove the last one first
if local_prices.len() >= TWAP_PRICE_MAX_LEN {
local_prices.pop_back();
}

// Push the last price into the vector
local_prices.push_front(last_price.clone());

// Save the new list of prices
LOCAL_PRICES.save(deps.storage, pair.clone(), &local_prices)?;

// Calculate the average price
let avg_price = get_avg_price(local_prices);
// Save price
PRICES.save(deps.storage, pair.clone(), &price)?;
PRICES.save(deps.storage, pair.clone(), &avg_price)?;

let event = ValenceEvent::OracleUpdatePrice {
pair: pair.clone(),
price: price.price,
price: avg_price.price,
source: source.to_string(),
};

Expand Down
6 changes: 5 additions & 1 deletion contracts/auction/price_oracle/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use auction_package::Pair;
use std::collections::VecDeque;

use auction_package::{Pair, Price};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::Addr;
use cw_storage_plus::{Item, Map};

pub const CONFIG: Item<Config> = Item::new("config");
pub const ASTRO_PRICE_PATHS: Map<Pair, Vec<PriceStep>> = Map::new("astro_price_paths");
/// Local last 10 prices to be calculated for the average
pub const LOCAL_PRICES: Map<Pair, VecDeque<Price>> = Map::new("local_prices");

#[cw_serde]
pub struct Config {
Expand Down
8 changes: 5 additions & 3 deletions packages/cw-pid/src/pid.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use cosmwasm_std::SignedDecimal;
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use wasm_bindgen::JsValue;

#[derive(Serialize, Deserialize)]
Expand Down Expand Up @@ -35,7 +35,6 @@ pub struct Input {
last_input: SignedDecimal,
}


#[derive(Serialize, Deserialize)]
pub struct Output {
value: SignedDecimal,
Expand All @@ -57,5 +56,8 @@ pub fn pid(input_js: JsValue) -> Output {

d = d * pid.d / input.dt;

Output { value: p + i - d, i }
Output {
value: p + i - d,
i,
}
}
9 changes: 4 additions & 5 deletions packages/valence-package/src/services/rebalancer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use auction_package::Pair;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, SignedDecimal, SubMsg, Timestamp, Uint128
coins, Addr, Api, BankMsg, CosmosMsg, Decimal, Env, MessageInfo, SignedDecimal, SubMsg,
Timestamp, Uint128,
};
use cw_utils::{must_pay, Expiration};
use std::borrow::Borrow;
Expand Down Expand Up @@ -535,10 +536,8 @@ mod test {
#[serde(default)]
pub account_type: RebalancerAccountType,
}

let one = Data1 {
trustee: None,
};

let one = Data1 { trustee: None };

let parse = to_json_binary(&one).unwrap();
let two = from_json::<Data2>(&parse).unwrap();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(clippy::all)]
// 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
Expand Down
6 changes: 3 additions & 3 deletions tests/rust-tests/src/tests_rebalancer/test_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ fn test_update_whitelist() {
let whitelist = suite.query_rebalancer_whitelists().unwrap();

// lets make sure the whitelist is what we expect for the tests
assert!(whitelist.denom_whitelist.contains(&ATOM.to_string()));
assert!(whitelist.denom_whitelist.contains(ATOM));
assert!(whitelist.denom_whitelist.len() == 3);
assert!(whitelist
.base_denom_whitelist
Expand All @@ -282,8 +282,8 @@ fn test_update_whitelist() {
.unwrap();

let whitelist = suite.query_rebalancer_whitelists().unwrap();
assert!(!whitelist.denom_whitelist.contains(&ATOM.to_string()));
assert!(!whitelist.denom_whitelist.contains(&NTRN.to_string()));
assert!(!whitelist.denom_whitelist.contains(ATOM));
assert!(!whitelist.denom_whitelist.contains(NTRN));
assert!(whitelist.denom_whitelist.len() == 2);

// remove atom, add random
Expand Down

0 comments on commit 8cbc7d1

Please sign in to comment.