Skip to content

Commit

Permalink
modifications for deviations (#147)
Browse files Browse the repository at this point in the history
* modifications for deviations init

* test fixes

* unit test fixes

* contract query import error fix

* schema modifications

* tc name fix

* resolve duration flag

* contract version change

* updating docs

* merge fixes
  • Loading branch information
dixitaniket authored Aug 11, 2023
1 parent a6d970b commit 3ec74dc
Show file tree
Hide file tree
Showing 12 changed files with 265 additions and 144 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
cosmwasm/artifacts
cosmwasm/target
cw-relayer/build
cw-relayer/build

# ide files
.idea
4 changes: 2 additions & 2 deletions cosmwasm/Cargo.lock

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

12 changes: 6 additions & 6 deletions cosmwasm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,15 +186,15 @@ pub struct RefMedianData {

### DeviationData

`RefData` is the struct that is returned when querying with `GetDeviationRef` or `GetDeviationRefBulk` where the
bulk variant returns `Vec<RefData>`
`RefDeviationData` is the struct that is returned when querying with `GetDeviationRef` or `GetDeviationRefBulk` where the
bulk variant returns `Vec<RefDeviationData>`

`RefData` is defined as:
`RefDeviationData` is defined as:

```rust
pub struct RefData {
// Rate of an asset relative to USD (deviation of assets when used with deviation queries)
pub rate: Uint64,
pub struct RefDeviationData {
// Deviation Rates of an asset relative to USD
pub rates: Vec<Uint64>,
// The resolve time of the request ID
pub resolve_time: Uint64,
// The request ID where the rate was derived from
Expand Down
2 changes: 1 addition & 1 deletion cosmwasm/contracts/price-feed/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
authors = ["ojonetwork"]
edition = "2021"
name = "std-reference"
version = "0.1.3"
version = "0.1.6"

exclude = [
"contract.wasm",
Expand Down
5 changes: 3 additions & 2 deletions cosmwasm/contracts/price-feed/examples/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::fs::create_dir_all;
use cosmwasm_schema::{export_schema, remove_schemas, schema_for};

use std_reference::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use std_reference::state::{RefData, ReferenceData, RefMedianData};
use std_reference::state::{RefData, RefMedianData, ReferenceData,RefDeviationData};

fn main() {
let mut out_dir = current_dir().unwrap();
Expand All @@ -17,6 +17,7 @@ fn main() {
export_schema(&schema_for!(ExecuteMsg), &out_dir);
export_schema(&schema_for!(QueryMsg), &out_dir);
export_schema(&schema_for!(RefData), &out_dir);
export_schema(&schema_for!(ReferenceData), &out_dir);
export_schema(&schema_for!(RefMedianData), &out_dir);
export_schema(&schema_for!(RefDeviationData), &out_dir);
export_schema(&schema_for!(ReferenceData), &out_dir);
}
78 changes: 41 additions & 37 deletions cosmwasm/contracts/price-feed/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use semver::Version;
use crate::errors::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg};
use crate::state::{
RefData, RefMedianData, ReferenceData, ADMIN, DEVIATIONDATA, MEDIANREFDATA, MEDIANSTATUS,
REFDATA, RELAYERS,
RefData, RefDeviationData, RefMedianData, ReferenceData, ADMIN, DEVIATIONDATA, MEDIANREFDATA,
MEDIANSTATUS, REFDATA, RELAYERS,
};

const E0: Uint64 = Uint64::zero();
Expand Down Expand Up @@ -288,7 +288,7 @@ fn execute_force_relay_historical_median(
fn execute_relay_historical_deviation(
deps: DepsMut,
info: MessageInfo,
symbol_rates: Vec<(String, Uint64)>,
symbol_rates: Vec<(String, Vec<Uint64>)>,
resolve_time: Uint64,
request_id: Uint64,
) -> Result<Response, ContractError> {
Expand All @@ -301,7 +301,7 @@ fn execute_relay_historical_deviation(
}

// Saves price data
for (symbol, rate) in symbol_rates {
for (symbol, rates) in symbol_rates {
if let Some(existing_refdata) = DEVIATIONDATA.may_load(deps.storage, &symbol)? {
if existing_refdata.resolve_time >= resolve_time {
continue;
Expand All @@ -311,7 +311,7 @@ fn execute_relay_historical_deviation(
DEVIATIONDATA.save(
deps.storage,
&symbol,
&RefData::new(rate, resolve_time, request_id),
&RefDeviationData::new(rates, resolve_time, request_id),
)?
}

Expand All @@ -321,7 +321,7 @@ fn execute_relay_historical_deviation(
fn execute_force_relay_historical_deviation(
deps: DepsMut,
info: MessageInfo,
symbol_rates: Vec<(String, Uint64)>,
symbol_rates: Vec<(String, Vec<Uint64>)>,
resolve_time: Uint64,
request_id: Uint64,
) -> Result<Response, ContractError> {
Expand All @@ -334,11 +334,11 @@ fn execute_force_relay_historical_deviation(
}

// Saves price data
for (symbol, rate) in symbol_rates {
for (symbol, rates) in symbol_rates {
DEVIATIONDATA.save(
deps.storage,
&symbol,
&RefData::new(rate, resolve_time, request_id),
&RefDeviationData::new(rates, resolve_time, request_id),
)?
}

Expand Down Expand Up @@ -409,7 +409,7 @@ fn query_reference_data_bulk(
// can only support USD
fn query_median_ref(deps: Deps, symbol: &str) -> StdResult<RefMedianData> {
if !MEDIANSTATUS.load(deps.storage)? {
return Err(StdError::generic_err ("MEDIAN DISABLED"));
return Err(StdError::generic_err("MEDIAN DISABLED"));
}

if symbol == "USD" {
Expand All @@ -426,15 +426,15 @@ fn query_median_ref_data_bulk(deps: Deps, symbols: &[String]) -> StdResult<Vec<R
.collect()
}

fn query_deviation_ref(deps: Deps, symbol: &str) -> StdResult<RefData> {
fn query_deviation_ref(deps: Deps, symbol: &str) -> StdResult<RefDeviationData> {
if symbol == "USD" {
Ok(RefData::new(E0, Uint64::MAX, Uint64::zero()))
Ok(RefDeviationData::new(vec![E0], Uint64::MAX, Uint64::zero()))
} else {
DEVIATIONDATA.load(deps.storage, symbol)
}
}

fn query_deviation_ref_bulk(deps: Deps, symbols: &[String]) -> StdResult<Vec<RefData>> {
fn query_deviation_ref_bulk(deps: Deps, symbols: &[String]) -> StdResult<Vec<RefDeviationData>> {
symbols
.iter()
.map(|symbol| query_deviation_ref(deps, symbol))
Expand Down Expand Up @@ -925,10 +925,7 @@ mod tests {
// Check if relay was successful
let err = query_median_ref_data_bulk(deps.as_ref(), &symbols.clone()).unwrap_err();

assert_eq!(
err,
StdError::generic_err ("MEDIAN DISABLED")
);
assert_eq!(err, StdError::generic_err("MEDIAN DISABLED"));
}

#[test]
Expand Down Expand Up @@ -1015,9 +1012,14 @@ mod tests {
.map(|r| Uint64::new(*r))
.collect::<Vec<Uint64>>();

let symbol_rates: Vec<(String, Vec<Uint64>)> = symbols
.iter()
.zip(std::iter::repeat(rates.clone()))
.map(|(s, r)| (s.to_owned(), r))
.collect();

let msg = RelayHistoricalDeviation {
symbol_rates: zip(symbols.clone(), rates.clone())
.collect::<Vec<(String, Uint64)>>(),
symbol_rates: symbol_rates.clone(),
resolve_time: Uint64::from(10u64),
request_id: Uint64::one(),
};
Expand All @@ -1027,13 +1029,9 @@ mod tests {
let reference_datas =
query_deviation_ref_bulk(deps.as_ref(), &symbols.clone()).unwrap();

let retrieved_rates = reference_datas
.clone()
.iter()
.map(|r| r.rate)
.collect::<Vec<Uint64>>();

assert_eq!(retrieved_rates, rates);
for (expected, actual) in symbol_rates.iter().zip(reference_datas.iter()) {
assert_eq!(expected.1, actual.rates)
}
}

#[test]
Expand All @@ -1050,14 +1048,19 @@ mod tests {
.into_iter()
.map(|s| s.to_string())
.collect::<Vec<String>>();
let deviations = [1000, 2000, 3000]
let rates = [1000, 2000, 3000]
.iter()
.map(|r| Uint64::new(*r))
.collect::<Vec<Uint64>>();

let symbol_rates: Vec<(String, Vec<Uint64>)> = symbols
.iter()
.zip(std::iter::repeat(rates.clone()))
.map(|(s, r)| (s.to_owned(), r))
.collect();

let msg = ForceRelayHistoricalDeviation {
symbol_rates: zip(symbols.clone(), deviations.clone())
.collect::<Vec<(String, Uint64)>>(),
symbol_rates: symbol_rates.clone(),
resolve_time: Uint64::from(100u64),
request_id: Uint64::from(2u64),
};
Expand All @@ -1071,9 +1074,14 @@ mod tests {
.map(|r| Uint64::new(*r))
.collect::<Vec<Uint64>>();

let symbol_rates: Vec<(String, Vec<Uint64>)> = symbols
.iter()
.zip(std::iter::repeat(forced_deviations.clone()))
.map(|(s, r)| (s.to_owned(), r))
.collect();

let msg = ForceRelayHistoricalDeviation {
symbol_rates: zip(symbols.clone(), forced_deviations.clone())
.collect::<Vec<(String, Uint64)>>(),
symbol_rates: symbol_rates.clone(),
resolve_time: Uint64::from(10u64),
request_id: Uint64::zero(),
};
Expand All @@ -1083,13 +1091,9 @@ mod tests {
let reference_datas =
query_deviation_ref_bulk(deps.as_ref(), &symbols.clone()).unwrap();

let retrieved_rates = reference_datas
.clone()
.iter()
.map(|r| r.rate)
.collect::<Vec<Uint64>>();

assert_eq!(retrieved_rates, forced_deviations);
for (expected, actual) in symbol_rates.iter().zip(reference_datas.iter()) {
assert_eq!(expected.1, actual.rates)
}
}

#[test]
Expand Down
23 changes: 11 additions & 12 deletions cosmwasm/contracts/price-feed/src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use cosmwasm_schema::{cw_serde, QueryResponses};
use cosmwasm_std::Uint64;

use crate::state::{RefData, RefMedianData, ReferenceData};
use crate::state::{RefData,RefDeviationData,RefMedianData,ReferenceData};

#[cw_serde]
pub struct InstantiateMsg {}
Expand Down Expand Up @@ -44,7 +43,7 @@ pub enum ExecuteMsg {
// Request ID of the results on Ojo
request_id: Uint64,
},
// Relays a vector of symbols and their corresponding rates
// Relays a vector of symbols and their corresponding median rates
RelayHistoricalMedian {
// A vector of symbols and their corresponding rates where:
// symbol_rate := (symbol, rate)
Expand All @@ -57,9 +56,9 @@ pub enum ExecuteMsg {
// Request ID of the results on Ojo
request_id: Uint64,
},
// Relays a vector of symbols and their corresponding rates
// Relays a vector of symbols and their corresponding deviation rates
RelayHistoricalDeviation {
symbol_rates: Vec<(String, Uint64)>,
symbol_rates: Vec<(String, Vec<Uint64>)>,
resolve_time: Uint64,
// Request ID of the results on Ojo
request_id: Uint64,
Expand All @@ -70,15 +69,15 @@ pub enum ExecuteMsg {
resolve_time: Uint64,
request_id: Uint64,
},
// Same as Relay but without the resolve_time guard
// Same as RelayHistoricalMedian but without the resolve_time guard
ForceRelayHistoricalMedian {
symbol_rates: Vec<(String, Vec<Uint64>)>,
resolve_time: Uint64,
request_id: Uint64,
},
// Relays a vector of symbols and their corresponding deviations
// Same as RelayHistoricalDeviation but without the resolve_time guard
ForceRelayHistoricalDeviation {
symbol_rates: Vec<(String, Uint64)>,
symbol_rates: Vec<(String, Vec<Uint64>)>,
resolve_time: Uint64,
// Request ID of the results on Ojo
request_id: Uint64,
Expand Down Expand Up @@ -133,15 +132,15 @@ pub enum QueryMsg {
// Vector of Symbols to query
symbols: Vec<String>,
},
#[returns(RefData)]
// Returns the deviation RefData of a given symbol
#[returns(RefDeviationData)]
// Returns the deviation RefDeviationData of a given symbol
GetDeviationRef {
// Symbol to query
symbol: String,
},

#[returns(Vec < RefData >)]
// Returns the deviation RefData of the given symbols
#[returns(Vec < RefDeviationData >)]
// Returns the deviation RefDeviationData of the given symbols
GetDeviationRefBulk {
// Vector of Symbols to query
symbols: Vec<String>,
Expand Down
22 changes: 21 additions & 1 deletion cosmwasm/contracts/price-feed/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub const MEDIANREFDATA: Map<&str, RefMedianData> = Map::new("medianrefdata");
pub const MEDIANSTATUS: Item<bool> = Item::new("medianstatus");

// Used to store Deviation data
pub const DEVIATIONDATA: Map<&str, RefData> = Map::new("deviationdata");
pub const DEVIATIONDATA: Map<&str, RefDeviationData> = Map::new("deviationdata");

#[cw_serde]
pub struct RefData {
Expand Down Expand Up @@ -61,6 +61,26 @@ impl RefMedianData {
}
}

#[cw_serde]
pub struct RefDeviationData {
// Deviation Rates of an asset relative to USD
pub rates: Vec<Uint64>,
// The resolve time of the request ID
pub resolve_time: Uint64,
// The request ID where the rate was derived from
pub request_id: Uint64,
}

impl RefDeviationData {
pub fn new(rates: Vec<Uint64>, resolve_time: Uint64, request_id: Uint64) -> Self {
RefDeviationData {
rates,
resolve_time,
request_id,
}
}
}

#[cw_serde]
pub struct ReferenceData {
// Pair rate e.g. rate of BTC/USD
Expand Down
6 changes: 5 additions & 1 deletion cw-relayer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ each msg above has a forced version which ignores the resolve duration present i

#### Median Duration
- median duration determines how frequently median prices are posted to the contract
- if median duration is set to 0, then median prices are not posted to the contract
- if median duration is set to 0, then median prices are not posted to the contract

### Links to other supported implementations
- [Secret Network](https://github.com/ojo-network/contracts/tree/secret)
- [Evm](https://github.com/ojo-network/contracts/tree/evm)
Loading

0 comments on commit 3ec74dc

Please sign in to comment.