Skip to content

Commit

Permalink
Merge pull request #299 from SorellaLabs/will/back-139-ensure-ray-is-…
Browse files Browse the repository at this point in the history
…used-everywhere

Will/back 139 ensure ray is used everywhere
  • Loading branch information
Will-Smith11 authored Dec 16, 2024
2 parents 253a4f4 + ebf9c72 commit 16ff405
Show file tree
Hide file tree
Showing 17 changed files with 234 additions and 118 deletions.
8 changes: 2 additions & 6 deletions contracts/test/Angstrom.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ contract AngstromTest is BaseTest {

function setUp() public {
uni = new PoolManager(address(0));
angstrom = Angstrom(
deployAngstrom(type(Angstrom).creationCode, uni, controller)
);
angstrom = Angstrom(deployAngstrom(type(Angstrom).creationCode, uni, controller));
domainSeparator = computeDomainSeparator(address(angstrom));

vm.prank(controller);
Expand Down Expand Up @@ -103,9 +101,7 @@ contract AngstromTest is BaseTest {
bundle.assets[1].take += 10.0e18;
bundle.assets[1].settle += 10.0e18;

bytes memory payload = bundle.encode(
rawGetConfigStore(address(angstrom))
);
bytes memory payload = bundle.encode(rawGetConfigStore(address(angstrom)));
vm.prank(node);
angstrom.execute(payload);
}
Expand Down
4 changes: 2 additions & 2 deletions crates/consensus/src/rounds/proposal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use std::{
};

use alloy::{
network::TransactionBuilder, providers::Provider,
rpc::types::TransactionRequest, sol_types::SolCall, transports::Transport
network::TransactionBuilder, providers::Provider, rpc::types::TransactionRequest,
sol_types::SolCall, transports::Transport
};
use angstrom_network::manager::StromConsensusEvent;
use angstrom_types::{
Expand Down
1 change: 0 additions & 1 deletion crates/matching-engine/src/book/sort.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

use super::BookOrder;

/// There are lots of different ways we can sort the orders we get in, so let's
Expand Down
11 changes: 9 additions & 2 deletions crates/matching-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ use angstrom_types::{
matching::uniswap::PoolSnapshot,
orders::PoolSolution,
primitive::{PoolId, UniswapPoolRegistry},
sol_bindings::{grouped_orders::OrderWithStorageData, rpc_orders::TopOfBlockOrder}
sol_bindings::{
grouped_orders::OrderWithStorageData, rpc_orders::TopOfBlockOrder, RawPoolOrder
}
};
use book::{BookOrder, OrderBook};
use futures_util::future::BoxFuture;
Expand Down Expand Up @@ -39,7 +41,12 @@ pub trait MatchingEngineHandle: Send + Sync + Clone + Unpin + 'static {
}

pub fn build_book(id: PoolId, amm: Option<PoolSnapshot>, orders: HashSet<BookOrder>) -> OrderBook {
let (bids, asks) = orders.into_iter().partition(|o| o.is_bid);
let (mut bids, mut asks): (Vec<BookOrder>, Vec<BookOrder>) =
orders.into_iter().partition(|o| o.is_bid);

// assert bids decreasing and asks increasing
bids.sort_by_key(|b| std::cmp::Reverse(b.limit_price()));
asks.sort_by_key(|a| a.limit_price());

OrderBook::new(id, amm, bids, asks, Some(book::sort::SortStrategy::ByPriceByVolume))
}
Expand Down
8 changes: 4 additions & 4 deletions crates/types/src/contract_payloads/angstrom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1016,8 +1016,8 @@ impl AngstromBundle {
rewards_update
});
// calculate the shared amount of gas in token 0 to share over this pool
let delegated_amount_in_token_0: U256 =
*(Ray::from(*conversion_rate_to_token0) * Ray::from(U256::from(shared_gas_in_wei)));
let delegated_amount_in_token_0 =
(*conversion_rate_to_token0 * U256::from(shared_gas_in_wei)).scale_out_of_ray();

// Add the ToB order to our tob order list - This is currently converting
// between two ToB order formats
Expand Down Expand Up @@ -1092,14 +1092,14 @@ impl AngstromBundle {
pub struct BundleGasDetails {
/// a map (sorted tokens) of how much of token0 in gas is needed per unit of
/// gas
token_price_per_wei: HashMap<(Address, Address), U256>,
token_price_per_wei: HashMap<(Address, Address), Ray>,
/// total gas to execute the bundle on angstrom
total_gas_cost_wei: u64
}

impl BundleGasDetails {
pub fn new(
token_price_per_wei: HashMap<(Address, Address), U256>,
token_price_per_wei: HashMap<(Address, Address), Ray>,
total_gas_cost_wei: u64
) -> Self {
Self { token_price_per_wei, total_gas_cost_wei }
Expand Down
1 change: 0 additions & 1 deletion crates/types/src/matching/composite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,6 @@ impl<'a> CompositeOrder<'a> {

#[cfg(test)]
mod tests {


use super::*;
use crate::matching::{
Expand Down
17 changes: 11 additions & 6 deletions crates/types/src/matching/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,39 @@ use alloy::primitives::U256;

mod composite;
pub use composite::CompositeOrder;
mod debt;
pub mod debt;
pub use debt::{Debt, DebtType};
pub mod match_estimate_response;
mod math;
mod ray;
mod sqrtprice;
mod tokens;
pub mod uniswap;
use malachite::{
num::{arithmetic::traits::PowerOf2, conversion::traits::FromSciString},
Natural
};
pub use ray::Ray;
pub use sqrtprice::SqrtPriceX96;
pub use tokens::TokenQuantity;

fn const_1e27() -> &'static Natural {
pub use super::sol_bindings::Ray;

pub fn const_1e27() -> &'static Natural {
static TWENTYSEVEN: OnceLock<Natural> = OnceLock::new();
TWENTYSEVEN.get_or_init(|| Natural::from_sci_string("1e27").unwrap())
}

fn const_2_192() -> &'static Natural {
pub fn const_1e54() -> &'static Natural {
static FIFTYFOUR: OnceLock<Natural> = OnceLock::new();
FIFTYFOUR.get_or_init(|| Natural::from_sci_string("1e54").unwrap())
}

pub fn const_2_192() -> &'static Natural {
static ONENINETWO: OnceLock<Natural> = OnceLock::new();
ONENINETWO.get_or_init(|| Natural::power_of_2(192))
}

#[allow(unused)]
fn const_2_96() -> &'static Natural {
pub fn const_2_96() -> &'static Natural {
static ONENINETWO: OnceLock<Natural> = OnceLock::new();
ONENINETWO.get_or_init(|| Natural::power_of_2(96))
}
Expand Down
1 change: 0 additions & 1 deletion crates/types/src/matching/uniswap/poolprice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,6 @@ mod test {
println!("Result: {}", result);
let valid = debt.valid_for_price(amm.current_price().as_ray());
println!("Valid: {}", valid);

}

#[test]
Expand Down
8 changes: 4 additions & 4 deletions crates/types/src/pair_with_price.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use alloy::primitives::{Address, U256};
use alloy::primitives::Address;
use futures::{Stream, StreamExt};
use pade::PadeDecode;
use reth_provider::CanonStateNotificationStream;

use crate::contract_payloads::angstrom::AngstromBundle;
use crate::{contract_payloads::angstrom::AngstromBundle, sol_bindings::Ray};

/// represents the price settled on angstrom between two tokens
#[derive(Debug, Clone, Copy)]
pub struct PairsWithPrice {
pub token0: Address,
pub token1: Address,
pub price_1_over_0: U256,
pub price_1_over_0: Ray,
pub block_num: u64
}

Expand All @@ -25,7 +25,7 @@ impl PairsWithPrice {
.map(|pair| Self {
token0: bundle.assets[pair.index0 as usize].addr,
token1: bundle.assets[pair.index1 as usize].addr,
price_1_over_0: pair.price_1over0,
price_1_over_0: Ray::from(pair.price_1over0),
block_num
})
.collect::<Vec<_>>()
Expand Down
2 changes: 2 additions & 0 deletions crates/types/src/sol_bindings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ pub mod rpc_orders;
#[cfg(feature = "testnet")]
pub mod testnet;
pub use ext::*;
pub mod ray;
pub use ray::*;
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::{
ops::{Add, AddAssign, Deref, Mul, Sub, SubAssign},
iter::Sum,
ops::{Add, AddAssign, Deref, Sub, SubAssign},
sync::OnceLock
};

Expand All @@ -16,8 +17,10 @@ use malachite::{
use serde::{Deserialize, Serialize};
use uniswap_v3_math::tick_math::{MAX_SQRT_RATIO, MIN_SQRT_RATIO};

use super::{const_2_192, uniswap::PoolPrice, MatchingPrice, SqrtPriceX96};
use crate::matching::const_1e27;
use super::rpc_orders::SolRay;
use crate::matching::{
const_1e27, const_1e54, const_2_192, uniswap::PoolPrice, MatchingPrice, SqrtPriceX96
};

fn max_tick_ray() -> &'static Ray {
static MAX_TICK_PRICE: OnceLock<Ray> = OnceLock::new();
Expand All @@ -29,7 +32,29 @@ fn min_tick_ray() -> &'static Ray {
MIN_TICK_PRICE.get_or_init(|| Ray::from(SqrtPriceX96::from(MIN_SQRT_RATIO)))
}
#[derive(Copy, Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Ray(U256);
pub struct Ray(pub U256);

impl From<SolRay> for Ray {
fn from(value: SolRay) -> Self {
Self(value.into())
}
}

impl Sum for Ray {
fn sum<I: Iterator<Item = Ray>>(iter: I) -> Self {
let mut acc = Ray::default();
for ray in iter {
acc += ray;
}
acc
}
}

impl From<Ray> for SolRay {
fn from(value: Ray) -> Self {
SolRay::from(value.0)
}
}

impl Deref for Ray {
type Target = U256;
Expand Down Expand Up @@ -61,6 +86,22 @@ impl SubAssign for Ray {
}
}

impl std::ops::Mul<U256> for Ray {
type Output = Ray;

fn mul(self, rhs: U256) -> Self::Output {
Ray::from(self.0 * rhs)
}
}

impl std::ops::Div<U256> for Ray {
type Output = Ray;

fn div(self, rhs: U256) -> Self::Output {
Ray::from(self.0 / rhs)
}
}

impl Add for Ray {
type Output = Ray;

Expand All @@ -82,19 +123,6 @@ impl AddAssign for Ray {
*self = Self(self.0 + rhs.0);
}
}
impl Mul for Ray {
type Output = Ray;

#[allow(clippy::suspicious_arithmetic_impl)]
fn mul(self, rhs: Self) -> Self::Output {
let mult: U512 = self.widening_mul(rhs.0);
// div by 1e27
let out = (mult / U512::from(1e27)).into_limbs();

let buf = [out[4], out[5], out[6], out[7]];
Ray::from(U256::from_limbs(buf))
}
}

impl From<U256> for Ray {
fn from(value: U256) -> Self {
Expand All @@ -120,15 +148,6 @@ impl From<usize> for Ray {
}
}

// Can't do this because of something in the blsful crate, annoying!
// trait RayConvert {}

// impl<T: Into<U256> + RayConvert> From<T> for Ray {
// fn from(value: T) -> Self {
// Self(Uint::from(value))
// }
// }

impl From<f64> for Ray {
fn from(value: f64) -> Self {
Self(U256::from((value * (10.0_f64.pow(27))).floor()))
Expand Down Expand Up @@ -208,6 +227,78 @@ impl<'de> Deserialize<'de> for Ray {
impl Ray {
pub const ZERO: Ray = Ray(U256::ZERO);

/// value * 1e27
pub fn scale_to_ray(value: U256) -> Ray {
let value = Natural::from_limbs_asc(value.as_limbs()) * const_1e27();

Ray::from(Uint::from_limbs_slice(&value.to_limbs_asc()))
}

/// value / 1e27
pub fn scale_out_of_ray(self) -> U256 {
let numerator = Natural::from_limbs_asc(self.0.as_limbs());
let denominator: Natural = const_1e27().clone();
let price = Rational::from_naturals(numerator, denominator);
let (res, _): (Natural, _) =
price.rounding_into(malachite::rounding_modes::RoundingMode::Floor);

Uint::from_limbs_slice(&res.into_limbs_asc())
}

/// self * other / ray
pub fn mul_ray_assign(&mut self, other: Ray) {
let p: U512 = self.0.widening_mul(other.0);
let numerator = Natural::from_limbs_asc(p.as_limbs());
let (res, _) =
numerator.div_round(const_1e27(), malachite::rounding_modes::RoundingMode::Floor);
let reslimbs = res.into_limbs_asc();

*self = Ray::from(Uint::from_limbs_slice(&reslimbs));
}

/// self * other / ray
pub fn mul_ray(mut self, other: Ray) -> Ray {
self.mul_ray_assign(other);
self
}

/// self * ray / other
pub fn div_ray_assign(&mut self, other: Ray) {
let numerator = Natural::from_limbs_asc(self.0.as_limbs());
let num = numerator * const_1e27();

let denom = Natural::from_limbs_asc(other.0.as_limbs());
let res = Rational::from_naturals(num, denom);
let (n, _): (Natural, _) = res.rounding_into(RoundingMode::Floor);
let this = U256::from_limbs_slice(&n.to_limbs_asc());

*self = Ray::from(this);
}

/// self * ray / other
pub fn div_ray(mut self, other: Ray) -> Ray {
self.div_ray_assign(other);
self
}

/// 1e54 / self
pub fn inv_ray_assign(&mut self) {
let num = const_1e54().clone();
let denom = Natural::from_limbs_asc(self.0.as_limbs());

let res = Rational::from_naturals(num, denom);
let (n, _): (Natural, _) = res.rounding_into(RoundingMode::Floor);
let this = U256::from_limbs_slice(&n.to_limbs_asc());

*self = Ray::from(this);
}

/// 1e54 / self
pub fn inv_ray(mut self) -> Ray {
self.inv_ray_assign();
self
}

pub fn max_uniswap_price() -> Self {
*max_tick_ray()
}
Expand Down Expand Up @@ -248,7 +339,7 @@ impl Ray {
let p: U512 = self.0.widening_mul(q);
let numerator = Natural::from_limbs_asc(p.as_limbs());
let (res, _) =
numerator.div_round(const_1e27(), malachite::rounding_modes::RoundingMode::Ceiling);
numerator.div_round(const_1e27(), malachite::rounding_modes::RoundingMode::Floor);
let reslimbs = res.into_limbs_asc();
Uint::from_limbs_slice(&reslimbs)
}
Expand Down
Loading

0 comments on commit 16ff405

Please sign in to comment.