Giter Club home page Giter Club logo

cw-injective's People

Contributors

albertchon avatar antekm avatar aursen avatar darainj avatar darashahriari avatar drunkenrandomwalker avatar ewoolsey avatar gorgos avatar jbernal87 avatar kakysha avatar keithbaum avatar kishan-dhakan avatar mankenavenkatesh avatar maurolacy avatar maxrobot avatar pyramation avatar rhaki avatar stackman27 avatar tofel avatar vinhphuctadang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cw-injective's Issues

Create better conversions for FPDecimal and cosmwasm-std math types

An example would be From<Decimal256> for FPDecimal

pub fn into_fp_decimal(value: Decimal256) -> FPDecimal {
    let atomics = value.atomics().to_be_bytes();
    FPDecimal { num: atomics.into(), sign: 1 }
}

but there are many more. As well some conversions seem to be using implementations for Display which likely isn't best practice.

injective-math 0.2.0 - unstable feature

when I try to use

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/workspace-optimizer:0.13.0

it spits out issues about the use of is_some_and.

now version 0.14.0 of the workspace-optimizer doesn't fail.
but then it refuses to upload the wasm generated to injective-888

Create enums or aliases for chain enum types

We currently pass in i32 for chain enum types like the order type or cancellation strategy. Wonder if we instead could use a Rust enum type or use some kind of alias to actually know what the i32 stands for.

add spot market structs to query.rs

pub enum InjectiveQuery {
    // Missing fields 
    SpotMarket {
        market_id: String,
    },
    TraderSpotOrders {
        market_id: String,
        subaccount_id: String,
    },
    SpotMarketInfo {
        market_id: String,
    },
}

