Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

apy #945

Open
wants to merge 31 commits into
base: main
Choose a base branch
from
Open

apy #945

Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
760 changes: 760 additions & 0 deletions crates/subgraph/src/apy.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/subgraph/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod apy;
mod cynic_client;
mod orderbook_client;
mod pagination;
Expand Down
6 changes: 6 additions & 0 deletions crates/subgraph/src/orderbook_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ pub enum OrderbookSubgraphClientError {
PaginationClientError(#[from] PaginationClientError),
#[error(transparent)]
ParseError(#[from] alloy::primitives::ruint::ParseError),
#[error(transparent)]
ParseBigIntConversionError(#[from] alloy::primitives::BigIntConversionError),
#[error(transparent)]
ParseFloatError(#[from] std::num::ParseFloatError),
#[error(transparent)]
ParseIntError(#[from] std::num::ParseIntError),
}

pub struct OrderbookSubgraphClient {
Expand Down
6 changes: 3 additions & 3 deletions crates/subgraph/src/types/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ pub struct OrderStructPartialTrade {
pub id: Bytes,
}

#[derive(cynic::QueryFragment, Debug, Serialize, Clone, PartialEq)]
#[derive(cynic::QueryFragment, Debug, Serialize, Clone, PartialEq, Eq, Hash)]
#[cynic(graphql_type = "ERC20")]
#[typeshare]
pub struct Erc20 {
Expand All @@ -305,11 +305,11 @@ pub struct AddOrder {
pub transaction: Transaction,
}

#[derive(cynic::Scalar, Debug, Clone, PartialEq)]
#[derive(cynic::Scalar, Debug, Clone, PartialEq, Eq, Hash)]
#[typeshare]
pub struct BigInt(pub String);

#[derive(cynic::Scalar, Debug, Clone, PartialEq)]
#[derive(cynic::Scalar, Debug, Clone, PartialEq, Eq, Hash)]
#[typeshare]
pub struct Bytes(pub String);

Expand Down
191 changes: 191 additions & 0 deletions crates/subgraph/src/types/impls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
use super::common::*;
use crate::utils::{one_18, to_18_decimals};
use alloy::primitives::{
utils::{ParseUnits, UnitsError},
I256, U256,
};
use std::str::FromStr;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ParseUnitsError {
#[error(transparent)]
UnitsError(#[from] UnitsError),
#[error(transparent)]
ParseUnsignedError(#[from] alloy::primitives::ruint::ParseError),
#[error(transparent)]
ParseSignedError(#[from] alloy::primitives::ParseSignedError),
#[error(transparent)]
BigIntConversionError(#[from] alloy::primitives::BigIntConversionError),
}

impl Trade {
/// Converts this trade's input to 18 point decimals in U256/I256
pub fn input_to_18_decimals(&self) -> Result<ParseUnits, ParseUnitsError> {
Ok(to_18_decimals(
ParseUnits::U256(U256::from_str(&self.input_vault_balance_change.amount.0)?),
self.input_vault_balance_change
.vault
.token
.decimals
.as_ref()
.map(|v| v.0.as_str())
.unwrap_or("18"),
)?)
}

/// Converts this trade's output to 18 point decimals in U256/I256
pub fn output_to_18_decimals(&self) -> Result<ParseUnits, ParseUnitsError> {
Ok(to_18_decimals(
ParseUnits::I256(I256::from_str(&self.output_vault_balance_change.amount.0)?),
self.output_vault_balance_change
.vault
.token
.decimals
.as_ref()
.map(|v| v.0.as_str())
.unwrap_or("18"),
)?)
}

/// Calculates the trade's I/O ratio
pub fn ratio(&self) -> Result<U256, ParseUnitsError> {
Ok(self
.input_to_18_decimals()?
.get_absolute()
.saturating_mul(one_18().get_absolute())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as below

.checked_div(
self.output_to_18_decimals()?
.get_signed()
.saturating_neg()
.try_into()?,
)
.unwrap_or(U256::MAX))
}

/// Calculates the trade's O/I ratio (inverse)
pub fn inverse_ratio(&self) -> Result<U256, ParseUnitsError> {
Ok(
TryInto::<U256>::try_into(self.output_to_18_decimals()?.get_signed().saturating_neg())?
.saturating_mul(one_18().get_absolute())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as below

.checked_div(self.input_to_18_decimals()?.get_absolute())
.unwrap_or(U256::MAX),
)
}
}

#[cfg(test)]
mod test {
use super::*;
use crate::types::common::{
BigInt, Bytes, Orderbook, TradeEvent, TradeStructPartialOrder, TradeVaultBalanceChange,
Transaction, VaultBalanceChangeVault,
};
use alloy::primitives::Address;

#[test]
fn test_input_to_18_decimals() {
let result = get_trade().input_to_18_decimals().unwrap();
let expected = U256::from_str("3000000000000000000").unwrap();
assert_eq!(result.get_absolute(), expected);
}

#[test]
fn test_output_to_18_decimals() {
let result = get_trade().output_to_18_decimals().unwrap();
let expected = I256::from_str("-6000000000000000000").unwrap();
assert_eq!(result.get_signed(), expected);
}

#[test]
fn test_ratio() {
let result = get_trade().ratio().unwrap();
let expected = U256::from_str("500000000000000000").unwrap();
assert_eq!(result, expected);
}

#[test]
fn test_inverse_ratio() {
let result = get_trade().inverse_ratio().unwrap();
let expected = U256::from_str("2000000000000000000").unwrap();
assert_eq!(result, expected);
}

// helper to get trade struct
fn get_trade() -> Trade {
let token_address = Address::from_slice(&[0x11u8; 20]);
let token = Erc20 {
id: Bytes(token_address.to_string()),
address: Bytes(token_address.to_string()),
name: Some("Token1".to_string()),
symbol: Some("Token1".to_string()),
decimals: Some(BigInt(6.to_string())),
};
let input_trade_vault_balance_change = TradeVaultBalanceChange {
id: Bytes("".to_string()),
__typename: "".to_string(),
amount: BigInt("3000000".to_string()),
new_vault_balance: BigInt("".to_string()),
old_vault_balance: BigInt("".to_string()),
vault: VaultBalanceChangeVault {
id: Bytes("".to_string()),
vault_id: BigInt("".to_string()),
token: token.clone(),
},
timestamp: BigInt("".to_string()),
transaction: Transaction {
id: Bytes("".to_string()),
from: Bytes("".to_string()),
block_number: BigInt("".to_string()),
timestamp: BigInt("".to_string()),
},
orderbook: Orderbook {
id: Bytes("".to_string()),
},
};
let output_trade_vault_balance_change = TradeVaultBalanceChange {
id: Bytes("".to_string()),
__typename: "".to_string(),
amount: BigInt("-6000000".to_string()),
new_vault_balance: BigInt("".to_string()),
old_vault_balance: BigInt("".to_string()),
vault: VaultBalanceChangeVault {
id: Bytes("".to_string()),
vault_id: BigInt("".to_string()),
token: token.clone(),
},
timestamp: BigInt("".to_string()),
transaction: Transaction {
id: Bytes("".to_string()),
from: Bytes("".to_string()),
block_number: BigInt("".to_string()),
timestamp: BigInt("".to_string()),
},
orderbook: Orderbook {
id: Bytes("".to_string()),
},
};
Trade {
id: Bytes("".to_string()),
trade_event: TradeEvent {
transaction: Transaction {
id: Bytes("".to_string()),
from: Bytes("".to_string()),
block_number: BigInt("".to_string()),
timestamp: BigInt("".to_string()),
},
sender: Bytes("".to_string()),
},
output_vault_balance_change: output_trade_vault_balance_change,
input_vault_balance_change: input_trade_vault_balance_change,
order: TradeStructPartialOrder {
id: Bytes("".to_string()),
order_hash: Bytes("".to_string()),
},
timestamp: BigInt("".to_string()),
orderbook: Orderbook {
id: Bytes("".to_string()),
},
}
}
}
1 change: 1 addition & 0 deletions crates/subgraph/src/types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod common;
pub mod impls;
pub mod order;
pub mod order_detail_traits;
pub mod order_trade;
Expand Down
62 changes: 62 additions & 0 deletions crates/subgraph/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,67 @@
use alloy::primitives::utils::{format_units, parse_units, ParseUnits, Unit, UnitsError};
use chrono::TimeDelta;

mod order_id;
mod slice_list;

pub use order_id::*;
pub use slice_list::*;

/// Returns 18 point decimals 1 as I256/U256
pub fn one_18() -> ParseUnits {
rouzwelt marked this conversation as resolved.
Show resolved Hide resolved
parse_units("1", 18).unwrap()
}

/// Returns YEAR as 18 point decimals as I256/U256
pub fn year_18() -> ParseUnits {
parse_units(&TimeDelta::days(365).num_seconds().to_string(), 18).unwrap()
}

/// Converts a U256/I256 value to a 18 fixed point U256/I256 given the decimals point
pub fn to_18_decimals<T: TryInto<Unit, Error = UnitsError>>(
amount: ParseUnits,
decimals: T,
) -> Result<ParseUnits, UnitsError> {
parse_units(&format_units(amount, decimals)?, 18)
}

#[cfg(test)]
mod test {
use super::*;
use alloy::primitives::{I256, U256};
use std::str::FromStr;

#[test]
fn test_one() {
let result = one_18();
let expected_signed = I256::from_str("1_000_000_000_000_000_000").unwrap();
let expected_absolute = U256::from_str("1_000_000_000_000_000_000").unwrap();
assert_eq!(result.get_signed(), expected_signed);
assert_eq!(result.get_absolute(), expected_absolute);
}

#[test]
fn test_year_18_decimals() {
const YEAR: u64 = 60 * 60 * 24 * 365;
let result = year_18();
let expected_signed = I256::try_from(YEAR)
.unwrap()
.saturating_mul(one_18().get_signed());
let expected_absolute = U256::from(YEAR).saturating_mul(one_18().get_absolute());
assert_eq!(result.get_signed(), expected_signed);
assert_eq!(result.get_absolute(), expected_absolute);
}

#[test]
fn test_to_18_decimals() {
let value = ParseUnits::I256(I256::from_str("-123456789").unwrap());
let result = to_18_decimals(value, 5).unwrap();
let expected = ParseUnits::I256(I256::from_str("-1234567890000000000000").unwrap());
assert_eq!(result, expected);

let value = ParseUnits::U256(U256::from_str("123456789").unwrap());
let result = to_18_decimals(value, 12).unwrap();
let expected = ParseUnits::U256(U256::from_str("123456789000000").unwrap());
assert_eq!(result, expected);
}
}
14 changes: 7 additions & 7 deletions crates/subgraph/src/vol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ use serde::{Deserialize, Serialize};
use std::str::FromStr;
use typeshare::typeshare;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct VaultVolume {
id: String,
token: Erc20,
pub id: String,
pub token: Erc20,
#[typeshare(typescript(type = "string"))]
total_in: U256,
pub total_in: U256,
#[typeshare(typescript(type = "string"))]
total_out: U256,
pub total_out: U256,
#[typeshare(typescript(type = "string"))]
total_vol: U256,
pub total_vol: U256,
#[typeshare(typescript(type = "string"))]
net_vol: I256,
pub net_vol: I256,
}

/// Get the vaults volume from array of trades
Expand Down
2 changes: 1 addition & 1 deletion flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
cargo install --git https://github.com/tomjw64/typeshare --rev 556b44aafd5304eedf17206800f69834e3820b7c
export PATH=$PATH:$CARGO_HOME/bin

typeshare crates/subgraph/src/types/common.rs crates/subgraph/src/types/order.rs crates/subgraph/src/types/vault.rs crates/subgraph/src/types/order_trade.rs crates/common/src/types/order_detail_extended.rs crates/subgraph/src/vol.rs --lang=typescript --output-file=tauri-app/src/lib/typeshare/subgraphTypes.ts;
typeshare crates/subgraph/src/types/common.rs crates/subgraph/src/types/order.rs crates/subgraph/src/types/vault.rs crates/subgraph/src/types/order_trade.rs crates/common/src/types/order_detail_extended.rs crates/subgraph/src/vol.rs crates/subgraph/src/apy.rs --lang=typescript --output-file=tauri-app/src/lib/typeshare/subgraphTypes.ts;

typeshare crates/settings/src/parse.rs --lang=typescript --output-file=tauri-app/src/lib/typeshare/appSettings.ts;
typeshare lib/rain.interpreter/crates/eval/src/trace.rs crates/common/src/fuzz/mod.rs crates/settings/src/config_source.rs crates/settings/src/config.rs crates/settings/src/plot_source.rs crates/settings/src/chart.rs crates/settings/src/deployer.rs crates/settings/src/network.rs crates/settings/src/order.rs crates/settings/src/orderbook.rs crates/settings/src/scenario.rs crates/settings/src/blocks.rs crates/settings/src/token.rs crates/settings/src/deployment.rs --lang=typescript --output-file=tauri-app/src/lib/typeshare/config.ts;
Expand Down
21 changes: 21 additions & 0 deletions tauri-app/src-tauri/src/commands/order_take.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::error::CommandResult;
use rain_orderbook_common::{
csv::TryIntoCsv, subgraph::SubgraphArgs, types::FlattenError, types::OrderTakeFlattened,
};
use rain_orderbook_subgraph_client::apy::{get_order_apy, OrderAPY};
use rain_orderbook_subgraph_client::vol::VaultVolume;
use rain_orderbook_subgraph_client::{types::common::*, PaginationArgs};
use std::fs;
Expand Down Expand Up @@ -79,3 +80,23 @@ pub async fn order_trades_count(
.await?
.len())
}

#[tauri::command]
pub async fn order_apy(
order_id: String,
subgraph_args: SubgraphArgs,
start_timestamp: Option<u64>,
end_timestamp: Option<u64>,
) -> CommandResult<OrderAPY> {
let client = subgraph_args.to_subgraph_client().await?;
let order = client.order_detail(order_id.clone().into()).await?;
let trades = client
.order_trades_list_all(order_id.into(), start_timestamp, end_timestamp)
.await?;
Ok(get_order_apy(
&order,
&trades,
start_timestamp,
end_timestamp,
)?)
}
6 changes: 4 additions & 2 deletions tauri-app/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use commands::order::{
};
use commands::order_quote::{batch_order_quotes, debug_order_quote};
use commands::order_take::{
order_trades_count, order_trades_list, order_trades_list_write_csv, order_vaults_volume,
order_apy, order_trades_count, order_trades_list, order_trades_list_write_csv,
order_vaults_volume,
};
use commands::trade_debug::debug_trade;
use commands::vault::{
Expand Down Expand Up @@ -82,7 +83,8 @@ fn run_tauri_app() {
get_app_commit_sha,
validate_raindex_version,
order_vaults_volume,
order_trades_count
order_trades_count,
order_apy,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
Loading
Loading