#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
use crate::exchange::CallDynamicChecked;
pub struct HyperliquidCore {
pub exchange: crate::exchange::Exchange,
}
impl HyperliquidCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::exchange::Exchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = HyperliquidCore::describe(self);
self.initialize_properties(described);
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for HyperliquidCore {
fn nonce(&self, ) -> crate::Value {
HyperliquidCore::nonce(self, )
}
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_order(self, order, &[market])
}
fn parse_market(&self, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_market(self, market)
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_funding_rate(self, rate, &[market])
}
fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
HyperliquidCore::parse_ledger_entry(self, entry, &[currency])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
HyperliquidCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
HyperliquidCore::parse_currency(self, currency)
}
fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_open_interest(self, interest, &[market])
}
fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_liquidation(self, liquidation, &[market])
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_margin_modification(self, data, &[market])
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
HyperliquidCore::parse_transaction(self, transaction, &[currency])
}
fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
HyperliquidCore::parse_income(self, info, &[market])
}
fn market(&self, symbol: crate::Value) -> crate::Value {
HyperliquidCore::market(self, symbol)
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
HyperliquidCore::sign(self, path, &[api, method, params, headers, body])
}
fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
HyperliquidCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for HyperliquidCore {
fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
-> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
{
Box::pin(async move {
match method {
"action_hash" => self.action_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]),
"add_margin" => self.add_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"approve_builder_fee" => self.approve_builder_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"build_approve_builder_fee_sig" => self.build_approve_builder_fee_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_send_asset_sig" => self.build_send_asset_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_usd_class_send_sig" => self.build_usd_class_send_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_usd_send_sig" => self.build_usd_send_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_user_abstraction_sig" => self.build_user_abstraction_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_user_dex_abstraction_sig" => self.build_user_dex_abstraction_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"build_withdraw_sig" => self.build_withdraw_sig(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"calculate_price_precision" => self.calculate_price_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null)),
"calculate_rate_limiter_cost" => self.calculate_rate_limiter_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"cancel_all_orders_after" => self.cancel_all_orders_after(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_for_symbols" => self.cancel_orders_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders_request" => self.cancel_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"cancel_twap_order" => self.cancel_twap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"construct_phantom_agent" => self.construct_phantom_agent(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_order_request" => self.create_order_request(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
"create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_orders_request" => self.create_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"create_sub_account" => self.create_sub_account(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"create_twap_order" => self.create_twap_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"create_vault" => self.create_vault(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"edit_order" => self.edit_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"edit_orders" => self.edit_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"edit_orders_request" => self.edit_orders_request(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"enable_user_dex_abstraction" => self.enable_user_dex_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"extract_type_from_delta" => self.extract_type_from_delta(&args[..]),
"fetch_balance" => self.fetch_balance(&args[..]).await,
"fetch_canceled_and_closed_orders" => self.fetch_canceled_and_closed_orders(&args[..]).await,
"fetch_canceled_orders" => self.fetch_canceled_orders(&args[..]).await,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_currencies" => self.fetch_currencies(&args[..]).await,
"fetch_deposits" => self.fetch_deposits(&args[..]).await,
"fetch_funding_history" => self.fetch_funding_history(&args[..]).await,
"fetch_funding_rate" => self.fetch_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_funding_rate_history" => self.fetch_funding_rate_history(&args[..]).await,
"fetch_funding_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_hip3_markets" => self.fetch_hip3_markets(&args[..]).await,
"fetch_ledger" => self.fetch_ledger(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_liquidations" => self.fetch_my_liquidations(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_interests" => self.fetch_open_interests(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders" => self.fetch_orders(&args[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_spot_markets" => self.fetch_spot_markets(&args[..]).await,
"fetch_status" => self.fetch_status(&args[..]).await,
"fetch_swap_markets" => self.fetch_swap_markets(&args[..]).await,
"fetch_tickers" => self.fetch_tickers(&args[..]).await,
"fetch_time" => self.fetch_time(&args[..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"handle_builder_fee_approval" => self.handle_builder_fee_approval().await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null),
args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_public_address" => self.handle_public_address(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"initialize_client" => self.initialize_client().await,
"is_unified_enabled" => self.is_unified_enabled(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"market" => self.market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"modify_margin_helper" => self.modify_margin_helper(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
"nonce" => self.nonce(),
"parse_create_edit_order_args" => self.parse_create_edit_order_args(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]),
"parse_currency" => self.parse_currency(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_funding_rate" => self.parse_funding_rate(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_income" => self.parse_income(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ledger_entry" => self.parse_ledger_entry(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_liquidation" => self.parse_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_market" => self.parse_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_open_interest" => self.parse_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_order" => self.parse_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_position" => self.parse_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ticker" => self.parse_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trade" => self.parse_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_trading_fee" => self.parse_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transaction" => self.parse_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_transfer" => self.parse_transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"price_to_precision" => self.price_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"reduce_margin" => self.reduce_margin(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"reserve_request_weight" => self.reserve_request_weight(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_agent_abstraction" => self.set_agent_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin_mode" => self.set_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_ref" => self.set_ref().await,
"set_user_abstraction" => self.set_user_abstraction(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_l1_action" => self.sign_l1_action(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]),
"sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_user_signed_action" => self.sign_user_signed_action(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"transfer" => self.transfer(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
"update_spot_currency_code" => self.update_spot_currency_code(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"withdraw" => self.withdraw(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), &args[3.min(args.len())..]).await,
_ => self.call_dynamic_base(method, args).await,
}
})
}
}
impl std::ops::Deref for HyperliquidCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for HyperliquidCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl HyperliquidCore {
pub fn describe(&self) -> Value {
return self.deep_extend(self.super_describe(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), Value::Str("hyperliquid".into()));
m.insert("name".to_string(), Value::Str("Hyperliquid".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("rateLimit".to_string(), Value::Int(50));
m.insert("certified".to_string(), Value::Bool(true));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(true));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(true));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("addMargin".to_string(), Value::Bool(true));
m.insert("borrowCrossMargin".to_string(), Value::Bool(false));
m.insert("borrowIsolatedMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(true));
m.insert("closeAllPositions".to_string(), Value::Bool(false));
m.insert("closePosition".to_string(), Value::Bool(false));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketOrderWithCost".to_string(), Value::Bool(false));
m.insert("createMarketSellOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(true));
m.insert("createOrderWithTakeProfitAndStopLoss".to_string(), Value::Bool(true));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(true));
m.insert("createStopOrder".to_string(), Value::Bool(true));
m.insert("createTriggerOrder".to_string(), Value::Bool(true));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("editOrders".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(true));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCrossBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchCrossBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchCurrencies".to_string(), Value::Bool(true));
m.insert("fetchDepositAddress".to_string(), Value::Bool(false));
m.insert("fetchDepositAddresses".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(true));
m.insert("fetchDepositWithdrawFee".to_string(), Value::Str("emulated".into()));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRate".to_string(), Value::Bool(true));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(true));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchIsolatedBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchLedger".to_string(), Value::Bool(true));
m.insert("fetchLeverage".to_string(), Value::Bool(false));
m.insert("fetchLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchLiquidations".to_string(), Value::Bool(false));
m.insert("fetchMarginMode".to_string(), Value::Null);
m.insert("fetchMarketLeverageTiers".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMarkOHLCV".to_string(), Value::Bool(false));
m.insert("fetchMyLiquidations".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(true));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(true));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositionMode".to_string(), Value::Bool(false));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchPositionsRisk".to_string(), Value::Bool(false));
m.insert("fetchPremiumIndexOHLCV".to_string(), Value::Bool(false));
m.insert("fetchStatus".to_string(), Value::Bool(true));
m.insert("fetchTicker".to_string(), Value::Str("emulated".into()));
m.insert("fetchTickers".to_string(), Value::Bool(true));
m.insert("fetchTime".to_string(), Value::Bool(true));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(true));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(false));
m.insert("fetchWithdrawal".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(true));
m.insert("reduceMargin".to_string(), Value::Bool(true));
m.insert("repayCrossMargin".to_string(), Value::Bool(false));
m.insert("repayIsolatedMargin".to_string(), Value::Bool(false));
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("setLeverage".to_string(), Value::Bool(true));
m.insert("setMarginMode".to_string(), Value::Bool(true));
m.insert("setPositionMode".to_string(), Value::Bool(false));
m.insert("transfer".to_string(), Value::Bool(true));
m.insert("withdraw".to_string(), Value::Bool(true));
m
}));
m.insert("timeframes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("1m".to_string(), Value::Str("1m".into()));
m.insert("3m".to_string(), Value::Str("3m".into()));
m.insert("5m".to_string(), Value::Str("5m".into()));
m.insert("15m".to_string(), Value::Str("15m".into()));
m.insert("30m".to_string(), Value::Str("30m".into()));
m.insert("1h".to_string(), Value::Str("1h".into()));
m.insert("2h".to_string(), Value::Str("2h".into()));
m.insert("4h".to_string(), Value::Str("4h".into()));
m.insert("8h".to_string(), Value::Str("8h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m.insert("3d".to_string(), Value::Str("3d".into()));
m.insert("1w".to_string(), Value::Str("1w".into()));
m.insert("1M".to_string(), Value::Str("1M".into()));
m
}));
m.insert("hostname".to_string(), Value::Str("hyperliquid.xyz".into()));
m.insert("urls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/550769b3-d270-461e-9e02-8e8b8c0210b8".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://api.{hostname}".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Str("https://api.hyperliquid-testnet.xyz".into()));
m.insert("private".to_string(), Value::Str("https://api.hyperliquid-testnet.xyz".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://hyperliquid.xyz".into()));
m.insert("doc".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api".into()));
m.insert("fees".to_string(), Value::Str("https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees".into()));
m.insert("referral".to_string(), Value::Str("https://app.hyperliquid.xyz/".into()));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(10));
m.insert("byType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("l2Book".to_string(), Value::Int(2));
m.insert("allMids".to_string(), Value::Int(2));
m.insert("clearinghouseState".to_string(), Value::Int(2));
m.insert("orderStatus".to_string(), Value::Int(2));
m.insert("spotClearinghouseState".to_string(), Value::Int(2));
m.insert("exchangeStatus".to_string(), Value::Int(2));
m.insert("candleSnapshot".to_string(), Value::Int(4));
m
}));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exchange".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.00045".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.00015".into()), &[]));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), self.parse_number(Value::Str("0.0007".into()), &[]));
m.insert("maker".to_string(), self.parse_number(Value::Str("0.0004".into()), &[]));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(false));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(true));
m.insert("privateKey".to_string(), Value::Bool(true));
m
}));
m.insert("exceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("exact".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Price must be divisible by tick size.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order must have minimum value of $10".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Insufficient margin to place order.".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("Reduce only order would increase position.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Post only order would have immediately matched,".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order could not immediately match against any resting orders.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Invalid TP/SL price.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("No liquidity available for market order.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".into()));
m.insert("User or API Wallet ".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order has invalid size".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order price cannot be more than 80% away from the reference price".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Order has zero size.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("Insufficient spot balance asset".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("Insufficient balance for withdrawal".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("Insufficient balance for token transfer".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("TWAP order value too small. Min is $1200, which is $10 per minute.".to_string(), Value::Str("InvalidOrder".into()));
m.insert("TWAP was never placed, already canceled, or filled.".to_string(), Value::Str("OrderNotFound".into()));
m.insert("Too many cumulative requests sent".to_string(), Value::Str("RateLimitExceeded".into()));
m
}));
m
}));
m.insert("precisionMode".to_string(), Value::Int(crate::runtime::TICK_SIZE));
m.insert("commonCurrencies".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("defaultType".to_string(), Value::Str("swap".into()));
m.insert("sandboxMode".to_string(), Value::Bool(false));
m.insert("builderFee".to_string(), Value::Bool(true));
m.insert("defaultSlippage".to_string(), Value::Float(0.05));
m.insert("marketHelperProps".to_string(), Value::from(vec![Value::Str("hip3TokensByName".into()), Value::Str("cachedCurrenciesById".into())]));
m.insert("zeroAddress".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m.insert("spotCurrencyMapping".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("UDZ".to_string(), Value::Str("2Z".into()));
m.insert("UBONK".to_string(), Value::Str("BONK".into()));
m.insert("UBTC".to_string(), Value::Str("BTC".into()));
m.insert("UETH".to_string(), Value::Str("ETH".into()));
m.insert("UFART".to_string(), Value::Str("FARTCOIN".into()));
m.insert("HPENGU".to_string(), Value::Str("PENGU".into()));
m.insert("UPUMP".to_string(), Value::Str("PUMP".into()));
m.insert("USOL".to_string(), Value::Str("SOL".into()));
m.insert("UUUSPX".to_string(), Value::Str("SPX".into()));
m.insert("USDT0".to_string(), Value::Str("USDT".into()));
m.insert("XAUT0".to_string(), Value::Str("XAUT".into()));
m.insert("UXPL".to_string(), Value::Str("XPL".into()));
m
}));
m.insert("fetchMarkets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("types".to_string(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("hip3".into())]));
m.insert("hip3".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(10));
m.insert("dexes".to_string(), Value::from(vec![]));
m
}));
m
}));
m
}));
m.insert("features".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("default".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sandbox".to_string(), Value::Bool(true));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("triggerPrice".to_string(), Value::Bool(false));
m.insert("triggerPriceType".to_string(), Value::Null);
m.insert("triggerDirection".to_string(), Value::Bool(false));
m.insert("stopLossPrice".to_string(), Value::Bool(false));
m.insert("takeProfitPrice".to_string(), Value::Bool(false));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("triggerPriceType".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("last".to_string(), Value::Bool(false));
m.insert("mark".to_string(), Value::Bool(false));
m.insert("index".to_string(), Value::Bool(false));
m
}));
m.insert("triggerPrice".to_string(), Value::Bool(true));
m.insert("type".to_string(), Value::Bool(true));
m.insert("price".to_string(), Value::Bool(true));
m
}));
m.insert("timeInForce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("IOC".to_string(), Value::Bool(true));
m.insert("FOK".to_string(), Value::Bool(false));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("hedged".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m.insert("createOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("max".to_string(), Value::Int(1000));
m
}));
m.insert("fetchMyTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOpenOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchClosedOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marginMode".to_string(), Value::Bool(false));
m.insert("limit".to_string(), Value::Int(2000));
m.insert("daysBack".to_string(), Value::Null);
m.insert("daysBackCanceled".to_string(), Value::Null);
m.insert("untilDays".to_string(), Value::Null);
m.insert("trigger".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("symbolRequired".to_string(), Value::Bool(true));
m
}));
m.insert("fetchOHLCV".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Int(5000));
m
}));
m
}));
m.insert("spot".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m
}));
m.insert("forPerps".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("default".into()));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), Value::Bool(true));
m.insert("takeProfitPrice".to_string(), Value::Bool(true));
m.insert("attachedStopLossTakeProfit".to_string(), Value::Null);
m
}));
m
}));
m.insert("swap".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m
}));
m.insert("future".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("linear".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m.insert("inverse".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("extends".to_string(), Value::Str("forPerps".into()));
m
}));
m
}));
m
}));
m.insert("rollingWindowSize".to_string(), Value::Int(0));
m
})]);
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enabled: Value) {
self.super_set_sandbox_mode(enabled.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enabled); }
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
pub fn market(&self, mut symbol: Value) -> Value {
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" market() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" markets not loaded".into()))));
}
if !(matches!((&self.markets, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut symbolParts: Value = Value::Array(if let Some(__s) = symbol.as_str() { __s.split("/").map(Value::from).collect() } else { Vec::new() });
let mut baseName: Value = self.safe_string(symbolParts.clone(), Value::Int(0), &[]);
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (matches!((&spotCurrencyMapping, &baseName), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut unifiedBaseName: Option<String> = self.safe_string_opt(spotCurrencyMapping.clone(), baseName.clone(), &[]);
let quote: String = self.safe_string_opt(symbolParts, Value::Int(1), &[]).unwrap_or_default();
let mut newSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.safe_currency_code(unifiedBaseName.map(Value::from).unwrap_or(Value::Null), &[]), Value::Str("/".into())).into()), quote).into());
if (matches!((&self.markets, &newSymbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
return (if let (Some(__m), Some(__k)) = (self.markets.as_map(), newSymbol.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
}
}
}
return self.super_market(symbol);
Value::Null
}
pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("exchangeStatus".into()));
m
});
let __ws_arg_0 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_0]).await;
let mut status: Option<String> = self.safe_string_k(response.clone(), "specialStatuses", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (status.is_none()) { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
m.insert("updated".to_string(), self.safe_integer_k(response.clone(), "time", &[]));
m.insert("eta".to_string(), Value::Null);
m.insert("url".to_string(), Value::Null);
m.insert("info".to_string(), response);
m
});
Value::Null
}
pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("exchangeStatus".into()));
m
});
let __ws_arg_1 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_1]).await;
return self.safe_integer_k(response, "time", &[]);
Value::Null
}
pub async fn fetch_currencies(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
self.initialize_client().await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotMeta".into()));
m
});
let __ws_arg_2 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_2]).await;
let mut tokens: Value = self.safe_list_k(response, "tokens", &[Value::from(vec![])]);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("cachedCurrenciesById".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }; return self.parse_currencies(tokens);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut id: Option<String> = self.safe_string_k_opt(rawCurrency.clone(), "index", &[]);
let mut name: Value = self.safe_string_k(rawCurrency.clone(), "name", &[]);
let mut code: Value = self.safe_currency_code(name.clone(), &[]);
if let Value::Dict(__bf03d0) = unsafe { crate::runtime::coerce_value_to_mut(&self.options) } { let __bf03e1 = std::sync::Arc::make_mut(__bf03d0).entry("cachedCurrenciesById".to_string()).or_insert(Value::Null); if let Value::Dict(__r05d) = __bf03e1 { std::sync::Arc::make_mut(__r05d).insert(id.as_deref().unwrap_or("null").to_string(), name.clone()); } }
let mut result: Value = self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("name".to_string(), name.clone());
m.insert("code".to_string(), code.clone());
m.insert("precision".to_string(), self.parse_precision(&[self.safe_string_k(rawCurrency.clone(), "weiDecimals", &[])]));
m.insert("info".to_string(), rawCurrency.clone());
m.insert("active".to_string(), Value::Null);
m.insert("deposit".to_string(), Value::Null);
m.insert("withdraw".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("withdraw".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m
}));
let mut fullName: Option<String> = self.safe_string_k_opt(rawCurrency, "fullName", &[]);
if (fullName.is_some()) && (name != Value::Null) {
let mut isWrapped: bool = (fullName.as_deref().unwrap_or("").starts_with("Unit ")) && (name.as_str().unwrap_or("").starts_with("U"));
if isWrapped {
let mut parts: Vec<Value> = Value::Array(if let Some(__s) = name.as_str() { __s.split("U").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
let mut nameWithoutU: Value = Value::Str("".into());
{
let mut j: i64 = 0;
let mut __for_first_797: bool = true;
while { if !__for_first_797 { j += 1; } __for_first_797 = false; j < (parts.len() as i64) } {
nameWithoutU = Value::Str(format!("{}{}", nameWithoutU, parts.get(j as usize).cloned().unwrap_or(Value::Null)).into());
}
}
let mut baseCode: Value = self.safe_currency_code(nameWithoutU, &[]);
if (code != Value::Null) {
if let Value::Dict(__bf03d0) = unsafe { crate::runtime::coerce_value_to_mut(&self.options) } { let __bf03e1 = std::sync::Arc::make_mut(__bf03d0).entry("spotCurrencyMapping".to_string()).or_insert(Value::Null); if let Value::Dict(__r05d) = __bf03e1 { std::sync::Arc::make_mut(__r05d).insert(crate::runtime::stringify_param(&code), baseCode); } }
}
}
}
return result;
Value::Null
}
pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut types: Value = self.safe_list_k(options, "types", &[Value::from(vec![])]);
let mut rawPromises: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_798: bool = true;
while { if !__for_first_798 { i += 1; } __for_first_798 = false; i < (types.len() as i64) } {
let mut marketType: Option<String> = self.safe_string(types.clone(), Value::Int(i), &[]).as_str().map(str::to_owned);
if (marketType.as_deref() == Some("swap")) {
rawPromises.push(self.fetch_swap_markets(&[params.clone()]).await);
} else if (marketType.as_deref() == Some("spot")) {
rawPromises.push(self.fetch_spot_markets(&[params.clone()]).await);
} else if (marketType.as_deref() == Some("hip3")) {
rawPromises.push(self.fetch_hip3_markets(&[params.clone()]).await);
}
}
}
let mut promises: Value = promise_all(&Value::from(rawPromises)).await;
let mut result: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_799: bool = true;
while { if !__for_first_799 { i += 1; } __for_first_799 = false; i < (promises.len() as i64) } {
result = self.array_concat(result.clone(), self.safe_list(promises.clone(), Value::Int(i), &[Value::from(vec![])]));
}
}
return result;
Value::Null
}
pub async fn fetch_hip3_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut fetchDexes: Value = self.public_post_info(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("perpDexs".into()));
m
})]).await;
let mut perpDexesOffset: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut dexesCount: Value = get_array_length(&fetchDexes);
{
let mut i: Value = Value::Int(1);
let mut __for_first_800: bool = true;
while { if !__for_first_800 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_800 = false; i.as_f64().unwrap_or(f64::NAN) < dexesCount.as_f64().unwrap_or(f64::NAN) } {
let mut dex: Value = self.safe_dict(fetchDexes.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut secondPart: Value = (match (&((match (&(i), &(Value::Int(10000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })),
&(Value::Int(10000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
let mut offset: Value = self.sum(&[Value::Int(110000), secondPart]);
add_element_to_object(&mut perpDexesOffset, &self.safe_string_k(dex.clone(), "name", &[Value::Str("".into())]), offset.clone());
}
}
let mut fetchDexesList: Value = Value::from(vec![]);
let mut options: Value = self.safe_dict_k(self.options.clone(), "fetchMarkets", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut hip3: Value = self.safe_dict_k(options.clone(), "hip3", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dexesProvided: Value = self.safe_list_k(hip3.clone(), "dexes", &[Value::from(vec![])]); let mut maxLimit: Value = self.safe_integer_k(hip3, "limit", &[Value::Int(10)]);
let mut userProvidedDexesLength: f64 = ((dexesProvided.len() as i64) as f64);
if userProvidedDexesLength > ((0i64) as f64) {
if userProvidedDexesLength > ((0i64) as f64) {
fetchDexesList = dexesProvided;
}
} else {
let mut fetchDexesLength: Value = get_array_length(&fetchDexes);
let mut maxIteration: Value = self.sum(&[maxLimit, Value::Int(1)]);
{
let mut i: Value = Value::Int(1);
let mut __for_first_801: bool = true;
while { if !__for_first_801 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_801 = false; i.as_f64().unwrap_or(f64::NAN) < maxIteration.as_f64().unwrap_or(f64::NAN) } {
if i.as_f64().unwrap_or(f64::NAN) >= fetchDexesLength.as_f64().unwrap_or(f64::NAN) {
break;
}
let mut dex: Value = self.safe_dict(fetchDexes.clone(), i.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (dex == Value::Null) {
continue;
}
let mut dexName: Option<String> = self.safe_string_k_opt(dex, "name", &[]);
if let Value::Arr(__a) = &mut fetchDexesList { std::sync::Arc::make_mut(__a).push(dexName.map(Value::from).unwrap_or(Value::Null)); }
}
}
}
let mut rawPromises: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_802: bool = true;
while { if !__for_first_802 { i += 1; } __for_first_802 = false; i < (fetchDexesList.len() as i64) } {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m.insert("dex".to_string(), self.safe_string(fetchDexesList.clone(), Value::Int(i), &[]));
m
});
let __ws_arg_3 = self.extend(Value::Map(request), &[params.clone()]);
rawPromises.push(self.public_post_info(&[__ws_arg_3]).await);
}
}
let mut promises: Value = promise_all(&Value::from(rawPromises)).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("hip3TokensByName".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})); }
let mut markets: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_804: bool = true;
while { if !__for_first_804 { i += 1; } __for_first_804 = false; i < (promises.len() as i64) } {
let mut dexName: Value = fetchDexesList.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut offset: Option<i64> = self.safe_integer(perpDexesOffset.clone(), dexName.clone(), &[]).as_i64();
let mut response: Value = self.safe_list(promises.clone(), Value::Int(i), &[]);
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut collateralToken: Value = self.safe_string_k(meta.clone(), "collateralToken", &[]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Vec<Value> = Vec::new();
{
let mut j: i64 = 0;
let mut __for_first_803: bool = true;
while { if !__for_first_803 { j += 1; } __for_first_803 = false; j < (universe.len() as i64) } {
let __ws_arg_4 = self.safe_dict(universe.clone(), Value::Int(j), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_5 = self.safe_dict(assetCtxs.clone(), Value::Int(j), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_4, &[__ws_arg_5]);
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("baseId".into(), self.sum(&[Value::Int(j), Value::from(offset)])); }
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("collateralToken".into(), collateralToken.clone()); }
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("hip3".into(), Value::Bool(true)); }
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("dex".into(), dexName.clone()); }
let mut cachedCurrencies: Value = self.safe_dict_k(self.options.clone(), "cachedCurrenciesById", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (matches!((&cachedCurrencies, &collateralToken), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
let mut name: Value = self.safe_string_k(data.clone(), "name", &[]);
let mut collateralTokenCode: Option<String> = self.safe_string_opt(cachedCurrencies.clone(), collateralToken.clone(), &[]);
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("collateralTokenName".into(), collateralTokenCode.clone().map(Value::from).unwrap_or(Value::Null)); }
let mut safeCode: Value = self.safe_currency_code(name.clone(), &[]);
let mut hip3Code: Value = (if (safeCode == Value::Null) { name.clone() } else { safeCode.as_str().map(|__s| Value::Str(__s.replace(":", "-").into())).unwrap_or_else(|| safeCode.clone()) });
if let Value::Dict(__bf03d0) = &mut self.options {
let __bf03e1 = std::sync::Arc::make_mut(__bf03d0).entry("hip3TokensByName".to_string()).or_insert(Value::Null);
if let Value::Dict(__r05d) = __bf03e1 { std::sync::Arc::make_mut(__r05d).insert(crate::runtime::stringify_param(&name), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("quote".to_string(), collateralTokenCode.map(Value::from).unwrap_or(Value::Null));
m.insert("code".to_string(), hip3Code);
m
}));
}
}
}
result.push(data);
}
}
markets = self.array_concat(markets.clone(), self.parse_markets(Value::from(result)));
}
}
return markets;
Value::Null
}
pub async fn fetch_swap_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m
});
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_6]).await;
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_805: bool = true;
while { if !__for_first_805 { i += 1; } __for_first_805 = false; i < (universe.len() as i64) } {
let __ws_arg_7 = self.safe_dict(universe.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_8 = self.safe_dict(assetCtxs.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_7, &[__ws_arg_8]);
if let Value::Dict(__d) = &mut data { std::sync::Arc::make_mut(__d).insert("baseId".into(), Value::Int(i)); }
result.push(data);
}
}
return self.parse_markets(Value::from(result));
Value::Null
}
pub fn calculate_price_precision(&self, mut price: Value, mut amountPrecision: Value, mut maxDecimals: Value) -> Value {
let mut pricePrecision: Value = Value::Int(0);
let mut priceStr: Value = self.number_to_string(price);
if (priceStr == Value::Null) {
return Value::Int(0);
}
let mut priceSplitted: Value = Value::Array(if let Some(__s) = priceStr.as_str() { __s.split(".").map(Value::from).collect() } else { Vec::new() });
let mut maxDecimalsInt: Value = self.parse_to_int(maxDecimals);
let mut amountPrecisionInt: Value = self.parse_to_int(amountPrecision);
let mut decimalsLeft: Value = (match (&(maxDecimalsInt), &(amountPrecisionInt)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
if crate::precise::Precise::stringEq(&priceStr, &Value::Str("0".into())).as_bool() == Some(true) {
pricePrecision = crate::runtime::Math::min(&decimalsLeft, &Value::Int(5));
} else if crate::precise::Precise::stringGt(&priceStr, &Value::Str("0".into())).as_bool() == Some(true) && crate::precise::Precise::stringLt(&priceStr, &Value::Str("1".into())).as_bool() == Some(true) {
let mut significantDigits: Value = Value::Int(5);
let mut decimalPart: Value = self.safe_string(priceSplitted.clone(), Value::Int(1), &[Value::Str("".into())]);
let mut leadingZeros: Value = self.parse_to_int(Value::Int(0));
while (leadingZeros.as_f64().unwrap_or(f64::NAN) <= ((decimalPart.len() as i64) as f64)) && (get_value(&decimalPart, &leadingZeros).as_str() == Some("0")) {
leadingZeros = self.parse_to_int((match (&(leadingZeros), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
}
pricePrecision = (match (&(leadingZeros), &(significantDigits)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
pricePrecision = crate::runtime::Math::min(&decimalsLeft, &pricePrecision);
} else {
let mut integerPart: Value = self.safe_string(priceSplitted, Value::Int(0), &[Value::Str("".into())]);
let mut digitsLeft: Value = Value::Int(0);
if ((integerPart.len() as i64) as f64) <= ((5i64) as f64) {
digitsLeft = (match (&(Value::Int(5)), &((Value::Int(integerPart.len() as i64)))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
}
pricePrecision = crate::runtime::Math::min(&decimalsLeft, &digitsLeft);
}
return self.parse_to_int(pricePrecision);
Value::Null
}
pub async fn fetch_spot_markets(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("spotMetaAndAssetCtxs".into()));
m
});
let __ws_arg_9 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_9]).await;
let mut first: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut second: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut meta: Value = self.safe_list_k(first.clone(), "universe", &[Value::from(vec![])]);
let mut tokens: Value = self.safe_list_k(first, "tokens", &[Value::from(vec![])]);
let mut tokensByIndex: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
{
let mut i: i64 = 0;
let mut __for_first_806: bool = true;
while { if !__for_first_806 { i += 1; } __for_first_806 = false; i < (tokens.len() as i64) } {
let mut token: Value = self.safe_dict(tokens.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenIndex: Option<String> = self.safe_string_k_opt(token.clone(), "index", &[]);
if (tokenIndex.is_some()) {
tokensByIndex.insert(tokenIndex.as_deref().unwrap_or("null").to_string(), token);
}
}
}
let mut markets: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_807: bool = true;
while { if !__for_first_807 { i += 1; } __for_first_807 = false; i < (meta.len() as i64) } {
let mut market: Value = self.safe_dict(meta.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut index: Value = self.safe_integer_k(market.clone(), "index", &[]);
let mut extraData: Value = self.safe_dict(second.clone(), index.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketName: Option<String> = self.safe_string_k_opt(market.clone(), "name", &[]);
let mut fees: Value = self.safe_dict_k(self.fees.clone(), "spot", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker: Value = self.safe_number_k(fees.clone(), "taker", &[]);
let mut maker: Value = self.safe_number_k(fees, "maker", &[]);
let mut tokensPos: Value = self.safe_list_k(market.clone(), "tokens", &[Value::from(vec![])]);
let mut baseTokenIndex: Option<String> = self.safe_string_opt(tokensPos.clone(), Value::Int(0), &[]);
let mut quoteTokenIndex: Option<String> = self.safe_string_opt(tokensPos, Value::Int(1), &[]);
let mut baseTokenInfo: Value = self.safe_dict(Value::Map(tokensByIndex.clone()), baseTokenIndex.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut quoteTokenInfo: Value = self.safe_dict(Value::Map(tokensByIndex.clone()), quoteTokenIndex.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut baseName: Option<String> = self.safe_string_k_opt(baseTokenInfo.clone(), "name", &[]);
let mut quoteId: Option<String> = self.safe_string_k_opt(quoteTokenInfo, "name", &[]);
if (baseName.is_none()) || (quoteId.is_none()) {
continue;
}
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut mappedBaseName: Value = self.safe_string(spotCurrencyMapping.clone(), baseName.clone().map(Value::from).unwrap_or(Value::Null), &[baseName.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut mappedQuoteId: Value = self.safe_string(spotCurrencyMapping, quoteId.clone().map(Value::from).unwrap_or(Value::Null), &[quoteId.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut mappedBase: Value = self.safe_currency_code(mappedBaseName, &[]);
let mut mappedQuote: Value = self.safe_currency_code(mappedQuoteId, &[]);
let mut mappedSymbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", mappedBase, Value::Str("/".into())).into()), mappedQuote).into());
let mut innerBaseTokenInfo: Value = self.safe_dict_k(baseTokenInfo.clone(), "spec", &[baseTokenInfo.clone()]);
let mut amountPrecisionStr: Option<String> = self.safe_string_k_opt(innerBaseTokenInfo, "szDecimals", &[]);
let mut amountPrecision: Value = self.parse_to_int(amountPrecisionStr.clone().map(Value::from).unwrap_or(Value::Null));
let mut price: Value = self.safe_number_k(extraData.clone(), "midPx", &[]);
let mut pricePrecision: Value = Value::Int(0);
if (price != Value::Null) {
pricePrecision = self.calculate_price_precision(price, amountPrecision, Value::Int(8));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision);
let mut baseId: Value = self.number_to_string((match (&(index), &(Value::Int(10000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
let mut entry: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketName.map(Value::from).unwrap_or(Value::Null));
m.insert("symbol".to_string(), mappedSymbol);
m.insert("base".to_string(), mappedBase);
m.insert("quote".to_string(), mappedQuote);
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), baseId);
m.insert("baseName".to_string(), baseName.map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), quoteId.map(Value::from).unwrap_or(Value::Null));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("spot".into()));
m.insert("spot".to_string(), Value::Bool(true));
m.insert("subType".to_string(), Value::Null);
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(true));
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[amountPrecisionStr.map(Value::from).unwrap_or(Value::Null)]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr]), &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("10".into()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), self.extend(extraData, &[market]));
m
});
markets.push(self.safe_market_structure(&[Value::Map(entry)]));
}
}
return Value::from(markets);
Value::Null
}
pub fn parse_market(&self, mut market: Value) -> Value {
let mut collateralTokenCode: Option<String> = self.safe_string_k_opt(market.clone(), "collateralTokenName", &[]);
let mut quoteId: Value = collateralTokenCode.clone().map(Value::from).unwrap_or(Value::Null);
if (collateralTokenCode.is_none()) {
quoteId = Value::Str("USDC".into());
}
let mut settleId: Value = collateralTokenCode.clone().map(Value::from).unwrap_or(Value::Null);
if (collateralTokenCode.is_none()) {
settleId = Value::Str("USDC".into());
}
let mut baseName: Option<String> = self.safe_string_k_opt(market.clone(), "name", &[]);
let mut base: Value = self.safe_currency_code(baseName.clone().map(Value::from).unwrap_or(Value::Null), &[]);
if (base == Value::Null) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" parseMarket() missing base currency".into()))));
}
base = base.as_str().map(|__s| Value::Str(__s.replace(":", "-").into())).unwrap_or_else(|| base.clone()); let mut quote: Value = self.safe_currency_code(quoteId.clone(), &[]);
if (quote == Value::Null) {
return Value::Null;
}
let mut baseId: Option<String> = self.safe_string_k_opt(market.clone(), "baseId", &[]);
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbolBase: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
let mut symbol: Value = symbolBase.clone();
let mut contract: bool = true;
let mut swap: bool = true;
if contract {
if swap {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbolBase, Value::Str(":".into())).into()), settle).into());
}
}
let mut fees: Value = self.safe_dict_k(self.fees.clone(), "swap", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut taker: Value = self.safe_number_k(fees.clone(), "taker", &[]);
let mut maker: Value = self.safe_number_k(fees, "maker", &[]);
let mut amountPrecisionStr: Option<String> = self.safe_string_k_opt(market.clone(), "szDecimals", &[]);
let mut amountPrecision: Value = self.parse_to_int(amountPrecisionStr.clone().map(Value::from).unwrap_or(Value::Null));
let mut price: Value = self.safe_number_k(market.clone(), "markPx", &[Value::Int(0)]);
let mut pricePrecision: Value = Value::Int(0);
if (price != Value::Null) {
pricePrecision = self.calculate_price_precision(price, amountPrecision, Value::Int(6));
}
let mut pricePrecisionStr: Value = self.number_to_string(pricePrecision);
let mut isDelisted: Option<bool> = self.safe_bool_k_opt(market.clone(), "isDelisted", &[]);
let mut active: Value = Value::Bool(true);
if (isDelisted.is_some()) {
active = Value::Bool(!(isDelisted == Some(true)));
}
return self.safe_market_structure(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), baseId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("symbol".to_string(), symbol);
m.insert("base".to_string(), base);
m.insert("quote".to_string(), quote);
m.insert("settle".to_string(), settle);
m.insert("baseId".to_string(), baseId.map(Value::from).unwrap_or(Value::Null));
m.insert("baseName".to_string(), baseName.map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), quoteId);
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), Value::Str("swap".into()));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Null);
m.insert("swap".to_string(), Value::Bool(swap));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), active);
m.insert("contract".to_string(), Value::Bool(contract));
m.insert("linear".to_string(), Value::Bool(true));
m.insert("inverse".to_string(), Value::Bool(false));
m.insert("taker".to_string(), taker);
m.insert("maker".to_string(), maker);
m.insert("contractSize".to_string(), self.parse_number(Value::Str("1".into()), &[]));
m.insert("expiry".to_string(), Value::Null);
m.insert("expiryDatetime".to_string(), Value::Null);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("precision".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), self.parse_number(self.parse_precision(&[amountPrecisionStr.map(Value::from).unwrap_or(Value::Null)]), &[]));
m.insert("price".to_string(), self.parse_number(self.parse_precision(&[pricePrecisionStr]), &[]));
m
}));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("leverage".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), self.safe_integer_k(market.clone(), "maxLeverage", &[]));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), self.parse_number(Value::Str("10".into()), &[]));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
})]);
Value::Null
}
pub fn update_spot_currency_code(&self, mut code: Value) -> Value {
if (code == Value::Null) {
return code;
}
let mut spotCurrencyMapping: Value = self.safe_dict_k(self.options.clone(), "spotCurrencyMapping", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_string(spotCurrencyMapping, code.clone(), &[code.clone()]);
Value::Null
}
pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut shouldRefresh: Value = Value::Bool((self.safe_string2(params.clone(), Value::Str("user".into()), Value::Str("address".into()), &[]) != Value::Null) && (self.safe_bool_k(params.clone(), "enableUnifiedMargin", &[]) == Value::Null));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchBalance".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchBalance".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let type_varparamsMarketTypeVariable: Vec<Value> = self.handle_market_type_and_params(Value::Str("fetchBalance".into()), &[Value::Null, paramsPublicAddress]).as_array().cloned().unwrap_or_default();
let mut type_var: Value = type_varparamsMarketTypeVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsMarketType: Value = type_varparamsMarketTypeVariable.get(1).cloned().unwrap_or(Value::Null);
let marginModeparamsMarginModeVariable: Vec<Value> = self.handle_margin_mode_and_params(Value::Str("fetchBalance".into()), &[paramsMarketType]).as_array().cloned().unwrap_or_default();
let mut marginMode: Value = marginModeparamsMarginModeVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsMarginMode: Value = marginModeparamsMarginModeVariable.get(1).cloned().unwrap_or(Value::Null);
let isUnifiedEnabledparamsValueVariable: Vec<Value> = self.is_unified_enabled(Value::Str("fetchBalance".into()), &[userAddress.clone().map(Value::from).unwrap_or(Value::Null), shouldRefresh, paramsMarginMode]).await.as_array().cloned().unwrap_or_default();
let mut isUnifiedEnabled: Value = isUnifiedEnabledparamsValueVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsValue: Value = isUnifiedEnabledparamsValueVariable.get(1).cloned().unwrap_or(Value::Null);
let mut dex: Option<String> = self.safe_string_k(paramsValue.clone(), "dex", &[]).as_str().map(str::to_owned);
let mut isSpot: bool = ((type_var.as_str() == Some("spot")) || (isUnifiedEnabled.as_bool() == Some(true))) && (dex.is_none());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), (if (isSpot) { Value::Str("spotClearinghouseState".into()) } else { Value::Str("clearinghouseState".into()) }));
m.insert("user".to_string(), userAddress.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_10 = self.extend(Value::Map(request), &[paramsValue]);
let mut response: Value = self.public_post_info(&[__ws_arg_10]).await;
let mut balances: Value = self.safe_list_k(response.clone(), "balances", &[]);
if (balances != Value::Null) {
let mut spotBalances: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
{
let mut i: i64 = 0;
let mut __for_first_808: bool = true;
while { if !__for_first_808 { i += 1; } __for_first_808 = false; i < (balances.len() as i64) } {
let mut balance: Value = self.safe_dict(balances.clone(), Value::Int(i), &[]);
let mut unifiedCode: Value = self.safe_currency_code(self.safe_string_k(balance.clone(), "coin", &[]), &[]);
let mut code: Value = (if (isSpot) { self.update_spot_currency_code(unifiedCode.clone()) } else { unifiedCode });
let mut account: indexmap::IndexMap<String, Value> = self.account().as_map().cloned().unwrap_or_default();
let mut total: Option<String> = self.safe_string_k_opt(balance.clone(), "total", &[]);
let mut used: Option<String> = self.safe_string_k_opt(balance, "hold", &[]);
account.insert("total".into(), total.map(Value::from).unwrap_or(Value::Null));
account.insert("used".into(), used.map(Value::from).unwrap_or(Value::Null));
if (code != Value::Null) {
spotBalances.insert(crate::runtime::stringify_param(&code), Value::Map(account));
}
}
}
return self.safe_balance(Value::Map(spotBalances));
}
let mut data: Value = self.safe_dict_k(response.clone(), "marginSummary", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut usdcBalance: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("total".to_string(), self.safe_number_k(data.clone(), "accountValue", &[]));
m
});
if (marginMode != Value::Null) && (marginMode.as_str() == Some("isolated")) {
usdcBalance.insert("free".into(), self.safe_number_k(response.clone(), "withdrawable", &[]));
} else {
usdcBalance.insert("used".into(), self.safe_number_k(data, "totalMarginUsed", &[]));
}
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m.insert("USDC".to_string(), Value::Map(usdcBalance));
m
});
let mut timestamp: Option<i64> = self.safe_integer_k(response, "time", &[]).as_i64();
result.insert("timestamp".into(), Value::from(timestamp));
result.insert("datetime".into(), self.iso8601(Value::from(timestamp)));
return self.safe_balance(Value::Map(result));
Value::Null
}
pub async fn fetch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut limit = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("l2Book".into()));
m.insert("coin".to_string(), (if matches!((self.safe_bool_k(market.clone(), "swap", &[Value::Bool(false)])), Value::Bool(true)) { self.safe_string_k(market.clone(), "baseName", &[]) } else { market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) }));
m
});
let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_11]).await;
let mut data: Value = self.safe_list_k(response.clone(), "levels", &[Value::from(vec![])]);
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), self.safe_list(data.clone(), Value::Int(0), &[Value::from(vec![])]));
m.insert("asks".to_string(), self.safe_list(data, Value::Int(1), &[Value::from(vec![])]));
m
});
let mut timestamp: Value = self.safe_integer_k(response, "time", &[]);
return self.parse_order_book(Value::Map(result), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("px".into()), Value::Str("sz".into())]);
Value::Null
}
pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut response: Value = Value::from(vec![]);
let mut type_var: Option<String> = self.safe_string_k(params.clone(), "type", &[]).as_str().map(str::to_owned);
let mut paramsOmitted: Value = self.omit(params, Value::Str("type".into()), &[]);
let hip3OptionparamsHip3Variable: Vec<Value> = self.handle_option_bool_and_params(paramsOmitted, Value::Str("fetchTickers".into()), Value::Str("hip3".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut hip3Option: Value = hip3OptionparamsHip3Variable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsHip3: Value = hip3OptionparamsHip3Variable.get(1).cloned().unwrap_or(Value::Null);
let mut hip3: Value = hip3Option;
if (symbolsNormalized != Value::Null) {
let mut firstSymbol: Option<String> = self.safe_string_opt(symbolsNormalized.clone(), Value::Int(0), &[]);
if (firstSymbol.is_some()) {
let mut market: Value = self.market(firstSymbol.map(Value::from).unwrap_or(Value::Null));
if matches!(self.safe_bool(self.safe_dict_k(market.clone(), "info", &[]), Value::Str("hip3".into()), &[Value::Bool(false)]), Value::Bool(true)) {
hip3 = Value::Bool(true);
}
}
}
if hip3.as_bool() == Some(true) {
response = self.fetch_hip3_markets(&[self.omit(paramsHip3.clone(), Value::Str("hip3".into()), &[])]).await;
} else if (type_var.as_deref() == Some("spot")) {
response = self.fetch_spot_markets(&[paramsHip3.clone()]).await;
} else if (type_var.as_deref() == Some("swap")) {
response = self.fetch_swap_markets(&[paramsHip3.clone()]).await;
} else {
response = self.fetch_markets(&[paramsHip3]).await;
}
let mut result: indexmap::IndexMap<String, Value> = {
let mut m = indexmap::IndexMap::new();
m
};
{
let mut i: i64 = 0;
let mut __for_first_809: bool = true;
while { if !__for_first_809 { i += 1; } __for_first_809 = false; i < (response.len() as i64) } {
let mut market: Value = response.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut info: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut ticker: Value = self.parse_ticker(info, &[market]);
let mut symbol: Option<String> = self.safe_string_k_opt(ticker.clone(), "symbol", &[]);
result.insert(symbol.as_deref().unwrap_or("null").to_string(), ticker);
}
}
return self.filter_by_array_tickers(Value::Map(result), Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub async fn fetch_funding_rate(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_markets(&[]).await;
let mut market: Value = self.market(symbol.clone());
let mut rates: Value = self.fetch_funding_rates(&[Value::from(vec![market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)]), params]).await;
let mut rate: Value = self.safe_dict(rates, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[]);
if (rate == Value::Null) {
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRate() could not find a funding rate for ".into())).into()), symbol)));
}
return rate;
Value::Null
}
pub async fn fetch_funding_rates(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("metaAndAssetCtxs".into()));
m
});
let mut dexName: Value = self.get_dex_from_symbols(Value::Str("fetchFundingRates".into()), &[symbolsNormalized.clone()]).map(Value::from).unwrap_or(Value::Null);
if (dexName != Value::Null) {
request.insert("dex".into(), dexName);
}
let __ws_arg_12 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_post_info(&[__ws_arg_12]).await;
let mut meta: Value = self.safe_dict(response.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut universe: Value = self.safe_list_k(meta, "universe", &[Value::from(vec![])]);
let mut assetCtxs: Value = self.safe_list(response, Value::Int(1), &[Value::from(vec![])]);
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_810: bool = true;
while { if !__for_first_810 { i += 1; } __for_first_810 = false; i < (universe.len() as i64) } {
let __ws_arg_13 = self.safe_dict(universe.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let __ws_arg_14 = self.safe_dict(assetCtxs.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.extend(__ws_arg_13, &[__ws_arg_14]);
result.push(data);
}
}
return self.parse_funding_rates(Value::from(result), &[symbolsNormalized]);
Value::Null
}
pub fn parse_funding_rate(&self, mut info: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut base: Option<String> = self.safe_string_k_opt(info.clone(), "name", &[]);
let mut marketId: Value = self.coin_to_market_id(base.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut symbol: Value = self.safe_symbol(marketId, &[market]);
let mut funding: Value = self.safe_number_k(info.clone(), "funding", &[]);
let mut markPx: Value = self.safe_number_k(info.clone(), "markPx", &[]);
let mut oraclePx: Value = self.safe_number_k(info.clone(), "oraclePx", &[]);
let mut currentHour: Value = self.parse_to_int((match (((match (((match ((self.milliseconds()).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(),
(Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
let mut fundingTimestamp: Value = (match (&((match (&((match (&(((match (&(currentHour), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y),
_ => Value::Null }))), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x),
Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x),
Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), info);
m.insert("symbol".to_string(), symbol);
m.insert("markPrice".to_string(), markPx);
m.insert("indexPrice".to_string(), oraclePx);
m.insert("interestRate".to_string(), Value::Null);
m.insert("estimatedSettlePrice".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("fundingRate".to_string(), funding);
m.insert("fundingTimestamp".to_string(), fundingTimestamp.clone());
m.insert("fundingDatetime".to_string(), self.iso8601(fundingTimestamp));
m.insert("nextFundingRate".to_string(), Value::Null);
m.insert("nextFundingTimestamp".to_string(), Value::Null);
m.insert("nextFundingDatetime".to_string(), Value::Null);
m.insert("previousFundingRate".to_string(), Value::Null);
m.insert("previousFundingTimestamp".to_string(), Value::Null);
m.insert("previousFundingDatetime".to_string(), Value::Null);
m.insert("interval".to_string(), Value::Str("1h".into()));
m
});
Value::Null
}
pub fn parse_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut name: Option<String> = self.safe_string_k_opt(ticker.clone(), "name", &[]);
let mut marketId: Value = self.coin_to_market_id(name.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut bidAsk: Value = self.safe_list_k(ticker.clone(), "impactPxs", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("previousClose".to_string(), self.safe_number_k(ticker.clone(), "prevDayPx", &[]));
m.insert("close".to_string(), self.safe_number_k(ticker.clone(), "midPx", &[]));
m.insert("last".to_string(), self.safe_number_k(ticker.clone(), "price", &[]));
m.insert("bid".to_string(), self.safe_number(bidAsk.clone(), Value::Int(0), &[]));
m.insert("ask".to_string(), self.safe_number(bidAsk, Value::Int(1), &[]));
m.insert("quoteVolume".to_string(), self.safe_number_k(ticker.clone(), "dayNtlVlm", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol);
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[self.milliseconds()]);
let mut useTail: Value = Value::Bool(since == Value::Null);
let mut originalSince: Value = since.clone();
let mut startTime: Value = since.clone();
if (since == Value::Null) {
if (limit != Value::Null) {
let mut timeframeInMilliseconds: Value = (match (&(self.parse_timeframe(timeframe.clone())), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
startTime = self.sum(&[until.clone(), (match (&((match (&(timeframeInMilliseconds), &(limit)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null })), &(Value::Int(-1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
if startTime.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
startTime = Value::Int(0);
}
useTail = Value::Bool(false);
} else {
startTime = Value::Int(0);
}
}
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("until".into())]), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("candleSnapshot".into()));
m.insert("req".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("coin".to_string(), (if matches!((self.safe_bool_k(market.clone(), "swap", &[Value::Bool(false)])), Value::Bool(true)) { self.safe_string_k(market.clone(), "baseName", &[]) } else { market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null) }));
m.insert("interval".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("startTime".to_string(), startTime);
m.insert("endTime".to_string(), until);
m
}));
m
});
let __ws_arg_15 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_15]).await;
let mut candles: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
candles = response.clone();
}
return self.parse_ohlc_vs(candles, &[market, timeframe, originalSince, limit, useTail]);
Value::Null
}
pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::from(vec![self.safe_integer_k(ohlcv.clone(), "t", &[]), self.safe_number_k(ohlcv.clone(), "o", &[]), self.safe_number_k(ohlcv.clone(), "h", &[]), self.safe_number_k(ohlcv.clone(), "l", &[]), self.safe_number_k(ohlcv.clone(), "c", &[]), self.safe_number_k(ohlcv, "v", &[])]);
Value::Null
}
pub async fn fetch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut since = get_arg(optional_args, 0, Value::Null);
let mut limit = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchTrades".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchTrades".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.map(Value::from).unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
request.insert("type".into(), Value::Str("userFillsByTime".into()));
request.insert("startTime".into(), since.clone());
} else {
request.insert("type".into(), Value::Str("userFills".into()));
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
}
let __ws_arg_16 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_16]).await;
let mut fills: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
fills = response.clone();
}
return self.parse_trades(fills, &[market, since, limit]);
Value::Null
}
pub fn amount_to_precision(&self, mut symbol: Value, mut amount: Value) -> Value {
let mut market: Value = self.market(symbol);
let mut result: Value = self.decimal_to_precision(amount.clone(), Value::Int(crate::runtime::ROUND), self.safe_number(market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null), Value::Str("amount".into()), &[]), &[self.precisionMode.clone(), self.paddingMode.clone()]);
if crate::precise::Precise::stringEq(&result, &Value::Str("0".into())).as_bool() == Some(true) && crate::precise::Precise::stringGt(&self.number_to_string(amount), &Value::Str("0".into())).as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::invalid_order(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" amount of ".into())).into()), market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null)).into()),
Value::Str(" must be greater than minimum amount precision of ".into())).into()), self.number_to_string(self.safe_number(market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null), Value::Str("amount".into()), &[])))));
}
return result;
Value::Null
}
pub fn price_to_precision(&self, mut symbol: Value, mut price: Value) -> Value {
let mut market: Value = self.market(symbol);
let mut priceStr: Value = self.number_to_string(price.clone());
let mut priceStrParts: Vec<Value> = Value::Array(if let Some(__s) = priceStr.as_str() { __s.split(".").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
let mut integerPart: Value = priceStrParts.get(0).cloned().unwrap_or(Value::Null);
let mut significantDigits: Value = crate::runtime::Math::max(&Value::Int(5), &Value::Int(integerPart.len() as i64));
let mut result: Value = self.decimal_to_precision(price, Value::Int(crate::runtime::ROUND), significantDigits, &[Value::Int(crate::runtime::SIGNIFICANT_DIGITS), self.paddingMode.clone()]);
let mut maxDecimals: Value = Value::Int(6);
if matches!(self.safe_bool_k(market.clone(), "spot", &[Value::Bool(false)]), Value::Bool(true)) {
maxDecimals = Value::Int(8);
}
let mut subtractedValue: Value = (match (&(maxDecimals), &(self.precision_from_string(self.safe_string(market.as_map().and_then(|__m| __m.get("precision")).cloned().unwrap_or(Value::Null), Value::Str("amount".into()), &[])))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y),
(Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
return self.decimal_to_precision(result, Value::Int(crate::runtime::ROUND), subtractedValue, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);
Value::Null
}
pub fn hash_message(&self, mut message: Value) -> Option<String> {
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null),
privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("r".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), self.safe_string_k(signature.clone(), "r", &[Value::Str("".into())])).into()));
m.insert("s".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), self.safe_string_k(signature.clone(), "s", &[Value::Str("".into())])).into()));
m.insert("v".to_string(), self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]));
m
});
Value::Null
}
pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
return self.sign_hash(self.hash_message(message).map(Value::from).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null));
Value::Null
}
pub fn construct_phantom_agent(&self, mut hash: Value, optional_args: &[Value]) -> Value {
let isTestnet: bool = get_arg(optional_args, 0, Value::Bool(true)).is_truthy();
let mut source: Value = (if isTestnet { Value::Str("b".into()) } else { Value::Str("a".into()) });
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("source".to_string(), source);
m.insert("connectionId".to_string(), hash);
m
});
Value::Null
}
pub fn action_hash(&self, mut action: Value, mut vaultAddress: Value, mut nonce: Value, optional_args: &[Value]) -> Value {
let mut expiresAfter = get_arg(optional_args, 0, Value::Null);
let mut dataBinary: Value = self.packb(action, &[]);
let mut dataHex: Value = self.binary_to_base16(dataBinary, &[]);
let mut data: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", dataHex, Value::Str("00000".into())).into()), self.int_to_base16(nonce, &[])).into());
if (vaultAddress == Value::Null) {
data = Value::Str(format!("{}{}", data, Value::Str("00".into())).into());
} else {
data = Value::Str(format!("{}{}", data, Value::Str("01".into())).into());
data = Value::Str(format!("{}{}", data, vaultAddress).into());
}
if (expiresAfter != Value::Null) {
data = Value::Str(format!("{}{}", data, Value::Str(format!("{}{}", Value::Str("0000000".into()), self.int_to_base16(expiresAfter, &[])).into())).into());
}
return self.hash(self.base16_to_binary(data, &[]), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
Value::Null
}
pub fn sign_l1_action(&self, mut action: Value, mut nonce: Value, optional_args: &[Value]) -> Value {
let mut vaultAdress = get_arg(optional_args, 0, Value::Null);
let mut expiresAfter = get_arg(optional_args, 1, Value::Null);
let mut hash: Value = self.action_hash(action, vaultAdress, nonce, &[expiresAfter]);
let mut isTestnet: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
let mut phantomAgent: Value = self.construct_phantom_agent(hash, &[isTestnet]);
let mut zeroAddress: Option<String> = self.safe_string_k_opt(self.options.clone(), "zeroAddress", &[]);
let mut chainId: Value = Value::Int(1337); let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), chainId);
m.insert("name".to_string(), Value::Str("Exchange".into()));
m.insert("verifyingContract".to_string(), zeroAddress.map(Value::from).unwrap_or(Value::Null));
m.insert("version".to_string(), Value::Str("1".into()));
m
});
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Agent".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("source".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("connectionId".into()));
m.insert("type".to_string(), Value::Str("bytes32".into()));
m
})]));
m
});
let mut msg: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), phantomAgent);
let mut signature: Value = self.sign_message(msg, self.privateKey.clone());
return signature;
Value::Null
}
pub fn sign_user_signed_action(&self, mut messageTypes: Value, mut message: Value) -> Value {
let mut zeroAddress: Option<String> = self.safe_string_k_opt(self.options.clone(), "zeroAddress", &[]);
let mut chainId: Value = Value::Int(421614); let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("chainId".to_string(), chainId);
m.insert("name".to_string(), Value::Str("HyperliquidSignTransaction".into()));
m.insert("verifyingContract".to_string(), zeroAddress.map(Value::from).unwrap_or(Value::Null));
m.insert("version".to_string(), Value::Str("1".into()));
m
});
let mut msg: Value = self.eth_encode_structured_data(Value::Map(domain), messageTypes, message);
let mut signature: Value = self.sign_message(msg, self.privateKey.clone());
return signature;
Value::Null
}
pub fn build_usd_send_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UsdSend".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_usd_class_send_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UsdClassTransfer".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("toPerp".into()));
m.insert("type".to_string(), Value::Str("bool".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_send_asset_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:SendAsset".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("sourceDex".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destinationDex".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("token".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("fromSubAccount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_withdraw_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:Withdraw".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("destination".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("amount".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("time".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_user_dex_abstraction_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UserDexAbstraction".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("enabled".into()));
m.insert("type".to_string(), Value::Str("bool".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_user_abstraction_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:UserSetAbstraction".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("user".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("abstraction".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub fn build_approve_builder_fee_sig(&self, mut message: Value) -> Value {
let mut messageTypes: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("HyperliquidTransaction:ApproveBuilderFee".to_string(), Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("hyperliquidChain".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maxFeeRate".into()));
m.insert("type".to_string(), Value::Str("string".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("builder".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint64".into()));
m
})]));
m
});
return self.sign_user_signed_action(Value::Map(messageTypes), message);
Value::Null
}
pub async fn set_ref(&mut self) -> Value {
if matches!(self.safe_bool_k(self.options.clone(), "refSet", &[Value::Bool(false)]), Value::Bool(true)) {
return Value::Bool(true);
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("refSet".into(), Value::Bool(true)); }
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("setReferrer".into()));
m.insert("code".to_string(), self.safe_string_k(self.options.clone(), "ref", &[Value::Str("CCXT1".into())]));
m
});
let mut nonce: Value = self.incrementing_nonce();
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce.clone(), &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
let mut success: Value = Value::Bool(false);
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
self.private_post_exchange(&[Value::Map(request)]).await;
success = Value::Bool(true);
#[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
success = Value::Bool(false); }
return success;
Value::Null
}
pub async fn approve_builder_fee(&mut self, mut builder: Value, mut maxFeeRate: Value) -> Value {
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut payload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("maxFeeRate".to_string(), maxFeeRate);
m.insert("builder".to_string(), builder);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_approve_builder_fee_sig(Value::Map(payload.clone()));
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), payload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("maxFeeRate".to_string(), payload.get("maxFeeRate").cloned().unwrap_or(Value::Null));
m.insert("builder".to_string(), payload.get("builder").cloned().unwrap_or(Value::Null));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("approveBuilderFee".into()));
m
});
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[Value::Map(request)]).await;
Value::Null
}
pub async fn initialize_client(&mut self) -> Value {
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
promise_all(&Value::from(vec![self.handle_builder_fee_approval().await, self.set_ref().await, self.is_unified_enabled(Value::Str("fetchBalance".into()), &[Value::Null, Value::Bool(false), Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).await])).await; #[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
return Value::Bool(false);
}
return Value::Bool(true);
Value::Null
}
pub async fn handle_builder_fee_approval(&mut self) -> Value {
let mut buildFee: bool = self.safe_bool_k_opt(self.options.clone(), "builderFee", &[Value::Bool(true)]).unwrap_or(true);
let mut approvedBuilderFee: bool = self.safe_bool_k_opt(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)]).unwrap_or(false);
if approvedBuilderFee {
return Value::Bool(true);
}
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut builder: Value = self.safe_string_k(self.options.clone(), "builder", &[Value::Str("0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".into())]);
let mut maxFeeRate: Value = self.safe_string_k(self.options.clone(), "feeRate", &[Value::Str("0.01%".into())]);
if !(buildFee) {
maxFeeRate = Value::Str("0%".into());
}
self.approve_builder_fee(builder, maxFeeRate).await;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("approvedBuilderFee".into(), Value::Bool(true)); }
#[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }; }
return Value::Bool(true);
Value::Null
}
pub async fn is_unified_enabled(&mut self, mut method: Value, optional_args: &[Value]) -> Value {
let mut address = get_arg(optional_args, 0, Value::Null);
let shouldRefresh: bool = get_arg(optional_args, 1, Value::Bool(false)).is_truthy();
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut publicAddress: Value = Value::Null;
let mut paramsPublicAddress: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if (address == Value::Null) {
publicAddress = self.safe_string(self.handle_public_address(Value::Str("isUnifiedEnabled".into()), params.clone()), Value::Int(0), &[]);
paramsPublicAddress = self.safe_dict(self.handle_public_address(Value::Str("isUnifiedEnabled".into()), params.clone()), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
}
let mut userAddress: Value = (if (address != Value::Null) { address.clone() } else { publicAddress });
let mut paramsAddress: Value = (if (address != Value::Null) { params } else { paramsPublicAddress });
let enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable: Vec<Value> = self.handle_option_bool_and_params(paramsAddress, method, Value::Str("enableUnifiedMargin".into()), &[]).as_array().cloned().unwrap_or_default();
let mut enableUnifiedMarginOption: Value = enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsEnableUnifiedMargin: Value = enableUnifiedMarginOptionparamsEnableUnifiedMarginVariable.get(1).cloned().unwrap_or(Value::Null);
let mut enableUnifiedMargin: Value = enableUnifiedMarginOption;
if (enableUnifiedMargin == Value::Null) || shouldRefresh {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userAbstraction".into()));
m.insert("user".to_string(), userAddress);
m
});
let mut response: Value = Value::Null;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let __ws_arg_17 = self.extend(paramsEnableUnifiedMargin.clone(), &[Value::Map(request)]);
let mut rawResponse: Value = self.public_post_info(&[__ws_arg_17]).await;
if matches!(&rawResponse, Value::Str(_)) {
response = rawResponse.clone();
}
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
if matches!(&e, Value::Str(__s) if __s.contains("[InvalidProxySettings]")) {
panic!("{}", e);
}
response = Value::Null; }
if (response != Value::Null) {
response = response.as_str().map(|__s| Value::Str(__s.replace("\"", "").into())).unwrap_or_else(|| response.clone());
response = response.as_str().map(|__s| Value::Str(__s.replace("\"", "").into())).unwrap_or_else(|| response.clone());
enableUnifiedMargin = Value::Bool(response.as_str() == Some("unifiedAccount"));
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("enableUnifiedMargin".into(), enableUnifiedMargin.clone()); }; }
return Value::from(vec![enableUnifiedMargin, paramsEnableUnifiedMargin]);
Value::Null
}
pub async fn set_user_abstraction(&mut self, mut abstraction: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let userAddressparamsPublicAddressVariable: Vec<Value> = self.handle_public_address(Value::Str("setUserAbstraction".into()), params).as_array().cloned().unwrap_or_default();
let mut userAddress: Value = userAddressparamsPublicAddressVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.get(1).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut type_var: Value = self.safe_string_k(paramsPublicAddress, "type", &[Value::Str("userSetAbstraction".into())]);
let mut payload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("user".to_string(), userAddress);
m.insert("abstraction".to_string(), abstraction);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_user_abstraction_sig(Value::Map(payload.clone()));
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), payload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("abstraction".to_string(), payload.get("abstraction").cloned().unwrap_or(Value::Null));
m.insert("user".to_string(), payload.get("user").cloned().unwrap_or(Value::Null));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var);
m
});
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[Value::Map(request)]).await;
Value::Null
}
pub async fn enable_user_dex_abstraction(&mut self, mut enabled: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let userAddressparamsPublicAddressVariable: Vec<Value> = self.handle_public_address(Value::Str("enableUserDexAbstraction".into()), params).as_array().cloned().unwrap_or_default();
let mut userAddress: Value = userAddressparamsPublicAddressVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPublicAddress: Value = userAddressparamsPublicAddressVariable.get(1).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut isSandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut type_var: Value = self.safe_string_k(paramsPublicAddress, "type", &[Value::Str("userDexAbstraction".into())]);
let mut payload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("user".to_string(), userAddress);
m.insert("enabled".to_string(), enabled);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sig: Value = self.build_user_dex_abstraction_sig(Value::Map(payload.clone()));
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), payload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("enabled".to_string(), payload.get("enabled").cloned().unwrap_or(Value::Null));
m.insert("user".to_string(), payload.get("user").cloned().unwrap_or(Value::Null));
m.insert("nonce".to_string(), nonce.clone());
m.insert("type".to_string(), type_var);
m
});
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m.insert("vaultAddress".to_string(), Value::Null);
m
});
return self.private_post_exchange(&[Value::Map(request)]).await;
Value::Null
}
pub async fn set_agent_abstraction(&mut self, mut abstraction: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("agentSetAbstraction".into()));
m.insert("abstraction".to_string(), abstraction);
m
});
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce, &[]);
request.insert("action".into(), Value::Map(action));
request.insert("signature".into(), signature);
let __ws_arg_18 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_18]).await;
return response;
Value::Null
}
pub async fn create_order(&mut self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let orderglobalParamsVariable: Vec<Value> = self.parse_create_edit_order_args(Value::Null, symbol, type_var, side, amount, &[price, params]).as_array().cloned().unwrap_or_default();
let mut order: Value = orderglobalParamsVariable.get(0).cloned().unwrap_or(Value::Null);
let mut globalParams: Value = orderglobalParamsVariable.get(1).cloned().unwrap_or(Value::Null);
let mut orders: Value = self.create_orders(Value::from(vec![order]), &[globalParams]).await;
let mut created: Value = self.safe_dict(orders, Value::Int(0), &[]);
return created;
Value::Null
}
pub async fn create_twap_order(&mut self, mut symbol: Value, mut side: Value, mut amount: Value, mut duration: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut market: Value = self.market(symbol.clone());
let mut nonce: Value = self.incrementing_nonce();
let mut isBuy: Value = (Value::Bool((if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null }).as_str() == Some("BUY")));
let mut randomize: bool = self.safe_bool_k_opt(params.clone(), "randomize", &[Value::Bool(false)]).unwrap_or(false);
let mut paramsOmitted: Value = self.omit(params, Value::Str("randomize".into()), &[]);
let vaultAddressOptionparamsVaultVariable: Vec<Value> = self.handle_option_string_and_params(paramsOmitted, Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default();
let mut vaultAddressOption: Value = vaultAddressOptionparamsVaultVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsVault: Value = vaultAddressOptionparamsVaultVariable.get(1).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut durationMins: Value = ((match (((match ((duration).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64(), (Value::Int(60)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.floor())).unwrap_or(Value::Null); let mut orderObj: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("s".to_string(), self.amount_to_precision(symbol, amount));
m.insert("r".to_string(), self.safe_bool_k(paramsVault.clone(), "reduceOnly", &[Value::Bool(false)]));
m.insert("m".to_string(), durationMins);
m.insert("t".to_string(), Value::Bool(randomize));
m
});
let mut orderAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapOrder".into()));
m.insert("twap".to_string(), Value::Map(orderObj));
m
});
let mut signature: Value = self.sign_l1_action(Value::Map(orderAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(orderAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
request.insert("vaultAddress".into(), vaultAddress);
}
let mut expiresAfter: Value = self.safe_integer_k(paramsVault, "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
request.insert("expiresAfter".into(), expiresAfter);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Value = self.safe_dict_k(data, "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut running: Value = self.safe_dict_k(status, "running", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut orderId: Option<String> = self.safe_string_k_opt(running, "twapId", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("running".into()));
m.insert("oid".to_string(), orderId.map(Value::from).unwrap_or(Value::Null));
m
}), &[market]);
Value::Null
}
pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.create_orders_request(orders, &[params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Vec<Value> = self.safe_list_k(data, "statuses", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut ordersToBeParsed: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_811: bool = true;
while { if !__for_first_811 { i += 1; } __for_first_811 = false; i < (statuses.len() as i64) } {
let mut order: Value = statuses.get(i as usize).cloned().unwrap_or(Value::Null);
if (order.as_str() == Some("waitingForTrigger")) {
ordersToBeParsed.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), order.clone());
m
})); } else {
ordersToBeParsed.push(order);
}
}
}
return self.parse_orders(Value::from(ordersToBeParsed), &[]);
Value::Null
}
pub fn create_order_request(&self, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (type_var == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a type argument".into()))));
}
if (side == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires a side argument".into()))));
}
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol.clone()).as_map().cloned().unwrap_or_default();
let mut typeValue: Value = (if let Some(__s) = type_var.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
let mut sideValue: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
let mut isMarket: Value = (Value::Bool(typeValue.as_str() == Some("MARKET")));
let mut isBuy: Value = (Value::Bool(sideValue.as_str() == Some("BUY")));
let mut clientOrderId: Option<String> = self.safe_string2_opt(params.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[]);
let mut defaultTimeInForce: String = "gtc".to_string();
if matches!(&isMarket, Value::Bool(true)) {
defaultTimeInForce = "ioc".to_string();
}
let mut postOnly: bool = self.safe_bool_k_opt(params.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
if postOnly {
defaultTimeInForce = "alo".to_string();
}
let mut timeInForceLower: Value = self.safe_string_lower_k(params.clone(), "timeInForce", &[Value::from(defaultTimeInForce)]);
let mut timeInForce: String = self.capitalize(timeInForceLower).to_string();
let mut triggerPrice: Value = self.safe_string2(params.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(params.clone(), "stopLossPrice", &[triggerPrice.clone()]);
let mut takeProfitPrice: Option<String> = self.safe_string_k_opt(params.clone(), "takeProfitPrice", &[]);
let mut isTrigger: bool = (stopLossPrice != Value::Null) || (takeProfitPrice.is_some());
let mut px: Value = Value::Null;
if matches!(&isMarket, Value::Bool(true)) {
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" market orders require price to calculate the max slippage price. Default slippage can be set in options (default is 5%).".into()))));
}
px = (if (isBuy).as_bool() == Some(true) { crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringAdd(&Value::Str("1".into()), &slippage)) } else { crate::precise::Precise::stringMul(&price, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &slippage)) });
px = self.price_to_precision(symbol.clone(), px.clone()); } else {
px = self.price_to_precision(symbol.clone(), price);
}
let mut sz: Value = self.amount_to_precision(symbol.clone(), amount);
let mut reduceOnly: bool = self.safe_bool_k_opt(params, "reduceOnly", &[Value::Bool(false)]).unwrap_or(false);
let mut orderType: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if isTrigger {
let mut isTp: bool = false;
if (takeProfitPrice.is_some()) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice.map(Value::from).unwrap_or(Value::Null));
isTp = true;
} else {
triggerPrice = self.price_to_precision(symbol, stopLossPrice);
}
let mut tpSlType: String = "sl".to_string();
if isTp {
tpSlType = "tp".to_string();
}
orderType.insert("trigger".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket);
m.insert("triggerPx".to_string(), triggerPrice);
m.insert("tpsl".to_string(), Value::from(tpSlType));
m
}));
} else {
orderType.insert("limit".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), Value::from(timeInForce));
m
}));
}
let mut orderObj: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.get("baseId").cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("p".to_string(), px);
m.insert("s".to_string(), sz);
m.insert("r".to_string(), Value::Bool(reduceOnly));
m.insert("t".to_string(), Value::Map(orderType));
m
});
if (clientOrderId.is_some()) {
orderObj.insert("c".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
}
return Value::Map(orderObj);
Value::Null
}
pub fn create_orders_request(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[]);
defaultSlippage = self.safe_string_k(params.clone(), "slippage", &[defaultSlippage.clone()]);
let mut hasClientOrderId: bool = false;
let mut ordersLength: f64 = ((orders.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_812: bool = true;
while { if !__for_first_812 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_812 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Option<String> = self.safe_string2_opt(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId.is_some()) {
hasClientOrderId = true;
}
}
}
if hasClientOrderId {
{
let mut i: Value = Value::Int(0);
let mut __for_first_813: bool = true;
while { if !__for_first_813 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_813 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Option<String> = self.safe_string2_opt(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrders() all orders must have clientOrderId if at least one has a clientOrderId".into()))));
}
}
}
}
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("slippage".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("slippage".into()), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("timeInForce".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut orderReq: Vec<Value> = Vec::new();
let mut grouping: Value = Value::Str("na".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_814: bool = true;
while { if !__for_first_814 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_814 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut marketId: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId.map(Value::from).unwrap_or(Value::Null));
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut type_var: Option<String> = self.safe_string_upper_k_opt(rawOrder.clone(), "type", &[]);
let mut side: Option<String> = self.safe_string_upper_k_opt(rawOrder.clone(), "side", &[]);
let mut amount: Value = self.safe_string_k(rawOrder.clone(), "amount", &[]);
let mut price: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut slippage: Value = self.safe_string_k(orderParams.clone(), "slippage", &[defaultSlippage.clone()]);
if let Value::Dict(__d) = &mut orderParams { std::sync::Arc::make_mut(__d).insert("slippage".into(), slippage); }
let mut stopLoss: Value = self.safe_dict_k(orderParams.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(orderParams.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
orderParams = self.omit(orderParams.clone(), Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into())]), &[]);
let mut mainOrderObj: Value = self.create_order_request(symbol.clone(), type_var.map(Value::from).unwrap_or(Value::Null), side.clone().map(Value::from).unwrap_or(Value::Null), amount.clone(), &[price.map(Value::from).unwrap_or(Value::Null), orderParams.clone()]);
if hasStopLoss || hasTakeProfit {
let mut stopLossOrderTriggerPrice: Option<String> = self.safe_string2_opt(stopLoss.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossOrderType: Value = self.safe_string_k(stopLoss.clone(), "type", &[Value::Str("limit".into())]);
let mut stopLossOrderLimitPrice: Value = self.safe_string2(stopLoss, Value::Str("price".into()), Value::Str("stopLossPrice".into()), &[stopLossOrderTriggerPrice.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut takeProfitOrderTriggerPrice: Option<String> = self.safe_string2_opt(takeProfit.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut takeProfitOrderType: Value = self.safe_string_k(takeProfit.clone(), "type", &[Value::Str("limit".into())]);
let mut takeProfitOrderLimitPrice: Value = self.safe_string2(takeProfit, Value::Str("price".into()), Value::Str("takeProfitPrice".into()), &[takeProfitOrderTriggerPrice.clone().map(Value::from).unwrap_or(Value::Null)]);
grouping = self.safe_string_k(orderParams.clone(), "grouping", &[Value::Str("normalTpsl".into())]);
if (grouping.as_str() == Some("positionTpsl")) {
amount = Value::Str("0".into());
stopLossOrderType = Value::Str("market".into());
takeProfitOrderType = Value::Str("market".into());
} else if (grouping.as_str() == Some("normalTpsl")) {
orderReq.push(mainOrderObj.clone());
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" only support grouping normalTpsl and positionTpsl.".into()))));
}
orderParams = self.omit(orderParams.clone(), Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("grouping".into())]), &[]);
let mut triggerOrderSide: String = "".to_string();
if (side.as_deref() == Some("BUY")) {
triggerOrderSide = "sell".to_string();
} else {
triggerOrderSide = "buy".to_string();
}
if hasTakeProfit {
let __ws_arg_19 = self.extend(orderParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("takeProfitPrice".to_string(), takeProfitOrderTriggerPrice.map(Value::from).unwrap_or(Value::Null));
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol.clone(), takeProfitOrderType, Value::from(triggerOrderSide.clone()), amount.clone(), &[takeProfitOrderLimitPrice, __ws_arg_19]);
orderReq.push(orderObj.clone());
}
if hasStopLoss {
let __ws_arg_20 = self.extend(orderParams, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), stopLossOrderTriggerPrice.map(Value::from).unwrap_or(Value::Null));
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})]);
let mut orderObj: Value = self.create_order_request(symbol, stopLossOrderType, Value::from(triggerOrderSide), amount, &[stopLossOrderLimitPrice, __ws_arg_20]);
orderReq.push(orderObj);
}
} else {
orderReq.push(mainOrderObj);
}
}
}
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params(params2.clone(), Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
let mut orderAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("order".into()));
m.insert("orders".to_string(), Value::from(orderReq));
m.insert("grouping".to_string(), grouping);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "approvedBuilderFee", &[Value::Bool(false)]), Value::Bool(true)) {
let mut builder: String = "0x6530512A6c89C7cfCEbC3BA7fcD9aDa5f30827a6".to_string();
let mut wallet: Value = self.safe_string_lower_k(self.options.clone(), "builder", &[(if let Some(__s) = Some(builder.as_str()) { Value::Str(__s.to_lowercase().into()) } else { Value::Null })]);
let mut feeInt: Option<i64> = self.safe_integer_k(self.options.clone(), "feeInt", &[Value::Int(10)]).as_i64();
if !matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
feeInt = Some(0);
}
orderAction.insert("builder".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("b".to_string(), wallet);
m.insert("f".to_string(), Value::from(feeInt));
m
}));
}
let mut signature: Value = self.sign_l1_action(Value::Map(orderAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(orderAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
request.insert("vaultAddress".into(), vaultAddress);
}
return Value::Map(request);
Value::Null
}
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if matches!(self.safe_bool_k(params.clone(), "twap", &[Value::Bool(false)]), Value::Bool(true)) {
return self.cancel_twap_order(id.clone(), &[symbol.clone(), self.omit(params.clone(), Value::Str("twap".into()), &[])]).await;
}
let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[symbol, params]).await;
let mut canceled: Value = self.safe_dict(orders, Value::Int(0), &[]);
return canceled;
Value::Null
}
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.cancel_orders_request(ids, &[symbol, params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
let mut innerResponse: Value = self.safe_dict_k(response, "response", &[]);
let mut data: Value = self.safe_dict_k(innerResponse, "data", &[]);
let mut statuses: Vec<Value> = self.safe_list_k(data, "statuses", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut orders: Value = Value::from(vec![]);
{
let mut i: i64 = 0;
let mut __for_first_815: bool = true;
while { if !__for_first_815 { i += 1; } __for_first_815 = false; i < (statuses.len() as i64) } {
let mut status: Value = statuses.get(i as usize).cloned().unwrap_or(Value::Null);
if let Value::Arr(__a) = &mut orders { std::sync::Arc::make_mut(__a).push(self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), status.clone());
m.insert("status".to_string(), status);
m
}), &[])); }
}
}
return orders;
Value::Null
}
pub async fn cancel_twap_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelTwapOrder() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol);
let vaultAddressOptionparamsUnwrappedVariable: Vec<Value> = self.handle_option_string_and_params(params, Value::Str("cancelTwapOrder".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default();
let mut vaultAddressOption: Value = vaultAddressOptionparamsUnwrappedVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsUnwrapped: Value = vaultAddressOptionparamsUnwrappedVariable.get(1).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut params2: Value = paramsUnwrapped;
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("twapCancel".into()));
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("t".to_string(), self.parse_to_numeric(id.clone()));
m
});
let mut nonce: Value = self.incrementing_nonce();
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
request.insert("vaultAddress".into(), vaultAddress);
}
let mut expiresAfter: Value = self.safe_integer_k(params2.clone(), "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
request.insert("expiresAfter".into(), expiresAfter);
params2 = self.omit(params2, Value::Str("expiresAfter".into()), &[]);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
let mut responseObj: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responseObj, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut status: Option<String> = self.safe_string_k_opt(data, "status", &[]);
return self.parse_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), status.map(Value::from).unwrap_or(Value::Null));
m.insert("oid".to_string(), id);
m
}), &[market]);
Value::Null
}
pub fn cancel_orders_request(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol.clone()).as_map().cloned().unwrap_or_default();
let mut clientOrderId: Value = self.safe_value2(params.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut fast: bool = self.safe_bool_k_opt(params.clone(), "fast", &[Value::Bool(false)]).unwrap_or(false);
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("fast".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelReq: Vec<Value> = vec![];
let mut cancelAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".into()));
m.insert("cancels".to_string(), Value::from(vec![]));
m
});
let mut baseId: Value = self.parse_to_numeric(market.get("baseId").cloned().unwrap_or(Value::Null));
if (clientOrderId != Value::Null) {
if !(matches!(&clientOrderId, Value::Arr(_))) {
clientOrderId = Value::from(vec![clientOrderId.clone()]);
}
cancelAction.insert("type".into(), Value::Str("cancelByCloid".into()));
{
let mut i: Value = Value::Int(0);
let mut __for_first_816: bool = true;
while { if !__for_first_816 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_816 = false; i.as_f64().unwrap_or(f64::NAN) < Value::Int(clientOrderId.len() as i64).as_f64().unwrap_or(f64::NAN) } {
cancelReq.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("asset".to_string(), baseId.clone());
m.insert("cloid".to_string(), self.safe_string(clientOrderId.clone(), i.clone(), &[]));
m
}));
}
}
} else {
cancelAction.insert("type".into(), Value::Str("cancel".into()));
{
let mut i: i64 = 0;
let mut __for_first_817: bool = true;
while { if !__for_first_817 { i += 1; } __for_first_817 = false; i < (ids.len() as i64) } {
let mut o: Value = self.parse_to_numeric(self.safe_string(ids.clone(), Value::Int(i), &[]));
cancelReq.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), baseId.clone());
m.insert("o".to_string(), o);
m
}));
}
}
}
cancelAction.insert("cancels".into(), Value::Array(cancelReq));
if fast {
cancelAction.insert("f".into(), Value::Bool(true));
}
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params2(params2.clone(), Value::Str("cancelOrders".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(cancelAction.clone()), nonce, &[vaultAddress.clone()]);
request.insert("action".into(), Value::Map(cancelAction));
request.insert("signature".into(), signature);
if (vaultAddress != Value::Null) {
params2 = self.omit(params2.clone(), Value::Str("vaultAddress".into()), &[]);
request.insert("vaultAddress".into(), vaultAddress);
}
return Value::Map(request);
Value::Null
}
pub async fn cancel_orders_for_symbols(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelReq: Value = Value::from(vec![]);
let mut cancelAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("".into()));
m.insert("cancels".to_string(), Value::from(vec![]));
m
});
let mut cancelByCloid: bool = false;
{
let mut i: i64 = 0;
let mut __for_first_818: bool = true;
while { if !__for_first_818 { i += 1; } __for_first_818 = false; i < (orders.len() as i64) } {
let mut order: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
let mut clientOrderId: Value = self.safe_string_k(order.clone(), "clientOrderId", &[]);
if (clientOrderId != Value::Null) {
cancelByCloid = true;
}
let mut id: Option<String> = self.safe_string_k_opt(order.clone(), "id", &[]);
let mut symbol: Option<String> = self.safe_string_k_opt(order, "symbol", &[]);
if (symbol.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() requires a symbol argument in each order".into()))));
}
if (id.is_some()) && cancelByCloid {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrdersForSymbols() all orders must have either id or clientOrderId".into()))));
}
let mut assetKey: Value = (if cancelByCloid { Value::Str("asset".into()) } else { Value::Str("a".into()) });
let mut idKey: Value = (if cancelByCloid { Value::Str("cloid".into()) } else { Value::Str("o".into()) });
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol.map(Value::from).unwrap_or(Value::Null)).as_map().cloned().unwrap_or_default();
let mut cancelObj: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
if let Value::Dict(__d) = &mut cancelObj { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&assetKey), self.parse_to_numeric(market.get("baseId").cloned().unwrap_or(Value::Null))); }
if let Value::Dict(__d) = &mut cancelObj { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&idKey), (if cancelByCloid { clientOrderId } else { self.parse_to_numeric(id.map(Value::from).unwrap_or(Value::Null)) })); }
if let Value::Arr(__a) = &mut cancelReq { std::sync::Arc::make_mut(__a).push(cancelObj); }
}
}
cancelAction.insert("type".into(), (if cancelByCloid { Value::Str("cancelByCloid".into()) } else { Value::Str("cancel".into()) }));
cancelAction.insert("cancels".into(), cancelReq);
let mut fast: bool = self.safe_bool_k_opt(params.clone(), "fast", &[Value::Bool(false)]).unwrap_or(false);
if fast {
cancelAction.insert("f".into(), Value::Bool(true));
}
let mut vaultAddressOption: Value = self.handle_option_string_and_params2(params, Value::Str("cancelOrdersForSymbols".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(cancelAction.clone()), nonce, &[vaultAddress.clone()]);
request.insert("action".into(), Value::Map(cancelAction));
request.insert("signature".into(), signature);
if (vaultAddress != Value::Null) {
request.insert("vaultAddress".into(), vaultAddress);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
return Value::from(vec![self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response);
m
}), &[])]);
Value::Null
}
pub async fn cancel_all_orders_after(&mut self, mut timeout: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("clientOrderId".into()), Value::Str("client_id".into())]), &[]);
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut cancelAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("scheduleCancel".into()));
m.insert("time".to_string(), (match (&(nonce), &(timeout)) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null }));
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params2(params2.clone(), Value::Str("cancelAllOrdersAfter".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(cancelAction.clone()), nonce, &[vaultAddress.clone()]);
request.insert("action".into(), Value::Map(cancelAction));
request.insert("signature".into(), signature);
if (vaultAddress != Value::Null) {
params2 = self.omit(params2, Value::Str("vaultAddress".into()), &[]);
request.insert("vaultAddress".into(), vaultAddress);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
return response;
Value::Null
}
pub fn edit_orders_request(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
let mut hasClientOrderId: bool = false;
let mut ordersLength: f64 = ((orders.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_819: bool = true;
while { if !__for_first_819 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_819 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Option<String> = self.safe_string2_opt(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId.is_some()) {
hasClientOrderId = true;
}
}
}
if hasClientOrderId {
{
let mut i: Value = Value::Int(0);
let mut __for_first_820: bool = true;
while { if !__for_first_820 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_820 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder.clone(), "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut clientOrderId: Option<String> = self.safe_string2_opt(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
if (clientOrderId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrders() all orders must have clientOrderId if at least one has a clientOrderId".into()))));
}
}
}
}
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("slippage".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("slippage".into()), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("timeInForce".into())]), &[]);
let mut modifies: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_821: bool = true;
while { if !__for_first_821 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_821 = false; i.as_f64().unwrap_or(f64::NAN) < ordersLength } {
let mut rawOrder: Value = self.safe_dict(orders.clone(), i.clone(), &[]);
let mut id: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "id", &[]);
let mut marketId: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "symbol", &[]);
let mut market: Value = self.market(marketId.map(Value::from).unwrap_or(Value::Null));
let mut symbol: Value = market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut type_var: Option<String> = self.safe_string_upper_k(rawOrder.clone(), "type", &[]).as_str().map(str::to_owned);
let mut isMarket: Value = (Value::Bool(type_var.as_deref() == Some("MARKET")));
let mut side: Option<String> = self.safe_string_upper_k(rawOrder.clone(), "side", &[]).as_str().map(str::to_owned);
let mut isBuy: Value = (Value::Bool(side.as_deref() == Some("BUY")));
let mut amount: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "amount", &[]);
let mut price: Option<String> = self.safe_string_k_opt(rawOrder.clone(), "price", &[]);
let mut orderParams: Value = self.safe_dict_k(rawOrder, "params", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut defaultSlippage: Option<String> = self.safe_string_k_opt(self.options.clone(), "defaultSlippage", &[]);
let mut slippage: Value = self.safe_string_k(orderParams.clone(), "slippage", &[defaultSlippage.map(Value::from).unwrap_or(Value::Null)]);
let mut defaultTimeInForce: String = "gtc".to_string();
if matches!(&isMarket, Value::Bool(true)) {
defaultTimeInForce = "ioc".to_string();
}
let mut postOnly: bool = self.safe_bool_k_opt(orderParams.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
if postOnly {
defaultTimeInForce = "alo".to_string();
}
let mut timeInForceLower: Value = self.safe_string_lower_k(orderParams.clone(), "timeInForce", &[Value::from(defaultTimeInForce)]);
let mut timeInForce: String = self.capitalize(timeInForceLower).to_string();
let mut clientOrderId: Option<String> = self.safe_string2_opt(orderParams.clone(), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), &[]);
let mut triggerPrice: Value = self.safe_string2(orderParams.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(orderParams.clone(), "stopLossPrice", &[triggerPrice.clone()]);
let mut takeProfitPrice: Option<String> = self.safe_string_k_opt(orderParams.clone(), "takeProfitPrice", &[]);
let mut isTrigger: bool = (stopLossPrice != Value::Null) || (takeProfitPrice.is_some());
let mut reduceOnly: bool = self.safe_bool_k_opt(orderParams.clone(), "reduceOnly", &[Value::Bool(false)]).unwrap_or(false);
orderParams = self.omit(orderParams, Value::from(vec![Value::Str("slippage".into()), Value::Str("timeInForce".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("clientOrderId".into()), Value::Str("client_id".into()), Value::Str("postOnly".into()), Value::Str("reduceOnly".into())]), &[]);
let mut px: Value = self.number_to_string(price.map(Value::from).unwrap_or(Value::Null));
if matches!(&isMarket, Value::Bool(true)) {
px = (if (isBuy).as_bool() == Some(true) { crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringAdd(&Value::Str("1".into()), &slippage)) } else { crate::precise::Precise::stringMul(&px, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &slippage)) });
px = self.price_to_precision(symbol.clone(), px.clone());
} else {
px = self.price_to_precision(symbol.clone(), px.clone());
}
let mut sz: Value = self.amount_to_precision(symbol.clone(), amount.map(Value::from).unwrap_or(Value::Null));
let mut orderType: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if isTrigger {
let mut isTp: bool = false;
if (takeProfitPrice.is_some()) {
triggerPrice = self.price_to_precision(symbol.clone(), takeProfitPrice.map(Value::from).unwrap_or(Value::Null));
isTp = true;
} else {
triggerPrice = self.price_to_precision(symbol, stopLossPrice);
}
let mut tpSlType: String = "sl".to_string();
if isTp {
tpSlType = "tp".to_string();
}
orderType.insert("trigger".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("isMarket".to_string(), isMarket);
m.insert("triggerPx".to_string(), triggerPrice.clone());
m.insert("tpsl".to_string(), Value::from(tpSlType));
m
}));
} else {
orderType.insert("limit".into(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tif".to_string(), Value::from(timeInForce));
m
}));
}
if (triggerPrice == Value::Null) {
triggerPrice = Value::Str("0".into());
}
let mut orderReq: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("a".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null)));
m.insert("b".to_string(), isBuy);
m.insert("p".to_string(), px);
m.insert("s".to_string(), sz);
m.insert("r".to_string(), Value::Bool(reduceOnly));
m.insert("t".to_string(), Value::Map(orderType));
m
});
if (clientOrderId.is_some()) {
orderReq.insert("c".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
}
let mut modifyReq: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("oid".to_string(), self.parse_to_int(id.map(Value::from).unwrap_or(Value::Null)));
m.insert("order".to_string(), Value::Map(orderReq));
m
});
modifies.push(modifyReq);
}
}
let mut nonce: Value = self.incrementing_nonce();
let mut modifyAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("batchModify".into()));
m.insert("modifies".to_string(), Value::from(modifies));
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params(params2.clone(), Value::Str("editOrder".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(modifyAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(modifyAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
request.insert("vaultAddress".into(), vaultAddress);
}
return Value::Map(request);
Value::Null
}
pub async fn edit_order(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
let mut amount = get_arg(optional_args, 0, Value::Null);
let mut price = get_arg(optional_args, 1, Value::Null);
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (id == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" editOrder() requires an id argument".into()))));
}
let orderglobalParamsVariable: Vec<Value> = self.parse_create_edit_order_args(id, symbol, type_var, side, amount, &[price, params]).as_array().cloned().unwrap_or_default();
let mut order: Value = orderglobalParamsVariable.get(0).cloned().unwrap_or(Value::Null);
let mut globalParams: Value = orderglobalParamsVariable.get(1).cloned().unwrap_or(Value::Null);
let mut orders: Value = self.edit_orders(Value::from(vec![order]), &[globalParams]).await;
let mut edited: Value = self.safe_dict(orders, Value::Int(0), &[]);
return edited;
Value::Null
}
pub async fn edit_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.initialize_client().await;
let mut request: Value = self.edit_orders_request(orders, &[params]);
let mut response: Value = self.private_post_exchange(&[request]).await;
let mut responseObject: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut dataObject: Value = self.safe_dict_k(responseObject, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Value = self.safe_list_k(dataObject, "statuses", &[Value::from(vec![])]);
return self.parse_orders(statuses, &[]);
Value::Null
}
pub async fn create_vault(&mut self, mut name: Value, mut description: Value, mut initialUsd: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut usd: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.number_to_string(initialUsd), &Value::Str("1000000".into())));
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createVault".into()));
m.insert("name".to_string(), name);
m.insert("description".to_string(), description);
m.insert("initialUsd".to_string(), usd);
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce, &[]);
request.insert("action".into(), Value::Map(action));
request.insert("signature".into(), signature);
let __ws_arg_21 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_21]).await;
return response;
Value::Null
}
pub async fn fetch_funding_rate_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchFundingRateHistory() requires a symbol argument".into()))));
}
let mut market: Value = self.market(symbol.clone());
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("fundingHistory".into()));
m.insert("coin".to_string(), self.safe_string_k(market.clone(), "baseName", &[]));
m
});
if (since != Value::Null) {
request.insert("startTime".into(), since.clone());
} else {
let mut maxLimit: Value = (if (limit == Value::Null) { Value::Int(500) } else { limit.clone() });
request.insert("startTime".into(), (match (&(self.milliseconds()), &((match (&((match (&((match (&(maxLimit), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x),
Value::Float(y)) => Value::Float(x * y), _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
_ => Value::Null })), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }))) { (Value::Int(x),
Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null }));
}
let mut until: Value = self.safe_integer_k(params.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::Str("until".into()), &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
}
let __ws_arg_22 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_22]).await;
let mut result: Vec<Value> = Vec::new();
let mut fundings: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
fundings = response.clone();
}
{
let mut i: i64 = 0;
let mut __for_first_822: bool = true;
while { if !__for_first_822 { i += 1; } __for_first_822 = false; i < (fundings.len() as i64) } {
let mut entry: Value = self.safe_dict(fundings.clone(), Value::Int(i), &[]);
let mut timestamp: Option<i64> = self.safe_integer_k(entry.clone(), "time", &[]).as_i64();
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), entry.clone());
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("fundingRate".to_string(), self.safe_number_k(entry, "fundingRate", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m
}));
}
}
let mut sorted: Value = self.sort_by(Value::from(result), Value::Str("timestamp".into()), &[]);
return self.filter_by_symbol_since_limit(sorted, &[symbol, since, limit]);
Value::Null
}
pub fn get_dex_from_hip3_symbol(&self, mut market: Value) -> Option<String> {
let __market_empty = indexmap::IndexMap::new();
let market = market.as_map().unwrap_or(&__market_empty);
let mut baseName: Value = (match market.get("baseName") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Str("".into()) });
let mut part: Value = Value::Array(if let Some(__s) = baseName.as_str() { __s.split(":").map(Value::from).collect() } else { Vec::new() });
let mut partsLength: f64 = ((part.len() as i64) as f64);
if partsLength > ((1i64) as f64) {
return self.safe_string(part, Value::Int(0), &[]).as_str().map(str::to_owned);
}
return None;
}
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchOpenOrders".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchOpenOrders".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let methodparamsMethodVariable: Vec<Value> = self.handle_option_string_and_params(paramsPublicAddress, Value::Str("fetchOpenOrders".into()), Value::Str("method".into()), &[Value::Str("frontendOpenOrders".into())]).as_array().cloned().unwrap_or_default();
let mut method: Value = methodparamsMethodVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsMethod: Value = methodparamsMethodVariable.get(1).cloned().unwrap_or(Value::Null);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), method);
m.insert("user".to_string(), userAddress.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone()).map(Value::from).unwrap_or(Value::Null);
if (dexName != Value::Null) {
request.insert("dex".into(), dexName);
}
}
let __ws_arg_23 = self.extend(Value::Map(request), &[paramsMethod]);
let mut response: Value = self.public_post_info(&[__ws_arg_23]).await;
let mut orderWithStatus: Vec<Value> = Vec::new();
let mut rawOrders: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
rawOrders = response.clone();
}
{
let mut i: i64 = 0;
let mut __for_first_823: bool = true;
while { if !__for_first_823 { i += 1; } __for_first_823 = false; i < (rawOrders.len() as i64) } {
let mut order: Value = self.safe_dict(rawOrders.clone(), Value::Int(i), &[]);
let mut extendOrder: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (self.safe_string_k(order.clone(), "status", &[]) == Value::Null) {
extendOrder.insert("ccxtStatus".into(), Value::Str("open".into()));
}
orderWithStatus.push(self.extend(order, &[Value::Map(extendOrder)]));
}
}
return self.parse_orders(Value::from(orderWithStatus), &[market, since, limit]);
Value::Null
}
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("closed".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
pub async fn fetch_canceled_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("canceled".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
pub async fn fetch_canceled_and_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut orders: Value = self.fetch_orders(&[symbol.clone(), Value::Null, Value::Null, params]).await; let mut closedOrders: Value = self.filter_by_array(orders, Value::Str("status".into()), &[Value::from(vec![Value::Str("canceled".into()), Value::Str("closed".into()), Value::Str("rejected".into())]), Value::Bool(false)]);
return self.filter_by_symbol_since_limit(closedOrders, &[symbol, since, limit]);
Value::Null
}
pub async fn fetch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchOrders".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchOrders".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("historicalOrders".into()));
m.insert("user".to_string(), userAddress.clone().map(Value::from).unwrap_or(Value::Null));
m
});
if (symbol != Value::Null) {
market = self.market(symbol);
let mut dexName: Value = self.get_dex_from_hip3_symbol(market.clone()).map(Value::from).unwrap_or(Value::Null);
if (dexName != Value::Null) {
request.insert("dex".into(), dexName);
}
}
let __ws_arg_24 = self.extend(Value::Map(request), &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_24]).await;
let mut deduplicatedByOid: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut historicalOrders: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
historicalOrders = response.clone();
}
{
let mut i: i64 = 0;
let mut __for_first_824: bool = true;
while { if !__for_first_824 { i += 1; } __for_first_824 = false; i < (historicalOrders.len() as i64) } {
let mut rawOrder: Value = historicalOrders.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut entry: Value = self.safe_dict_k(rawOrder.clone(), "order", &[rawOrder.clone()]);
let mut oid: Option<String> = self.safe_string_k_opt(entry, "oid", &[]);
if (oid.is_some()) {
if !(matches!((&deduplicatedByOid, &oid.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut deduplicatedByOid { std::sync::Arc::make_mut(__d).insert(oid.as_deref().unwrap_or("null").to_string(), rawOrder.clone()); }
} else {
let mut existingTimestamp: Value = self.safe_integer((if let (Some(__m), Some(__k)) = (deduplicatedByOid.as_map(), oid.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null }), Value::Str("statusTimestamp".into()), &[]);
let mut currentTimestamp: Value = self.safe_integer_k(rawOrder.clone(), "statusTimestamp", &[]);
if (currentTimestamp != Value::Null) && ((existingTimestamp == Value::Null) || currentTimestamp.as_f64().unwrap_or(f64::NAN) > existingTimestamp.as_f64().unwrap_or(f64::NAN)) {
if let Value::Dict(__d) = &mut deduplicatedByOid { std::sync::Arc::make_mut(__d).insert(oid.as_deref().unwrap_or("null").to_string(), rawOrder); }
}
}
}
}
}
let mut deduplicated: Value = Value::Array(deduplicatedByOid.as_map().map(|__m| __m.values().cloned().collect()).unwrap_or_default());
return self.parse_orders(deduplicated, &[market, since, limit]);
Value::Null
}
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
userAddress = self.safe_string(self.handle_public_address(Value::Str("fetchOrder".into()), params.clone()), Value::Int(0), &[]);
params2 = self.safe_dict(self.handle_public_address(Value::Str("fetchOrder".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut clientOrderId: Option<String> = self.safe_string_k_opt(params2.clone(), "clientOrderId", &[]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("orderStatus".into()));
m.insert("user".to_string(), userAddress);
m
});
if (clientOrderId.is_some()) {
params2 = self.omit(params2.clone(), Value::Str("clientOrderId".into()), &[]);
request.insert("oid".into(), clientOrderId.map(Value::from).unwrap_or(Value::Null));
} else {
let mut isClientOrderId: bool = ((id.len() as i64) as f64) >= ((34i64) as f64);
request.insert("oid".into(), (if isClientOrderId { id.clone() } else { self.parse_to_numeric(id) }));
}
let __ws_arg_25 = self.extend(Value::Map(request), &[params2]);
let mut response: Value = self.public_post_info(&[__ws_arg_25]).await;
let mut data: Value = self.safe_dict_k(response, "order", &[]);
return self.parse_order(data, &[market]);
Value::Null
}
pub fn parse_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut error: Option<String> = self.safe_string_k(order.clone(), "error", &[]).as_str().map(str::to_owned);
if (error.is_some()) {
let mut finalOrder: Value = order.clone(); return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), finalOrder);
m.insert("status".to_string(), Value::Str("rejected".into()));
m
}), &[]);
}
let mut entry: Value = self.safe_dict_n(order.clone(), Value::from(vec![Value::Str("order".into()), Value::Str("resting".into()), Value::Str("filled".into())]), &[order.clone()]);
let mut filled: Value = self.safe_dict_k(order.clone(), "filled", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Option<String> = self.safe_string_k_opt(entry.clone(), "coin", &[]);
let mut marketId: Value = Value::Null;
if (coin.is_some()) {
marketId = self.coin_to_market_id(coin.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
}
let mut marketResolved: Value = Value::Null;
if (self.safe_string_k(entry.clone(), "id", &[]) == Value::Null) {
marketResolved = self.safe_market(&[marketId.clone()]);
} else {
marketResolved = self.safe_market(&[marketId, market]);
}
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(entry.clone(), "timestamp", &[]).as_i64();
let mut status: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("status".into()), Value::Str("ccxtStatus".into()), &[]);
let mut orderOmitted: Value = self.omit(order, Value::from(vec![Value::Str("ccxtStatus".into())]), &[]);
let mut side: Value = self.safe_string_k(entry.clone(), "side", &[]);
if (side != Value::Null) {
side = (if (side.as_str() == Some("A")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut totalAmount: Option<String> = self.safe_string2_opt(entry.clone(), Value::Str("origSz".into()), Value::Str("totalSz".into()), &[]);
let mut remaining: Option<String> = self.safe_string_k_opt(entry.clone(), "sz", &[]);
let mut tif: Option<String> = self.safe_string_upper_k_opt(entry.clone(), "tif", &[]);
let mut postOnly: Value = Value::Null;
if (tif.is_some()) {
postOnly = (Value::Bool(tif.as_deref() == Some("ALO")));
}
let mut isTrigger: bool = self.safe_bool_k_opt(entry.clone(), "isTrigger", &[Value::Bool(false)]).unwrap_or(false);
let mut triggerPx: Value = (if isTrigger { self.safe_number_k(entry.clone(), "triggerPx", &[]) } else { Value::Null });
let mut orderTypeRaw: Value = self.safe_string_lower_k(entry.clone(), "orderType", &[Value::Str("".into())]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if (triggerPx != Value::Null) {
if orderTypeRaw.as_str().unwrap_or("").contains("stop") {
stopLossPrice = triggerPx.clone();
} else if orderTypeRaw.as_str().unwrap_or("").contains("take profit") {
takeProfitPrice = triggerPx.clone();
}
}
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), orderOmitted.clone());
m.insert("id".to_string(), self.safe_string_k(entry.clone(), "oid", &[]));
m.insert("clientOrderId".to_string(), self.safe_string_k(entry.clone(), "cloid", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_integer_k(orderOmitted, "statusTimestamp", &[]));
m.insert("symbol".to_string(), symbol);
m.insert("type".to_string(), self.parse_order_type(self.safe_string_lower_k(entry.clone(), "orderType", &[])).map(Value::from).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), tif.map(Value::from).unwrap_or(Value::Null));
m.insert("postOnly".to_string(), postOnly);
m.insert("reduceOnly".to_string(), self.safe_bool_k(entry.clone(), "reduceOnly", &[]));
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_string_k(entry.clone(), "limitPx", &[]));
m.insert("triggerPrice".to_string(), triggerPx);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), totalAmount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("cost".to_string(), Value::Null);
m.insert("average".to_string(), self.safe_string_k(entry, "avgPx", &[]));
m.insert("filled".to_string(), self.safe_string_k(filled, "totalSz", &[crate::precise::Precise::stringSub(&totalAmount.clone().map(Value::from).unwrap_or(Value::Null), &remaining.clone().map(Value::from).unwrap_or(Value::Null))]));
m.insert("remaining".to_string(), remaining.map(Value::from).unwrap_or(Value::Null));
m.insert("status".to_string(), self.parse_order_status(status.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null));
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::Null);
m
}), &[marketResolved]);
Value::Null
}
pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
if (status == Value::Null) {
return None;
}
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("triggered".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("rejected".to_string(), Value::Str("rejected".into()));
m.insert("marginCanceled".to_string(), Value::Str("canceled".into()));
m
});
if (status.as_str().unwrap_or("").ends_with("Rejected")) {
return Value::Str("rejected".into()).as_str().map(str::to_owned);
}
if (status.as_str().unwrap_or("").ends_with("Canceled")) {
return Value::Str("canceled".into()).as_str().map(str::to_owned);
}
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("stop limit".to_string(), Value::Str("limit".into()));
m.insert("stop market".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchMyTrades".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchMyTrades".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.map(Value::from).unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
request.insert("type".into(), Value::Str("userFillsByTime".into()));
request.insert("startTime".into(), since.clone());
} else {
request.insert("type".into(), Value::Str("userFills".into()));
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
}
let __ws_arg_26 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_26]).await;
let mut myFills: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
myFills = response.clone();
}
return self.parse_trades(myFills, &[market, since, limit]);
Value::Null
}
pub fn parse_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(trade.clone(), "time", &[]).as_i64();
let mut price: Option<String> = self.safe_string_k_opt(trade.clone(), "px", &[]);
let mut amount: Option<String> = self.safe_string_k_opt(trade.clone(), "sz", &[]);
let mut coin: Option<String> = self.safe_string_k_opt(trade.clone(), "coin", &[]);
let mut marketId: Value = self.coin_to_market_id(coin.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(trade.clone(), "tid", &[]);
let mut side: Value = self.safe_string_k(trade.clone(), "side", &[]);
if (side != Value::Null) {
side = (if (side.as_str() == Some("A")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut fee: Value = self.safe_string_k(trade.clone(), "fee", &[]);
let mut takerOrMaker: Value = Value::Null;
let mut crossed: Option<bool> = self.safe_bool_k_opt(trade.clone(), "crossed", &[]);
if (crossed.is_some()) {
takerOrMaker = (if crossed == Some(true) { Value::Str("taker".into()) } else { Value::Str("maker".into()) });
}
let mut builderFee: Option<String> = self.safe_string_k_opt(trade.clone(), "builderFee", &[]);
if (builderFee.is_some()) {
fee = crate::precise::Precise::stringAdd(&fee, &builderFee.clone().map(Value::from).unwrap_or(Value::Null));
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("symbol".to_string(), symbol);
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("order".to_string(), self.safe_string_k(trade.clone(), "oid", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), price.map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), amount.map(Value::from).unwrap_or(Value::Null));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), fee);
m.insert("currency".to_string(), self.safe_string_k(trade, "feeToken", &[]));
m.insert("rate".to_string(), Value::Null);
m
}));
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_my_liquidations(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchMyLiquidations".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchMyLiquidations".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.clone().map(Value::from).unwrap_or(Value::Null));
m
});
if (since != Value::Null) {
request.insert("type".into(), Value::Str("userFillsByTime".into()));
request.insert("startTime".into(), since.clone());
} else {
request.insert("type".into(), Value::Str("userFills".into()));
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
}
let __ws_arg_27 = self.extend(Value::Map(request.clone()), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_27]).await;
let mut fills: Vec<Value> = Vec::new();
if (matches!(&response, Value::Arr(_))) {
let mut user: Option<String> = self.safe_string_lower_k_opt(Value::Map(request), "user", &[]);
{
let mut i: i64 = 0;
let mut __for_first_825: bool = true;
while { if !__for_first_825 { i += 1; } __for_first_825 = false; i < (response.len() as i64) } {
let mut fill: Value = self.safe_dict(response.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut liquidation: Value = self.safe_dict_k(fill.clone(), "liquidation", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_string_lower_k(liquidation, "liquidatedUser", &[]).as_str() == user.as_deref()) {
fills.push(fill);
}
}
}
}
return self.parse_liquidations(Value::from(fills), &[market, since, limit]);
Value::Null
}
pub fn parse_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(liquidation.clone(), "time", &[]).as_i64();
let mut marketId: Value = self.coin_to_market_id(self.safe_string_k(liquidation.clone(), "coin", &[])).map(Value::from).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
if (symbol != Value::Null) && (self.markets.clone() != Value::Null) && (matches!((&self.markets, &symbol), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
marketResolved = self.market(symbol.clone());
}
let mut side: Value = self.safe_string_k(liquidation.clone(), "side", &[]);
if (side != Value::Null) {
side = (if (side.as_str() == Some("A")) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut amount: Option<String> = self.safe_string_k_opt(liquidation.clone(), "sz", &[]);
let mut price: Option<String> = self.safe_string_k_opt(liquidation.clone(), "px", &[]);
return self.safe_liquidation(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), liquidation);
m.insert("symbol".to_string(), symbol);
m.insert("contracts".to_string(), amount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("price".to_string(), price.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("baseValue".to_string(), amount.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("quoteValue".to_string(), crate::precise::Precise::stringMul(&amount.clone().map(Value::from).unwrap_or(Value::Null), &price.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("side".to_string(), side);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_position(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut positions: Value = self.fetch_positions(&[Value::from(vec![symbol]), params]).await;
return self.safe_dict(positions, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
Value::Null
}
pub fn get_dex_from_symbols(&self, mut methodName: Value, optional_args: &[Value]) -> Option<String> {
let mut symbols = get_arg(optional_args, 0, Value::Null);
if (symbols == Value::Null) {
return None;
}
let mut symbolsLength: f64 = ((symbols.len() as i64) as f64);
if (symbolsLength == 0.0) {
return None;
}
let mut firstMarket: Value = self.market(symbols.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null));
let mut dexName: Value = self.get_dex_from_hip3_symbol(firstMarket).map(Value::from).unwrap_or(Value::Null);
{
let mut i: Value = Value::Int(1);
let mut __for_first_826: bool = true;
while { if !__for_first_826 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_826 = false; i.as_f64().unwrap_or(f64::NAN) < symbolsLength } {
let mut market: Value = self.market(symbols.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
let mut currentDexName: Value = self.get_dex_from_hip3_symbol(market).map(Value::from).unwrap_or(Value::Null);
if (currentDexName != dexName) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str(" only supports symbols from one DEX at a time for HIP3 markets".into()))));
}
}
}
return dexName.as_str().map(str::to_owned);
}
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchPositions".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchPositions".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("clearinghouseState".into()));
m.insert("user".to_string(), userAddress.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let mut dexName: Value = self.get_dex_from_symbols(Value::Str("fetchPositions".into()), &[symbolsNormalized.clone()]).map(Value::from).unwrap_or(Value::Null);
if (dexName != Value::Null) {
request.insert("dex".into(), dexName);
}
let __ws_arg_28 = self.extend(Value::Map(request), &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_28]).await;
let mut data: Vec<Value> = self.safe_list_k(response, "assetPositions", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_827: bool = true;
while { if !__for_first_827 { i += 1; } __for_first_827 = false; i < (data.len() as i64) } {
result.push(self.parse_position(data.get(i as usize).cloned().unwrap_or(Value::Null), &[]));
}
}
return self.filter_by_array_positions(Value::from(result), Value::Str("symbol".into()), &[symbolsNormalized]);
Value::Null
}
pub fn parse_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut entry: Value = self.safe_dict_k(position.clone(), "position", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut coin: Option<String> = self.safe_string_k_opt(entry.clone(), "coin", &[]);
let mut marketId: Value = self.coin_to_market_id(coin.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut marketResolved: Value = self.safe_market(&[marketId]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut leverage: Value = self.safe_dict_k(entry.clone(), "leverage", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marginMode: Option<String> = self.safe_string_k_opt(leverage.clone(), "type", &[]);
let mut isIsolated: Value = (Value::Bool(marginMode.as_deref() == Some("isolated")));
let mut rawSize: Option<String> = self.safe_string_k_opt(entry.clone(), "szi", &[]);
let mut size: Value = rawSize.clone().map(Value::from).unwrap_or(Value::Null);
let mut side: Value = Value::Null;
if (size != Value::Null) {
side = (if crate::precise::Precise::stringGt(&rawSize.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("0".into())).as_bool() == Some(true) { Value::Str("long".into()) } else { Value::Str("short".into()) });
size = crate::precise::Precise::stringAbs(&size);
}
let mut rawUnrealizedPnl: Option<String> = self.safe_string_k_opt(entry.clone(), "unrealizedPnl", &[]);
let mut absRawUnrealizedPnl: Value = crate::precise::Precise::stringAbs(&rawUnrealizedPnl.clone().map(Value::from).unwrap_or(Value::Null));
let mut marginUsed: Option<String> = self.safe_string_k_opt(entry.clone(), "marginUsed", &[]);
let mut initialMargin: Value = Value::Null;
if matches!(&isIsolated, Value::Bool(true)) {
initialMargin = crate::precise::Precise::stringSub(&marginUsed.clone().map(Value::from).unwrap_or(Value::Null), &rawUnrealizedPnl.clone().map(Value::from).unwrap_or(Value::Null));
} else {
initialMargin = marginUsed.clone().map(Value::from).unwrap_or(Value::Null);
}
let mut percentage: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringDiv(&absRawUnrealizedPnl, &marginUsed.clone().map(Value::from).unwrap_or(Value::Null)), &Value::Str("100".into()));
let mut positionValueString: Option<String> = self.safe_string_k_opt(entry.clone(), "positionValue", &[]);
let mut markPriceString: Value = crate::precise::Precise::stringDiv(&positionValueString.clone().map(Value::from).unwrap_or(Value::Null), &size);
let mut marginString: Value = Value::Null;
if matches!(&isIsolated, Value::Bool(true)) {
marginString = initialMargin.clone();
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position);
m.insert("id".to_string(), Value::Null);
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("isolated".to_string(), isIsolated);
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.parse_number(size, &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(entry.clone(), "entryPx", &[]));
m.insert("markPrice".to_string(), self.parse_number(markPriceString, &[]));
m.insert("notional".to_string(), self.parse_number(positionValueString.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("leverage".to_string(), self.safe_number_k(leverage, "value", &[]));
m.insert("positionMargin".to_string(), self.parse_number(marginString, &[]));
m.insert("collateral".to_string(), self.parse_number(marginUsed.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("initialMargin".to_string(), self.parse_number(initialMargin, &[]));
m.insert("maintenanceMargin".to_string(), Value::Null);
m.insert("initialMarginPercentage".to_string(), Value::Null);
m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
m.insert("unrealizedPnl".to_string(), self.parse_number(rawUnrealizedPnl.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(entry, "liquidationPx", &[]));
m.insert("marginMode".to_string(), marginMode.map(Value::from).unwrap_or(Value::Null));
m.insert("marginRatio".to_string(), Value::Null);
m.insert("percentage".to_string(), self.parse_number(percentage, &[]));
m
}));
Value::Null
}
pub async fn set_margin_mode(&mut self, mut marginMode: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut leverage: Option<i64> = self.safe_integer_k(params.clone(), "leverage", &[]).as_i64();
if (leverage.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires a leverage parameter".into()))));
}
let mut asset: Value = self.parse_to_int(market.get("baseId").cloned().unwrap_or(Value::Null));
let mut isCross: Value = (Value::Bool(marginMode.as_str() == Some("cross")));
let mut nonce: Value = self.incrementing_nonce();
let mut params2: Value = self.omit(params, Value::from(vec![Value::Str("leverage".into())]), &[]);
let mut updateAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".into()));
m.insert("asset".to_string(), asset);
m.insert("isCross".to_string(), isCross);
m.insert("leverage".to_string(), Value::from(leverage));
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params2(params2.clone(), Value::Str("setMarginMode".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
if (vaultAddress != Value::Null) {
if (vaultAddress.as_str().unwrap_or("").starts_with("0x")) {
vaultAddress = vaultAddress.as_str().map(|__s| Value::Str(__s.replace("0x", "").into())).unwrap_or_else(|| vaultAddress.clone());
}
}
let mut signature: Value = self.sign_l1_action(Value::Map(updateAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(updateAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
request.insert("vaultAddress".into(), vaultAddress);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
return response;
Value::Null
}
pub async fn set_leverage(&mut self, mut leverage: Value, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut marginMode: Option<String> = self.safe_string_k(params.clone(), "marginMode", &[Value::Str("cross".into())]).as_str().map(str::to_owned);
let mut isCross: Value = (Value::Bool(marginMode.as_deref() == Some("cross")));
let mut asset: Value = self.parse_to_int(market.get("baseId").cloned().unwrap_or(Value::Null));
let mut nonce: Value = self.incrementing_nonce();
let mut params2: Value = self.omit(params, Value::Str("marginMode".into()), &[]);
let mut updateAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateLeverage".into()));
m.insert("asset".to_string(), asset);
m.insert("isCross".to_string(), isCross);
m.insert("leverage".to_string(), leverage);
m
});
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params2(params2.clone(), Value::Str("setLeverage".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(updateAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(updateAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
params2 = self.omit(params2, Value::Str("vaultAddress".into()), &[]);
request.insert("vaultAddress".into(), vaultAddress);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
return response;
Value::Null
}
pub async fn add_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("add".into()), &[params]).await;
Value::Null
}
pub async fn reduce_margin(&mut self, mut symbol: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.modify_margin_helper(symbol, amount, Value::Str("reduce".into()), &[params]).await;
Value::Null
}
pub async fn modify_margin_helper(&mut self, mut symbol: Value, mut amount: Value, mut type_var: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = self.market(symbol.clone());
let mut asset: Value = self.parse_to_int(market.as_map().and_then(|__m| __m.get("baseId")).cloned().unwrap_or(Value::Null));
let mut szAbs: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.amount_to_precision(symbol, amount), &Value::Str("1000000".into())));
let mut sz: Value = (if (type_var.as_str() == Some("reduce")) { (match &(szAbs) { Value::Int(x) => Value::Int(-x), Value::Float(x) => Value::Float(-x), _ => Value::Null }) } else { szAbs });
let mut nonce: Value = self.incrementing_nonce();
let mut updateAction: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("updateIsolatedMargin".into()));
m.insert("asset".to_string(), asset);
m.insert("isBuy".to_string(), Value::Bool(true));
m.insert("ntli".to_string(), sz);
m
});
let mut vaultAddressOption: Value = self.handle_option_string_and_params2(params, Value::Str("modifyMargin".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_l1_action(Value::Map(updateAction.clone()), nonce.clone(), &[vaultAddress.clone()]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(updateAction));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), signature);
m
});
if (vaultAddress != Value::Null) {
request.insert("vaultAddress".into(), vaultAddress);
}
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
let __ws_arg_29 = self.parse_margin_modification(response.clone(), &[market]);
let __ws_arg_30 = self.safe_string_k(response, "status", &[]);
return self.extend(__ws_arg_29, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("code".to_string(), __ws_arg_30);
m
})]);
Value::Null
}
pub fn parse_margin_modification(&self, mut data: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), self.safe_symbol(Value::Null, &[market.clone()]));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Str("isolated".into()));
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), self.safe_string_k(market, "settle", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m
});
Value::Null
}
pub async fn transfer(&mut self, mut code: Value, mut amount: Value, mut fromAccount: Value, mut toAccount: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut isSandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut nonce: Value = self.incrementing_nonce();
if self.in_array(fromAccount.clone(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("perp".into())])).as_bool() == Some(true) {
if !(self.in_array(toAccount.clone(), Value::from(vec![Value::Str("spot".into()), Value::Str("swap".into()), Value::Str("perp".into())])).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" transfer() only support spot <> swap transfer".into()))));
}
let mut strAmount: Value = self.number_to_string(amount.clone());
let mut vaultAddressRaw: Option<String> = self.safe_string2_opt(params.clone(), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]);
if (vaultAddressRaw.is_some()) {
strAmount = Value::Str(format!("{}{}", Value::Str(format!("{}{}", strAmount, Value::Str(" subaccount:".into())).into()), self.format_vault_address(&[vaultAddressRaw.map(Value::from).unwrap_or(Value::Null)]).map(Value::from).unwrap_or(Value::Null)).into());
}
let mut strAmountFinal: Value = strAmount; let mut toPerp: Value = Value::Bool((toAccount.as_str() == Some("perp")) || (toAccount.as_str() == Some("swap")));
let mut transferPayload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("amount".to_string(), strAmountFinal.clone());
m.insert("toPerp".to_string(), toPerp.clone());
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut transferSig: Value = self.build_usd_class_send_sig(Value::Map(transferPayload.clone()));
let mut transferRequest: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), transferPayload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("type".to_string(), Value::Str("usdClassTransfer".into()));
m.insert("amount".to_string(), strAmountFinal);
m.insert("toPerp".to_string(), toPerp);
m.insert("nonce".to_string(), nonce.clone());
m
}));
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), transferSig);
m
});
let mut transferResponse: Value = self.private_post_exchange(&[Value::Map(transferRequest)]).await;
let mut currency: Value = self.safe_currency(code.clone(), &[]);
return self.parse_transfer(transferResponse, &[currency.clone()]);
}
let mut isDeposit: Value = Value::Bool(false);
let mut subAccountAddress: Value = Value::Null;
if (fromAccount.as_str() == Some("main")) {
subAccountAddress = toAccount.clone();
isDeposit = Value::Bool(true);
} else if (toAccount.as_str() == Some("main")) {
subAccountAddress = fromAccount;
} else {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" transfer() only support main <> subaccount transfer".into()))));
}
self.check_address(&[subAccountAddress.clone()]);
let mut transferType: Option<String> = self.safe_string_k(params.clone(), "type", &[]).as_str().map(str::to_owned);
let mut transferMethod: Value = Value::Null;
let mut query: Value = params;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params(query.clone(), Value::Str("transfer".into()), Value::Str("method".into()), &[]).as_array().cloned().unwrap_or_default(); transferMethod = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); query = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
let mut masterAddress: Value = Value::Null;
masterAddress = self.safe_string(self.handle_public_address(Value::Str("transfer".into()), query.clone()), Value::Int(0), &[]);
query = self.safe_dict(self.handle_public_address(Value::Str("transfer".into()), query.clone()), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut useSendAsset: bool = transferMethod.as_str() == Some("sendAsset");
if (transferMethod == Value::Null) {
let mut isUnified: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.is_unified_enabled(Value::Str("transfer".into()), &[masterAddress.clone(), Value::Bool(false), query.clone()]).await.as_array().cloned().unwrap_or_default(); isUnified = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); query = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
useSendAsset = isUnified.as_bool() == Some(true);
}
if useSendAsset {
let mut paramsSendAsset: Value = query;
let mut sendAssetCurrency: Value = self.currency(code.clone());
let mut sendAssetCurrencyInfo: Value = self.safe_dict_k(sendAssetCurrency.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut sendAssetToken: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.safe_string_k(sendAssetCurrencyInfo.clone(), "name", &[Value::Str("".into())]), Value::Str(":".into())).into()), self.safe_string_k(sendAssetCurrencyInfo, "tokenId", &[Value::Str("".into())])).into());
let mut defaultDex: Value = (if ((transferType.as_deref() == Some("swap")) || (transferType.as_deref() == Some("perp"))) { Value::Str("".into()) } else { Value::Str("spot".into()) });
let mut sourceDex: Value = self.safe_string_k(paramsSendAsset.clone(), "sourceDex", &[defaultDex.clone()]);
let mut destinationDex: Value = self.safe_string_k(paramsSendAsset, "destinationDex", &[defaultDex]);
let mut sendAssetPayload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("destination".to_string(), (if (isDeposit).as_bool() == Some(true) { subAccountAddress.clone() } else { masterAddress }));
m.insert("sourceDex".to_string(), sourceDex.clone());
m.insert("destinationDex".to_string(), destinationDex.clone());
m.insert("token".to_string(), sendAssetToken.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m.insert("fromSubAccount".to_string(), (if (isDeposit).as_bool() == Some(true) { Value::Str("".into()) } else { subAccountAddress.clone() }));
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut sendAssetSig: Value = self.build_send_asset_sig(Value::Map(sendAssetPayload.clone()));
let mut sendAssetRequest: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), sendAssetPayload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("type".to_string(), Value::Str("sendAsset".into()));
m.insert("destination".to_string(), sendAssetPayload.get("destination").cloned().unwrap_or(Value::Null));
m.insert("sourceDex".to_string(), sourceDex);
m.insert("destinationDex".to_string(), destinationDex);
m.insert("token".to_string(), sendAssetToken);
m.insert("amount".to_string(), sendAssetPayload.get("amount").cloned().unwrap_or(Value::Null));
m.insert("fromSubAccount".to_string(), sendAssetPayload.get("fromSubAccount").cloned().unwrap_or(Value::Null));
m.insert("nonce".to_string(), nonce.clone());
m
}));
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), sendAssetSig);
m
});
let mut sendAssetResponse: Value = self.private_post_exchange(&[Value::Map(sendAssetRequest)]).await;
return self.parse_transfer(sendAssetResponse, &[sendAssetCurrency]);
}
let mut isUsdc: bool = (if let Some(__s) = code.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null }).as_str() == Some("USDC");
if isUsdc && (transferType.as_deref() != Some("spot")) {
let mut usd: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.number_to_string(amount.clone()), &Value::Str("1000000".into())));
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountTransfer".into()));
m.insert("subAccountUser".to_string(), subAccountAddress.clone());
m.insert("isDeposit".to_string(), isDeposit.clone());
m.insert("usd".to_string(), usd);
m
});
let mut sig: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action.clone());
m.insert("nonce".to_string(), nonce.clone());
m.insert("signature".to_string(), sig.clone());
m
});
let mut response: Value = self.private_post_exchange(&[request.clone()]).await;
return self.parse_transfer(response.clone(), &[self.safe_currency(code.clone(), &[])]);
} else {
if (code == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" transfer() requires a currency code for spot sub-account transfers".into()))));
}
let mut currency: Value = self.currency(code);
let mut currencyInfo: Value = self.safe_dict_k(currency.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut action: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("subAccountSpotTransfer".into()));
m.insert("subAccountUser".to_string(), subAccountAddress);
m.insert("isDeposit".to_string(), isDeposit);
m.insert("token".to_string(), Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.safe_string_k(currencyInfo.clone(), "name", &[Value::Str("".into())]), Value::Str(":".into())).into()), self.safe_string_k(currencyInfo, "tokenId", &[Value::Str("".into())])).into()));
m.insert("amount".to_string(), self.number_to_string(amount));
m
});
let mut sig: Value = self.sign_l1_action(action.clone(), nonce.clone(), &[]);
let mut request: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), action);
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m
});
let mut response: Value = self.private_post_exchange(&[request]).await;
return self.parse_transfer(response, &[currency]);
}
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transfer.clone());
m.insert("id".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("currency".to_string(), self.safe_currency_code(Value::Null, &[currency]));
m.insert("amount".to_string(), Value::Null);
m.insert("fromAccount".to_string(), Value::Null);
m.insert("toAccount".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transfer, "status", &[Value::Str("ok".into())]));
m
});
Value::Null
}
pub async fn withdraw(&mut self, mut code: Value, mut amount: Value, mut address: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.check_required_credentials(&[]);
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
self.check_address(&[address.clone()]);
if ((if let Some(__s) = code.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null }).as_str() != Some("USDC")) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" withdraw() only support USDC".into()))));
}
let mut vaultAddressOption: Value = self.handle_option_string_and_params(params, Value::Str("withdraw".into()), Value::Str("vaultAddress".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut nonce: Value = self.incrementing_nonce();
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut sig: Value = Value::Null;
if (vaultAddress != Value::Null) {
action = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("vaultTransfer".into()));
m.insert("vaultAddress".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into()));
m.insert("isDeposit".to_string(), Value::Bool(false));
m.insert("usd".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&self.number_to_string(amount.clone()), &Value::Str("1000000".into()))));
m
});
sig = self.sign_l1_action(Value::Map(action.clone()), nonce.clone(), &[]);
} else {
let mut isSandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut payload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), (if isSandboxMode { Value::Str("Testnet".into()) } else { Value::Str("Mainnet".into()) }));
m.insert("destination".to_string(), address.clone());
m.insert("amount".to_string(), self.number_to_string(amount.clone()));
m.insert("time".to_string(), nonce.clone());
m
});
sig = self.build_withdraw_sig(Value::Map(payload.clone()));
action = ({
let mut m = indexmap::IndexMap::new();
m.insert("hyperliquidChain".to_string(), payload.get("hyperliquidChain").cloned().unwrap_or(Value::Null));
m.insert("signatureChainId".to_string(), Value::Str("0x66eee".into()));
m.insert("destination".to_string(), address);
m.insert("amount".to_string(), self.number_to_string(amount));
m.insert("time".to_string(), nonce.clone());
m.insert("type".to_string(), Value::Str("withdraw3".into()));
m
});
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("action".to_string(), Value::Map(action));
m.insert("nonce".to_string(), nonce);
m.insert("signature".to_string(), sig);
m
});
let mut response: Value = self.private_post_exchange(&[Value::Map(request)]).await;
return self.parse_transaction(response, &[]);
Value::Null
}
pub fn parse_transaction(&self, mut transaction: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(transaction.clone(), "time", &[]).as_i64();
let mut delta: Value = self.safe_dict_k(transaction.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fee: Value = Value::Null;
let mut feeCost: Option<i64> = self.safe_integer_k(delta.clone(), "fee", &[]).as_i64();
if (feeCost.is_some()) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("cost".to_string(), Value::from(feeCost));
m
});
}
let mut internal: Value = Value::Null;
let mut type_var: Option<String> = self.safe_string_k(delta.clone(), "type", &[]).as_str().map(str::to_owned);
if (type_var.is_some()) {
internal = (Value::Bool(type_var.as_deref() == Some("internalTransfer")));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), Value::Null);
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "hash", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("network".to_string(), Value::Null);
m.insert("address".to_string(), Value::Null);
m.insert("addressTo".to_string(), self.safe_string_k(delta.clone(), "destination", &[]));
m.insert("addressFrom".to_string(), self.safe_string_k(delta.clone(), "user", &[]));
m.insert("tag".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("type".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_number_k(delta, "usdc", &[]));
m.insert("currency".to_string(), Value::Null);
m.insert("status".to_string(), self.safe_string_k(transaction, "status", &[]));
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("internal".to_string(), internal);
m.insert("fee".to_string(), fee);
m
});
Value::Null
}
pub async fn fetch_trading_fee(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchTradingFee".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchTradingFee".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userFees".into()));
m.insert("user".to_string(), userAddress.map(Value::from).unwrap_or(Value::Null));
m
});
let __ws_arg_31 = self.extend(Value::Map(request), &[paramsPublicAddress]);
let mut response: Value = self.public_post_info(&[__ws_arg_31]).await;
let mut data: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("userCrossRate".to_string(), self.safe_string_k(response.clone(), "userCrossRate", &[]));
m.insert("userAddRate".to_string(), self.safe_string_k(response, "userAddRate", &[]));
m
});
return self.parse_trading_fee(Value::Map(data), &[market]);
Value::Null
}
pub fn parse_trading_fee(&self, mut fee: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut symbol: Value = self.safe_symbol(Value::Null, &[market]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), fee.clone());
m.insert("symbol".to_string(), symbol);
m.insert("maker".to_string(), self.safe_number_k(fee.clone(), "userAddRate", &[]));
m.insert("taker".to_string(), self.safe_number_k(fee, "userCrossRate", &[]));
m.insert("percentage".to_string(), Value::Null);
m.insert("tierBased".to_string(), Value::Null);
m
});
Value::Null
}
pub async fn fetch_ledger(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
userAddress = self.safe_string(self.handle_public_address(Value::Str("fetchLedger".into()), params.clone()), Value::Int(0), &[]);
params2 = self.safe_dict(self.handle_public_address(Value::Str("fetchLedger".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
request.insert("startTime".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_32 = self.extend(Value::Map(request), &[params2]);
let mut response: Value = self.public_post_info(&[__ws_arg_32]).await;
return self.parse_ledger(response, &[Value::Null, since, limit]);
Value::Null
}
pub fn parse_ledger_entry(&self, mut item: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut timestamp: Option<i64> = self.safe_integer_k(item.clone(), "time", &[]).as_i64();
let mut delta: Value = self.safe_dict_k(item.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut fee: Value = Value::Null;
let mut feeCost: Option<i64> = self.safe_integer_k(delta.clone(), "fee", &[]).as_i64();
if (feeCost.is_some()) {
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), Value::Str("USDC".into()));
m.insert("cost".to_string(), Value::from(feeCost));
m
});
}
let mut type_var: Option<String> = self.safe_string_k_opt(delta.clone(), "type", &[]);
let mut amount: Option<String> = self.safe_string_k_opt(delta.clone(), "usdc", &[]);
return self.safe_ledger_entry(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), item.clone());
m.insert("id".to_string(), self.safe_string_k(item.clone(), "hash", &[]));
m.insert("direction".to_string(), Value::Null);
m.insert("account".to_string(), Value::Null);
m.insert("referenceAccount".to_string(), self.safe_string_k(delta, "user", &[]));
m.insert("referenceId".to_string(), self.safe_string_k(item, "hash", &[]));
m.insert("type".to_string(), self.parse_ledger_entry_type(type_var.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null));
m.insert("currency".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_number(amount.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("before".to_string(), Value::Null);
m.insert("after".to_string(), Value::Null);
m.insert("status".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m
}), &[currency]);
Value::Null
}
pub fn parse_ledger_entry_type(&self, mut type_var: Value) -> Option<String> {
let mut ledgerType: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("internalTransfer".to_string(), Value::Str("transfer".into()));
m.insert("accountClassTransfer".to_string(), Value::Str("transfer".into()));
m
});
return self.safe_string(Value::Map(ledgerType), type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub async fn fetch_deposits(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
userAddress = self.safe_string(self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params.clone()), Value::Int(0), &[]);
params2 = self.safe_dict(self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
request.insert("startTime".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
if (since == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposits requires since while until is set".into()))));
}
request.insert("endTime".into(), until);
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_33 = self.extend(Value::Map(request), &[params2.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_33]).await;
let mut depositLedger: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
depositLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[depositLedger]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params(params2.clone(), Value::Str("fetchDepositsWithdrawals".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
if (vaultAddress == Value::Null) {
let mut filtered: Value = self.filter_by_array(records.clone(), Value::Str("type".into()), &[Value::from(vec![Value::Str("deposit".into())]), Value::Bool(false)]);
return self.parse_transactions(filtered, &[Value::Null, since.clone(), limit.clone()]);
}
let mut deposits: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_828: bool = true;
while { if !__for_first_828 { i += 1; } __for_first_828 = false; i < (records.len() as i64) } {
let mut record: Value = records.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(record.clone(), "type", &[]).as_str() == Some("vaultDeposit")) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_string_k(delta, "vault", &[Value::Str("".into())]).as_str() == Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into()).as_str()) {
deposits.push(record);
}
}
}
}
return self.parse_transactions(Value::from(deposits), &[Value::Null, since, limit]);
Value::Null
}
pub async fn fetch_withdrawals(&mut self, optional_args: &[Value]) -> Value {
let mut code = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut userAddress: Value = Value::Null;
let mut params2: Value = Value::Null;
userAddress = self.safe_string(self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params.clone()), Value::Int(0), &[]);
params2 = self.safe_dict(self.handle_public_address(Value::Str("fetchDepositsWithdrawals".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("userNonFundingLedgerUpdates".into()));
m.insert("user".to_string(), userAddress);
m
});
if (since != Value::Null) {
request.insert("startTime".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(params2.clone(), "until", &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
params2 = self.omit(params2.clone(), Value::from(vec![Value::Str("until".into())]), &[]);
}
let __ws_arg_34 = self.extend(Value::Map(request), &[params2.clone()]);
let mut response: Value = self.public_post_info(&[__ws_arg_34]).await;
let mut withdrawalLedger: Value = Value::from(vec![]);
if (matches!(&response, Value::Arr(_))) {
withdrawalLedger = response.clone();
}
let mut records: Value = self.extract_type_from_delta(&[withdrawalLedger]);
let mut vaultAddress: Value = Value::Null;
{ let __destr_tmp: Vec<Value> = self.handle_option_string_and_params(params2.clone(), Value::Str("fetchDepositsWithdrawals".into()), Value::Str("vaultAddress".into()), &[]).as_array().cloned().unwrap_or_default(); vaultAddress = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); params2 = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
vaultAddress = self.format_vault_address(&[vaultAddress.clone()]).map(Value::from).unwrap_or(Value::Null);
if (vaultAddress == Value::Null) {
let mut filtered: Value = self.filter_by_array(records.clone(), Value::Str("type".into()), &[Value::from(vec![Value::Str("withdraw".into())]), Value::Bool(false)]);
return self.parse_transactions(filtered, &[Value::Null, since.clone(), limit.clone()]);
}
let mut withdrawals: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_829: bool = true;
while { if !__for_first_829 { i += 1; } __for_first_829 = false; i < (records.len() as i64) } {
let mut record: Value = records.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
if (self.safe_string_k(record.clone(), "type", &[]).as_str() == Some("vaultWithdraw")) {
let mut delta: Value = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_string_k(delta, "vault", &[Value::Str("".into())]).as_str() == Value::Str(format!("{}{}", Value::Str("0x".into()), vaultAddress).into()).as_str()) {
withdrawals.push(record);
}
}
}
}
return self.parse_transactions(Value::from(withdrawals), &[Value::Null, since, limit]);
Value::Null
}
pub async fn fetch_open_interests(&mut self, optional_args: &[Value]) -> Value {
let mut symbols = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut symbolsNormalized: Value = self.market_symbols(&[symbols]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut dexName: Value = self.get_dex_from_symbols(Value::Str("fetchOpenInterests".into()), &[symbolsNormalized.clone()]).map(Value::from).unwrap_or(Value::Null);
if (dexName != Value::Null) {
request.insert("dex".into(), dexName);
}
let __ws_arg_35 = self.extend(Value::Map(request), &[params]);
let mut swapMarkets: Value = self.fetch_swap_markets(&[__ws_arg_35]).await;
return self.parse_open_interests(swapMarkets, &[symbolsNormalized]);
Value::Null
}
pub async fn fetch_open_interest(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut symbolValue: Value = self.symbol(symbol.clone());
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut ois: Value = self.fetch_open_interests(&[Value::from(vec![symbolValue.clone()]), params]).await;
let mut openInterest: Value = self.safe_dict(ois, symbolValue, &[]);
return openInterest;
Value::Null
}
pub fn parse_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let __interest_empty = indexmap::IndexMap::new();
let interest = interest.as_map().unwrap_or(&__interest_empty);
let mut interestValue: Value = (match interest.get("info") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut coin: Option<String> = self.safe_string_k_opt(interestValue.clone(), "name", &[]);
let mut marketId: Value = Value::Null;
if (coin.is_some()) {
marketId = self.coin_to_market_id(coin.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
}
return self.safe_open_interest(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), self.safe_symbol(marketId, &[]));
m.insert("openInterestAmount".to_string(), self.safe_number_k(interestValue.clone(), "openInterest", &[]));
m.insert("openInterestValue".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("info".to_string(), interestValue);
m
}), &[market]);
Value::Null
}
pub async fn fetch_funding_history(&mut self, optional_args: &[Value]) -> Value {
let mut symbol = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
}
let mut userAddress: Option<String> = self.safe_string_opt(self.handle_public_address(Value::Str("fetchFundingHistory".into()), params.clone()), Value::Int(0), &[]);
let mut paramsPublicAddress: Value = self.safe_dict(self.handle_public_address(Value::Str("fetchFundingHistory".into()), params), Value::Int(1), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("user".to_string(), userAddress.map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), Value::Str("userFunding".into()));
m
});
if (since != Value::Null) {
request.insert("startTime".into(), since.clone());
}
let mut until: Value = self.safe_integer_k(paramsPublicAddress.clone(), "until", &[]);
let mut paramsOmitted: Value = self.omit(paramsPublicAddress, Value::Str("until".into()), &[]);
if (until != Value::Null) {
request.insert("endTime".into(), until);
}
let __ws_arg_36 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_post_info(&[__ws_arg_36]).await;
return self.parse_incomes(response, &[market, since, limit]);
Value::Null
}
pub fn parse_income(&self, mut income: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(income.clone(), "hash", &[]);
let mut timestamp: Option<i64> = self.safe_integer_k(income.clone(), "time", &[]).as_i64();
let mut delta: Value = self.safe_dict_k(income.clone(), "delta", &[]);
let mut coin: Option<String> = self.safe_string_k_opt(delta.clone(), "coin", &[]);
let mut marketId: Value = Value::Null;
if (coin.is_some()) {
marketId = self.coin_to_market_id(coin.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
}
let mut marketResolved: Value = self.safe_market(&[marketId, market]);
let mut amount: Option<String> = self.safe_string_k_opt(delta.clone(), "usdc", &[]);
let mut code: Value = self.safe_string_k(marketResolved.clone(), "settle", &[Value::Str("USDC".into())]);
let mut rate: Value = self.safe_number_k(delta, "fundingRate", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), income);
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("code".to_string(), code);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("amount".to_string(), self.parse_number(amount.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("rate".to_string(), rate);
m
});
Value::Null
}
pub async fn reserve_request_weight(&mut self, mut weight: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("reserveRequestWeight".into()));
m.insert("weight".to_string(), weight);
m
});
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce, &[]);
request.insert("action".into(), Value::Map(action));
request.insert("signature".into(), signature);
let __ws_arg_37 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_37]).await;
return response;
Value::Null
}
pub async fn create_sub_account(&mut self, mut name: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut nonce: Value = self.incrementing_nonce();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce.clone());
m
});
let mut action: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("type".to_string(), Value::Str("createSubAccount".into()));
m.insert("name".to_string(), name);
m
});
let mut expiresAfter: Value = self.safe_integer_k(params.clone(), "expiresAfter", &[]);
if (expiresAfter != Value::Null) {
request.insert("expiresAfter".into(), expiresAfter.clone());
}
let mut signature: Value = self.sign_l1_action(Value::Map(action.clone()), nonce, &[Value::Null, expiresAfter]);
request.insert("action".into(), Value::Map(action));
request.insert("signature".into(), signature);
let __ws_arg_38 = self.extend(Value::Map(request), &[self.omit(params, Value::Str("expiresAfter".into()), &[])]);
let mut response: Value = self.private_post_exchange(&[__ws_arg_38]).await;
return response;
Value::Null
}
pub fn extract_type_from_delta(&self, optional_args: &[Value]) -> Value {
let mut data = get_arg(optional_args, 0, Value::from(vec![]));
let mut records: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_830: bool = true;
while { if !__for_first_830 { i += 1; } __for_first_830 = false; i < (data.len() as i64) } {
let mut record: Value = self.safe_dict(data.clone(), Value::Int(i), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut delta: indexmap::IndexMap<String, Value> = self.safe_dict_k(record.clone(), "delta", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
if let Value::Dict(__d) = &mut record { std::sync::Arc::make_mut(__d).insert("type".into(), delta.get("type").cloned().unwrap_or(Value::Null)); }
records.push(record);
}
}
return Value::from(records);
Value::Null
}
pub fn format_vault_address(&self, optional_args: &[Value]) -> Option<String> {
let mut address = get_arg(optional_args, 0, Value::Null);
if (address == Value::Null) {
return None;
}
if (address.as_str().unwrap_or("").starts_with("0x")) {
return address.as_str().map(|__s| Value::Str(__s.replace("0x", "").into())).unwrap_or_else(|| address.clone()).as_str().map(str::to_owned);
}
return address.as_str().map(str::to_owned);
}
pub fn handle_public_address(&self, mut methodName: Value, mut params: Value) -> Value {
let userAuxparamsUserVariable: Vec<Value> = self.handle_option_string_and_params2(params, methodName.clone(), Value::Str("user".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default();
let mut userAux: Value = userAuxparamsUserVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsUser: Value = userAuxparamsUserVariable.get(1).cloned().unwrap_or(Value::Null);
let userparamsAddressVariable: Vec<Value> = self.handle_option_string_and_params(paramsUser, methodName.clone(), Value::Str("address".into()), &[userAux]).as_array().cloned().unwrap_or_default();
let mut user: Value = userparamsAddressVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAddress: Value = userparamsAddressVariable.get(1).cloned().unwrap_or(Value::Null);
if (user != Value::Null) && (user.as_str() != Some("")) {
return Value::from(vec![user, paramsAddress.clone()]);
}
if (self.walletAddress.clone() != Value::Null) && (self.walletAddress.as_str() != Some("")) {
return Value::from(vec![self.walletAddress.clone(), paramsAddress]);
}
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName).into()), Value::Str("() requires a user parameter inside 'params' or the wallet address set".into()))));
Value::Null
}
pub fn coin_to_market_id(&self, mut coin: Value) -> Option<String> {
if (coin == Value::Null) {
return None;
}
let mut hi3TokensByname: Value = self.safe_dict_k(self.options.clone(), "hip3TokensByName", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut hip3Dict: Value = self.safe_dict(hi3TokensByname, coin.clone(), &[]);
if (hip3Dict != Value::Null) {
let quote: String = self.safe_string_k_opt(hip3Dict.clone(), "quote", &[Value::Str("USDC".into())]).unwrap_or_default();
let mut code: Value = self.safe_string_k(hip3Dict, "code", &[coin.clone()]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", code, Value::Str("/".into())).into()), quote).into()), Value::Str(":".into())).into()), quote).into()).as_str().map(str::to_owned);
}
if coin.as_str().unwrap_or("").contains("/") || coin.as_str().unwrap_or("").contains("@") {
return coin.as_str().map(str::to_owned);
}
let mut coinId: Value = coin.clone();
if coin.as_str().unwrap_or("").contains(":") {
coinId = coin.as_str().map(|__s| Value::Str(__s.replace(":", "-").into())).unwrap_or_else(|| coin.clone());
}
return Value::Str(format!("{}{}", self.safe_currency_code(coinId, &[]), Value::Str("/USDC:USDC".into())).into()).as_str().map(str::to_owned);
}
pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
if (response == Value::Null) || (response == Value::Null) {
return Value::Null;
}
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[Value::Str("".into())]).as_str().map(str::to_owned);
let mut error: Option<String> = self.safe_string_k_opt(response.clone(), "error", &[]);
let mut message: Value = Value::Null;
if (status.as_deref() == Some("err")) {
message = self.safe_string_k(response.clone(), "response", &[]);
} else if (status.as_deref() == Some("unknownOid")) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body)));
} else if (error.is_some()) {
message = error.clone().map(Value::from).unwrap_or(Value::Null);
} else {
let mut responsePayload: Value = self.safe_dict_k(response, "response", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut data: Value = self.safe_dict_k(responsePayload, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut statuses: Vec<Value> = self.safe_list_k(data.clone(), "statuses", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut i: i64 = 0;
let mut __for_first_831: bool = true;
while { if !__for_first_831 { i += 1; } __for_first_831 = false; i < (statuses.len() as i64) } {
message = self.safe_string_k(statuses.get(i as usize).cloned().unwrap_or(Value::Null), "error", &[]);
if (message != Value::Null) {
break;
}
}
}
if (matches!(&data, Value::Dict(__d) if __d.contains_key("status"))) {
let mut errorStatus: Value = self.safe_dict_k(data, "status", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut errorMsg: Option<String> = self.safe_string_k_opt(errorStatus.clone(), "error", &[]);
if (errorStatus != Value::Null) {
message = errorMsg.map(Value::from).unwrap_or(Value::Null);
}
}
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
let mut nonEmptyMessage: bool = (message != Value::Null) && (message.as_str() != Some(""));
if nonEmptyMessage {
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), message.clone(), feedback.clone());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message, feedback.clone());
}
if nonEmptyMessage {
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("public".into())]));
let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
let mut params = get_arg(optional_args, 2, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __api_empty = Vec::new();
let api = api.as_array().unwrap_or(&__api_empty);
let mut apiName: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut apiUrl: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName, &[]);
if (apiUrl.is_none()) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.implode_hostname(apiUrl.map(Value::from).unwrap_or(Value::Null)), Value::Str("/".into())).into()), path).into());
let mut isPost: bool = method.as_str() == Some("POST");
let mut postHeaders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
m
});
let mut requestHeaders: Value = Value::Null;
if isPost {
requestHeaders = postHeaders;
}
let mut requestBody: Value = Value::Null;
if isPost {
requestBody = json_stringify(¶ms);
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url);
m.insert("method".to_string(), method);
m.insert("body".to_string(), requestBody);
m.insert("headers".to_string(), requestHeaders);
m
});
Value::Null
}
pub fn calculate_rate_limiter_cost(&self, mut api: Value, mut method: Value, mut path: Value, mut params: Value, optional_args: &[Value]) -> Value {
let mut config = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let __config_empty = indexmap::IndexMap::new();
let config = config.as_map().unwrap_or(&__config_empty);
if (config.contains_key("byType")) && (in_op(¶ms, &Value::Str("type".into()))) {
let mut type_var: Value = crate::value::get_value_k(¶ms, "type");
let mut byType: Value = (match config.get("byType") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
if (matches!((&byType, &type_var), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
return (if let (Some(__m), Some(__k)) = (byType.as_map(), type_var.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
}
}
return (match config.get("cost") { Some(Value::Float(__f)) => Value::Float(*__f), Some(Value::Int(__n)) => Value::Float(*__n as f64), Some(Value::Str(__s)) => match __s.parse::<f64>() { Ok(__n) => Value::Float(__n), Err(_) => Value::Int(1) }, _ => Value::Int(1) });
Value::Null
}
pub fn parse_create_edit_order_args(&self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
let mut price = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut market: Value = self.market(symbol);
let vaultAddressOptionparams2Variable: Vec<Value> = self.handle_option_string_and_params2(params, Value::Str("createOrder".into()), Value::Str("vaultAddress".into()), Value::Str("subAccountAddress".into()), &[]).as_array().cloned().unwrap_or_default();
let mut vaultAddressOption: Value = vaultAddressOptionparams2Variable.get(0).cloned().unwrap_or(Value::Null);
let mut params2: Value = vaultAddressOptionparams2Variable.get(1).cloned().unwrap_or(Value::Null);
let mut vaultAddress: Value = self.format_vault_address(&[vaultAddressOption]).map(Value::from).unwrap_or(Value::Null);
let mut symbolValue: Value = self.safe_string_k(market, "symbol", &[Value::Str("".into())]);
let mut order: indexmap::IndexMap<String, Value> = {
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbolValue);
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("amount".to_string(), amount);
m.insert("price".to_string(), price);
m.insert("params".to_string(), params2);
m
};
let mut globalParams: indexmap::IndexMap<String, Value> = {
let mut m = indexmap::IndexMap::new();
m
};
if (vaultAddress != Value::Null) {
globalParams.insert("vaultAddress".into(), vaultAddress);
}
if (id != Value::Null) {
order.insert("id".into(), id);
}
return Value::from(vec![Value::Map(order), Value::Map(globalParams)]);
Value::Null
}
}