[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct SpotLimitOrder {
    pub order_info: OrderInfo,
    pub order_type: i32,
    pub fillable: FPDecimal,
    pub trigger_price: Option<FPDecimal>,
    pub order_hash: String,
}

impl SpotLimitOrder {
    pub fn new(
        fillable: FPDecimal,
        order_hash: String,
        trigger_price: Option<FPDecimal>,
        order_type: i32,
        order_info: OrderInfo,
    ) -> SpotLimitOrder {
        SpotLimitOrder {
            fillable,
            order_hash,
            trigger_price,
            order_type,
            order_info,
        }
    }
}

[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct SpotMarketOrder {
    pub order_info: OrderInfo,
    pub order_type: i32,
    pub fillable: FPDecimal,
    pub trigger_price: Option<FPDecimal>,
    pub order_hash: String,
}

impl SpotMarketOrder {
    pub fn new(
        fillable: FPDecimal,
        order_hash: String,
        trigger_price: Option<FPDecimal>,
        order_type: i32,
        order_info: OrderInfo,
    ) -> SpotLimitOrder {
        SpotLimitOrder {
            fillable,
            order_hash,
            trigger_price,
            order_type,
            order_info,
        }
    }
}

#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TrimmedSpotLimitOrder {
    pub price: FPDecimal,
    pub quantity: FPDecimal,
    pub fillable: FPDecimal,
    pub isBuy: bool,
    pub order_hash: String,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TraderSpotOrdersResponse {
    pub orders: Option<Vec<TrimmedSpotLimitOrder>>,
}

#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct SpotMarket {
    pub ticker: String,
    pub oracle_base: String,
    pub oracle_quote: String,
    #[serde(default)]
    pub oracle_type: i32,
    #[serde(default)]
    pub oracle_scale_factor: u32,
    pub quote_denom: String,
    pub market_id: String,
    pub maker_fee_rate: FPDecimal,
    pub taker_fee_rate: FPDecimal,
    #[serde(default)]
    pub isPerpetual: bool, // this is from DerivativeMarket, not sure if this is necessary
    #[serde(default)]
    pub status: i32,
    pub min_price_tick_size: FPDecimal,
    pub min_quantity_tick_size: FPDecimal,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct DerivativeMarketOrder {
    pub order_info: OrderInfo,
    pub order_type: i32,
    pub margin: FPDecimal,
    pub fillable: FPDecimal,
    pub trigger_price: Option<FPDecimal>,
    pub order_hash: String,
}

impl DerivativeMarketOrder {
    pub fn new(
        margin: FPDecimal,
        fillable: FPDecimal,
        order_hash: String,
        trigger_price: Option<FPDecimal>,
        order_type: i32,
        order_info: OrderInfo,
    ) -> DerivativeLimitOrder {
        DerivativeLimitOrder {
            margin,
            fillable,
            order_hash,
            trigger_price,
            order_type,
            order_info,
        }
    }
    pub fn is_reduce_only(&self) -> bool {
        self.margin.is_zero()
    }
}

DerivativeMarketOrder is possible missing.

Building injective-cosmwasm with `--release` fails

specifically the error is

error[E0432]: unresolved import `test_helpers::testing_helpers`
  --> /Users/ewoolsey/.cargo/registry/src/github.com-1ecc6299db9ec823/injective-cosmwasm-0.2.1/src/lib.rs:51:23
   |
51 | pub use test_helpers::testing_helpers::{
   |                       ^^^^^^^^^^^^^^^ could not find `testing_helpers` in `test_helpers`

Add multi markets info query

All the query in this enum is single market query, I suggest we also add multi-market query.

A user case would be Spot-Perp arbritage on ETH/USDT Perp, and WETH/USDT market.

pub enum InjectiveQuery {
// SubaccountDeposit will return the subaccount deposits for a given subaccount_id and denom
SubaccountDeposit {
subaccount_id: String,
denom: String,
},
SpotMarket {
market_id: String,
},
TraderSpotOrders {
market_id: String,
subaccount_id: String,
},
// DerivativeMarket will return the derivative market for a given id
DerivativeMarket {
market_id: String,
},
SubaccountPositions {
subaccount_id: String,
},
SubaccountEffectivePositionInMarket {
market_id: String,
subaccount_id: String,
},
TraderDerivativeOrders {
market_id: String,
subaccount_id: String,
},
PerpetualMarketInfo {
market_id: String,
},
PerpetualMarketFunding {
market_id: String,
},
DerivativeMarketVolatility {
market_id: String,
from: i64,
only_trade_history: bool,
},
SpotMarketVolatility {
market_id: String,
from: i64,
},
}

[FPDecimal] Handling sdk.Dec <nil> case

The Cosmos-SDK's empty sdk.Dec (e.g. sdk.Dec{}) string form is represented as "<nil>" (proof below).

However, FPDecimals' from_str method won't be able to convert this value.

/// Converts the decimal string to a FPDecimal
/// Possible inputs: "1.23", "1", "000012", "1.123000000"
/// Disallowed: "", ".23"
///
/// This never performs any kind of rounding.
/// More than 18 fractional digits, even zeros, result in an error.
fn from_str(input: &str) -> Result<Self, Self::Err> {
let sign = if input.starts_with('-') { 0 } else { 1 };
let parts: Vec<&str> = input.trim_start_matches('-').split('.').collect();
match parts.len() {
1 => {
let integer = U256::from_dec_str(parts[0]).map_err(|_| StdError::generic_err("Error parsing integer"))?;
Ok(FPDecimal {
num: integer * FPDecimal::ONE.num,
sign,
})
}
2 => {
let integer = U256::from_dec_str(parts[0]).map_err(|_| StdError::generic_err("Error parsing integer"))?;
let fraction = U256::from_dec_str(parts[1]).map_err(|_| StdError::generic_err("Error parsing fraction"))?;
let exp = FPDecimal::DIGITS
.checked_sub(parts[1].len())
.ok_or_else(|| StdError::generic_err(format!("Cannot parse more than {} fractional digits", FPDecimal::DIGITS)))?;
Ok(FPDecimal {
num: integer * FPDecimal::ONE.num + fraction * U256::exp10(exp),
sign,
})
}
_ => Err(StdError::generic_err("Unexpected number of dots")),
}
//Ok(FPDecimal {num: num * FPDecimal::ONE.num, sign: sign})
}
}

Should we handle this case? If so, how? @DrunkRandomWalker @gorgos

Proof:

type Dec struct {
	i *big.Int
}

func (d Dec) String() string {
	if d.i == nil {
		return d.i.String()
	}
	...
}

and big.Int's String method is simply

// String returns the decimal representation of x as generated by
// x.Text(10).
func (x *Int) String() string {
	return x.Text(10)
}

// Text returns the string representation of x in the given base.
// Base must be between 2 and 62, inclusive. The result uses the
// lower-case letters 'a' to 'z' for digit values 10 to 35, and
// the upper-case letters 'A' to 'Z' for digit values 36 to 61.
// No prefix (such as "0x") is added to the string. If x is a nil
// pointer it returns "<nil>".
func (x *Int) Text(base int) string {
	if x == nil {
		return "<nil>"
	}
	return string(x.abs.itoa(x.neg, base))
}

Implementation of Power functions

Can we please keep the power functions as simple as - a^(x) = e ^ (x * log (a)) - this might be slightly expensive (roughly 26 iterations from taylor ex + dunno if we're using karastuba-offman multiplication ) but we will get very stable results. We can further optimize both log and exp implementations - via bilinear transformations.

injective-math 0.2.1 including random

fix is to do the following in cargo.toml
primitive-types = {version= "0.12.2" ,default-features = false}
to injective-math's cargo.toml.

I found that primitive-types was including 'random', and causing wasm-bindgen to be included in smart contracts (and failing to store on injective-888).

Pass values by reference for FPDecimal methods, and associate functions

#[allow(clippy::upper_case_acronyms)]
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
pub struct FPDecimal {
    #[schemars(with = "String")]
    pub num: U256,
    pub sign: i8,
}

FPDecimal implemented Copy trait, parameter in associated functions in below are passed parameters by value. So values are copied, I think we are safe to pass parameters by reference, and copy when it is necessary.

pub fn _int(x: FPDecimal) -> FPDecimal {
let x1 = x.num;
let x1_1 = x1 / FPDecimal::ONE.num;
let x_final = x1_1 * FPDecimal::ONE.num;
FPDecimal { num: x_final, sign: x.sign }
}

pub fn _fraction(x: FPDecimal) -> FPDecimal {
let x1 = x.num;
FPDecimal {
num: x1 - FPDecimal::_int(x).num,
sign: x.sign,
}
}

Update to Prost 0.12

The new Name trait in prost 0.12 brings a lot more ease of use for consumers. Would love to see these deps updated.

[Registry] Add index for is_executable contracts

Currently if there exist deactivated (not executable) contracts in the CONTRACTS map, query_active_contracts can return fewer contracts than the limit in the paginated query.

.take(limit)
.filter(|item| {
if let Ok((_, contract)) = item {
contract.is_executable
} else {
false
}
})

We can use an IndexedMap to iterate solely over the executable contracts to resolve this issue.

injective-protobuf isn't generating the types for all of the proto files

Perhaps there is a reason for this that I'm not aware of, but it seems injective-protobuf is not building all of the types defined in the .proto files. An example being EthAccount. This can be fixed by simply adding the paths to the missing proto files into the inputs in build.rs. I would be happy to submit a PR for this if it will be accepted.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.