#![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 LighterCore {
pub exchange: crate::exchange::Exchange,
}
impl LighterCore {
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 = LighterCore::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 LighterCore {
fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_ticker(self, ticker, &[market])
}
fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_trade(self, trade, &[market])
}
fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_order(self, order, &[market])
}
fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_ohlcv(self, ohlcv, &[market])
}
fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_position(self, position, &[market])
}
fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_funding_rate(self, rate, &[market])
}
fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
LighterCore::parse_transfer(self, transfer, &[currency])
}
fn parse_currency(&self, currency: crate::Value) -> crate::Value {
LighterCore::parse_currency(self, currency)
}
fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
LighterCore::parse_margin_modification(self, data, &[market])
}
fn parse_account(&self, account: crate::Value) -> crate::Value {
LighterCore::parse_account(self, account)
}
fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
LighterCore::parse_transaction(self, transaction, &[currency])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
LighterCore::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 {
LighterCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for LighterCore {
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 {
"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,
"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), 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())..]).await,
"cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
"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,
"change_api_key" => self.change_api_key(&args[..]).await,
"check_if_standard_tier" => self.check_if_standard_tier(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
"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_sub_account" => self.create_sub_account(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.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,
"fetch_accounts" => self.fetch_accounts(&args[..]).await,
"fetch_balance" => self.fetch_balance(&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_rates" => self.fetch_funding_rates(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_nonce" => self.fetch_nonce(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_status" => self.fetch_status(&args[..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_transfers" => self.fetch_transfers(&args[..]).await,
"fetch_withdrawals" => self.fetch_withdrawals(&args[..]).await,
"get_lighter_private_key" => self.get_lighter_private_key(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"handle_account_index" => self.handle_account_index(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,
"handle_api_key_index" => self.handle_api_key_index(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())..]),
"handle_builder_fee_approval" => self.handle_builder_fee_approval(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).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)),
"load_account" => self.load_account(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,
"modify_leverage_and_margin_mode" => self.modify_leverage_and_margin_mode(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"parse_account" => self.parse_account(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"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_margin_modification" => self.parse_margin_modification(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_ohlcv" => self.parse_ohlcv(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_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())..]),
"pre_load_lighter_library" => self.pre_load_lighter_library(&args[..]).await,
"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,
"set_leverage" => self.set_leverage(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"set_margin" => self.set_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,
"set_margin_mode" => self.set_margin_mode(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_and_cancel_all_orders" => self.sign_and_cancel_all_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"sign_and_cancel_order" => self.sign_and_cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
"sign_and_create_order" => self.sign_and_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.get(4).cloned().unwrap_or(crate::Value::Null), &args[5.min(args.len())..]).await,
"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,
"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 LighterCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { &self.exchange }
}
impl std::ops::DerefMut for LighterCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { &mut self.exchange }
}
impl LighterCore {
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("lighter".into()));
m.insert("name".to_string(), Value::Str("Lighter".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(1000));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("dex".to_string(), Value::Bool(true));
m.insert("quoteJsonNumbers".to_string(), Value::Bool(false));
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("borrowMargin".to_string(), Value::Bool(false));
m.insert("cancelAllOrders".to_string(), Value::Bool(true));
m.insert("cancelAllOrdersAfter".to_string(), Value::Bool(true));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(false));
m.insert("cancelOrdersForSymbols".to_string(), Value::Bool(false));
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(false));
m.insert("createPostOnlyOrder".to_string(), Value::Bool(false));
m.insert("createReduceOnlyOrder".to_string(), Value::Bool(false));
m.insert("createStopOrder".to_string(), Value::Bool(false));
m.insert("createTriggerOrder".to_string(), Value::Bool(false));
m.insert("editOrder".to_string(), Value::Bool(true));
m.insert("fetchAccounts".to_string(), Value::Bool(true));
m.insert("fetchAllGreeks".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(true));
m.insert("fetchBorrowInterest".to_string(), Value::Bool(false));
m.insert("fetchBorrowRate".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistories".to_string(), Value::Bool(false));
m.insert("fetchBorrowRateHistory".to_string(), Value::Bool(false));
m.insert("fetchBorrowRates".to_string(), Value::Bool(false));
m.insert("fetchBorrowRatesPerSymbol".to_string(), Value::Bool(false));
m.insert("fetchCanceledAndClosedOrders".to_string(), Value::Bool(false));
m.insert("fetchCanceledOrders".to_string(), Value::Bool(false));
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::Bool(false));
m.insert("fetchDepositWithdrawFees".to_string(), Value::Bool(false));
m.insert("fetchFundingHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRate".to_string(), Value::Bool(false));
m.insert("fetchFundingRateHistory".to_string(), Value::Bool(false));
m.insert("fetchFundingRates".to_string(), Value::Bool(true));
m.insert("fetchGreeks".to_string(), Value::Bool(false));
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(false));
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::Bool(false));
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(false));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(true));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenInterestHistory".to_string(), Value::Bool(false));
m.insert("fetchOpenInterests".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOption".to_string(), Value::Bool(false));
m.insert("fetchOptionChain".to_string(), Value::Bool(false));
m.insert("fetchOrder".to_string(), Value::Bool(false));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(false));
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::Bool(true));
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(false));
m.insert("fetchTradingFees".to_string(), Value::Bool(false));
m.insert("fetchTransfer".to_string(), Value::Bool(false));
m.insert("fetchTransfers".to_string(), Value::Bool(true));
m.insert("fetchVolatilityHistory".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("setMargin".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("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("4h".to_string(), Value::Str("4h".into()));
m.insert("12h".to_string(), Value::Str("12h".into()));
m.insert("1d".to_string(), Value::Str("1d".into()));
m
}));
m.insert("hostname".to_string(), Value::Str("zklighter.elliot.ai".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/5aa1158d-0734-49fc-9155-501d94b76a0b".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m.insert("public".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://mainnet.{hostname}".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Str("https://testnet.{hostname}".into()));
m.insert("public".to_string(), Value::Str("https://testnet.{hostname}".into()));
m.insert("private".to_string(), Value::Str("https://testnet.{hostname}".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://lighter.xyz/".into()));
m.insert("doc".to_string(), Value::Str("https://apidocs.lighter.xyz/".into()));
m.insert("fees".to_string(), Value::Str("https://docs.lighter.xyz/perpetual-futures/fees".into()));
m.insert("referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), Value::Str("https://app.lighter.xyz/?referral=715955W9".into()));
m.insert("discount".to_string(), Value::Float(0.1));
m
}));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("root".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("public".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountsByL1Address".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("apikeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("exchangeStats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("assetDetails".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBookDetails".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBookOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("orderBooks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("recentTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("blockTxs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("nextNonce".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tx".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("txFromL1TxHash".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("txs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("announcement".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("block".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("blocks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("currentHeight".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("candles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("markPriceCandles".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fundings".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("fastbridge/info".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("funding-rates".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdrawalDelay".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("partnerStats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("syntheticSpotInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("tokenlist".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("sendTx".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("sendTxBatch".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m.insert("private".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("accountLimits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountMetadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("pnl".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("l1Metadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("liquidations".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("positionFunding".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("publicPoolsMetadata".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("getMakerOnlyApiKeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountActiveOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountInactiveOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountOrders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("export".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("export/historicalTrades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("trades".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("accountTxs".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("deposit/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transfer/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("withdraw/history".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("referral/points".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("transferFeeInfo".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/get".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/list".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m.insert("post".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("changeAccountTier".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("setMakerOnlyApiKeys".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("notification/ack".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/respond".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("rfq/update".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("httpExceptions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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.insert("20001".to_string(), Value::Str("BadRequest".into()));
m.insert("21146".to_string(), Value::Str("ExchangeError".into()));
m.insert("21500".to_string(), Value::Str("ExchangeError".into()));
m.insert("21501".to_string(), Value::Str("ExchangeError".into()));
m.insert("21502".to_string(), Value::Str("ExchangeError".into()));
m.insert("21503".to_string(), Value::Str("ExchangeError".into()));
m.insert("21504".to_string(), Value::Str("ExchangeError".into()));
m.insert("21505".to_string(), Value::Str("ExchangeError".into()));
m.insert("21506".to_string(), Value::Str("ExchangeError".into()));
m.insert("21507".to_string(), Value::Str("ExchangeError".into()));
m.insert("21508".to_string(), Value::Str("ExchangeError".into()));
m.insert("21511".to_string(), Value::Str("ExchangeError".into()));
m.insert("21512".to_string(), Value::Str("ExchangeError".into()));
m.insert("21600".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21601".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21602".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21603".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21604".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21605".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21606".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21607".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21608".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21611".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21612".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21613".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21614".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21700".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21701".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21702".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21703".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21704".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21705".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21706".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21707".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21708".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21709".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21710".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21711".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21712".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21713".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21714".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21715".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21716".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21717".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21718".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21719".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21720".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21721".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21722".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21723".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21724".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21725".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21726".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21727".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21728".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21729".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21730".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21731".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21732".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21733".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21734".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21735".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21736".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21737".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21738".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21739".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21740".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21901".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21902".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21903".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21904".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21905".to_string(), Value::Str("InvalidOrder".into()));
m.insert("21906".to_string(), Value::Str("InvalidOrder".into()));
m.insert("22400".to_string(), Value::Str("BadRequest".into()));
m.insert("23000".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("23001".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("23002".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("23003".to_string(), Value::Str("RateLimitExceeded".into()));
m.insert("29404".to_string(), Value::Str("BadRequest".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::Int(0));
m.insert("maker".to_string(), Value::Int(0));
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(false));
m.insert("privateKey".to_string(), Value::Bool(true));
m.insert("password".to_string(), Value::Bool(false));
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("builderFee".to_string(), Value::Bool(true));
m.insert("chainId".to_string(), Value::Int(304));
m.insert("accountIndex".to_string(), Value::Null);
m.insert("apiKeyIndex".to_string(), Value::Null);
m.insert("lighterPrivateKey".to_string(), Value::Null);
m.insert("wasmExecPath".to_string(), Value::Null);
m.insert("libraryPath".to_string(), Value::Null);
m.insert("integratorAccountIndex".to_string(), Value::Int(718718));
m.insert("integratorMakerFee".to_string(), Value::Int(1000));
m.insert("integratorTakerFee".to_string(), Value::Int(1000));
m.insert("authDeadlineExpiry".to_string(), Value::Int(28800));
m.insert("authDeadlineMinimumRemaining".to_string(), Value::Int(60));
m.insert("tiersForAccountIndexes".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
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("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(true));
m.insert("PO".to_string(), Value::Bool(true));
m.insert("GTD".to_string(), Value::Bool(false));
m
}));
m.insert("leverage".to_string(), Value::Bool(false));
m.insert("marketBuyRequiresPrice".to_string(), Value::Bool(false));
m.insert("marketBuyByCost".to_string(), Value::Bool(false));
m.insert("selfTradePrevention".to_string(), Value::Bool(false));
m.insert("trailing".to_string(), Value::Bool(false));
m.insert("iceberg".to_string(), Value::Bool(false));
m
}));
m
}));
m
}));
m
})]);
Value::Null
}
pub async fn load_account(&mut self, mut chainId: Value, mut privateKey: Value, mut apiKeyIndex: Value, mut accountIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.init_auth_object(accountIndex.clone(), apiKeyIndex.clone());
let mut cachedAuths: Value = self.safe_dict(self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), accountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), apiKeyIndex.clone(), &[]);
let mut signer: Value = self.safe_value_k(cachedAuths, "signer", &[]);
if (signer != Value::Null) {
return signer;
}
let mut libraryPath: Value = self.handle_option_string_and_params(params, Value::Str("loadAccount".into()), Value::Str("libraryPath".into()), &[]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut lighterPrivateKeyIsSet: bool = (privateKey != Value::Null) && (privateKey.as_str() != Some(""));
if lighterPrivateKeyIsSet && (libraryPath != Value::Null) && (apiKeyIndex != Value::Null) && (accountIndex != Value::Null) {
signer = self.load_lighter_library(libraryPath.clone(), chainId.clone(), privateKey.clone(), self.parse_to_int(apiKeyIndex.clone()), self.parse_to_int(accountIndex.clone()), &[Value::Bool(true)]).await;
self.set_auth_entry(accountIndex.clone(), apiKeyIndex.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("signer".to_string(), signer.clone());
m
}));
return signer;
}
let mut privateKeyIsSet: bool = (self.privateKey.clone() != Value::Null) && (self.privateKey.as_str() != Some(""));
if privateKeyIsSet && (apiKeyIndex != Value::Null) && (accountIndex != Value::Null) {
if ((self.privateKey.len() as i64) as f64) > ((66i64) as f64) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt".into()))));
}
signer = self.load_lighter_library(libraryPath, chainId, Value::Str("".into()), self.parse_to_int(apiKeyIndex.clone()), self.parse_to_int(accountIndex.clone()), &[Value::Bool(false)]).await;
self.set_auth_entry(accountIndex.clone(), apiKeyIndex.clone(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("signer".to_string(), signer.clone());
m
}));
let mut res: Value = Box::pin(self.change_api_key(&[])).await;
Box::pin(self.handle_builder_fee_approval(self.parse_to_int(accountIndex), self.parse_to_int(apiKeyIndex))).await;
return res;
}
return signer;
Value::Null
}
pub fn set_auth_entry(&self, mut accIdx: Value, mut keyIdx: Value, mut entry: Value) {
let mut updated: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_0 = self.safe_dict(self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), accIdx.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), keyIdx.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
updated.insert(crate::runtime::stringify_param(&keyIdx), self.extend(__ws_arg_0, &[entry]));
let mut auths: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_1 = self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), accIdx.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{ let __be_tmp = self.extend(__ws_arg_1, &[Value::Map(updated)]); auths.insert(crate::runtime::stringify_param(&accIdx), __be_tmp); }
let __ws_arg_2 = self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
{ let __be_tmp = self.extend(__ws_arg_2, &[Value::Map(auths)]); if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("auths".into(), __be_tmp); } }
}
pub fn init_auth_object(&self, mut strAccountIndex: Value, mut strApiKeyIndex: Value) {
if (self.safe_dict(self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strAccountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strApiKeyIndex.clone(), &[]) == Value::Null) {
self.set_auth_entry(strAccountIndex, strApiKeyIndex, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("signer".to_string(), Value::Null);
m.insert("lighterPrivateKey".to_string(), Value::Null);
m.insert("deadline".to_string(), Value::Null);
m.insert("token".to_string(), Value::Null);
m
}));
}
}
pub fn get_lighter_private_key(&self, mut strAccountIndex: Value, mut strApiKeyIndex: Value) -> Value {
let mut auths: Value = self.safe_dict_k(self.options.clone(), "auths", &[]);
let mut accountAuths: Value = self.safe_dict(auths, strAccountIndex, &[]);
let mut apiKeyAuths: Value = self.safe_dict(accountAuths, strApiKeyIndex, &[]);
return self.safe_string_k(apiKeyAuths, "lighterPrivateKey", &[]);
Value::Null
}
pub async fn pre_load_lighter_library(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("loadAccount".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut accountIndexAndParams: Value = self.handle_account_index(paramsApiKeyIndex, Value::Str("loadAccount".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accountIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
if (accountIndex == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" requires accountIndex or account_index".into()))));
}
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
self.init_auth_object(strAccountIndex.clone(), strApiKeyIndex.clone());
let mut signer: Value = self.safe_dict(self.safe_dict(self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strAccountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strApiKeyIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("signer".into()), &[]);
if (signer != Value::Null) {
return Value::Bool(true);
}
signer = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[]).await;
self.handle_builder_fee_approval(accountIndex, apiKeyIndex).await;
let mut loaded: Value = (Value::Bool(signer != Value::Null));
return loaded;
Value::Null
}
pub fn handle_api_key_index(&self, mut params: Value, mut methodName1: Value, mut optionName1: Value, mut optionName2: Value, optional_args: &[Value]) -> Value {
let mut defaultValue = get_arg(optional_args, 0, Value::Null);
let apiKeyIndexOptionparamsApiKeyIndexVariable: Vec<Value> = self.handle_option_and_params2(params, methodName1, optionName1, optionName2, &[defaultValue]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndexOption: Value = apiKeyIndexOptionparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexOptionparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut apiKeyIndex: Value = self.safe_integer(Value::from(vec![apiKeyIndexOption]), Value::Int(0), &[]);
if (apiKeyIndex != Value::Null) && (apiKeyIndex.as_f64().unwrap_or(f64::NAN) >= ((4i64) as f64)) && (apiKeyIndex.as_f64().unwrap_or(f64::NAN) <= ((254i64) as f64)) {
return Value::from(vec![self.parse_to_int(apiKeyIndex), paramsApiKeyIndex.clone()]);
}
let mut defaultApiKeyIndex: Value = Value::Int(254);
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("apiKeyIndex".into(), defaultApiKeyIndex.clone()); }; return Value::from(vec![defaultApiKeyIndex, paramsApiKeyIndex]);
Value::Null
}
pub async fn handle_account_index(&mut self, mut params: Value, mut methodName1: Value, mut optionName1: Value, mut optionName2: Value, optional_args: &[Value]) -> Value {
let mut defaultValue = get_arg(optional_args, 0, Value::Null);
let accountIndexOptionparamsAccountIndexVariable: Vec<Value> = self.handle_option_and_params2(params, methodName1.clone(), optionName1.clone(), optionName2.clone(), &[defaultValue]).as_array().cloned().unwrap_or_default();
let mut accountIndexOption: Value = accountIndexOptionparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexOptionparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut accountIndex: Value = accountIndexOption;
if (accountIndex == Value::Null) {
let mut walletAddress: Value = self.walletAddress.clone();
if (self.privateKey.clone() != Value::Null) {
if ((self.privateKey.len() as i64) as f64) > ((66i64) as f64) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" after the latest update (v4.5.50), CCXT now expects the l1 private key to be provided in the credentials. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt".into()))));
}
walletAddress = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
}
if (walletAddress == Value::Null) || (walletAddress.as_str() == Some("")) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName1).into()),
Value::Str("() requires an ".into())).into()), optionName1).into()), Value::Str("/".into())).into()), optionName2).into()), Value::Str(" parameter or walletAddress to fetch accountIndex. Alternatively set privateKey in credentials to enable automatic walletAddress detection.".into()))));
}
let mut res: Value = self.public_get_accounts_by_l1_address(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("l1_address".to_string(), walletAddress);
m
})]).await;
let mut subAccounts: Value = self.safe_list_k(res, "sub_accounts", &[]);
if (matches!(&subAccounts, Value::Arr(_))) {
let mut account: Value = self.safe_dict(subAccounts.clone(), Value::Int(0), &[]);
if (account == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), methodName1).into()),
Value::Str("() requires an ".into())).into()), optionName1).into()), Value::Str(" or ".into())).into()), optionName2).into()), Value::Str(" parameter".into()))));
}
accountIndex = account.as_map().and_then(|__m| __m.get("index")).cloned().unwrap_or(Value::Null);
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("accountIndex".into(), accountIndex.clone()); }
}
}
return Value::from(vec![self.parse_to_int(accountIndex), paramsAccountIndex]);
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 apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("createSubAccount".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("createSubAccount".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex.clone());
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let __ws_arg_3 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_create_sub_account(signer, __ws_arg_3).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
return self.public_post_send_tx(&[Value::Map(request)]).await;
Value::Null
}
pub fn create_auth(&self, optional_args: &[Value]) -> Option<String> {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut apiKeyIndex: Value = self.safe_string2(params.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
if (apiKeyIndex == Value::Null) {
let mut res: Value = self.handle_option_and_params2(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Str("createAuth".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
apiKeyIndex = self.safe_string(res.clone(), Value::Int(0), &[]);
}
let mut accountIndex: Value = self.safe_string2(params, Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]);
if (accountIndex == Value::Null) {
let mut res: Value = self.handle_option_and_params2(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), Value::Str("createAuth".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]);
accountIndex = self.safe_string(res, Value::Int(0), &[]);
}
let mut auths: Value = self.safe_dict_k(self.options.clone(), "auths", &[]);
let mut accountAuths: Value = self.safe_dict(auths, accountIndex.clone(), &[]);
let mut cachedAuth: Value = self.safe_dict(accountAuths, apiKeyIndex.clone(), &[]);
let mut cachedDeadline: Value = self.safe_integer_k(cachedAuth.clone(), "deadline", &[]);
let mut minimumRemaining: Value = self.safe_integer_k(self.options.clone(), "authDeadlineMinimumRemaining", &[Value::Int(60)]);
if (cachedDeadline != Value::Null) && (minimumRemaining != Value::Null) && ((match (&(cachedDeadline), &(minimumRemaining)) { (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 }).as_f64().unwrap_or(f64::NAN) >= self.seconds().as_f64().unwrap_or(f64::NAN)) {
return self.safe_string_k(cachedAuth.clone(), "token", &[]).as_str().map(str::to_owned);
}
let mut deadline: Value = (match (&(self.seconds()), &(self.safe_integer_k(self.options.clone(), "authDeadlineExpiry", &[Value::Int(28800)]))) { (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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("deadline".to_string(), deadline.clone());
m.insert("api_key_index".to_string(), self.parse_to_int(apiKeyIndex.clone()));
m.insert("account_index".to_string(), self.parse_to_int(accountIndex.clone()));
m
});
let mut signer: Value = self.safe_value_k(cachedAuth, "signer", &[]);
if (signer == Value::Null) {
self.check_required_credentials(&[]);
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" could not load the signer, set options[\"libraryPath\"] to the lighter signing library. Please check for more details: https://github.com/ccxt/ccxt/wiki/FAQ#how-to-use-the-lighter-exchange-in-ccxt".into()))));
}
let mut token: Value = self.lighter_create_auth_token(signer, Value::Map(request));
self.set_auth_entry(accountIndex, apiKeyIndex, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deadline".to_string(), deadline);
m.insert("token".to_string(), token.clone());
m
}));
return token.as_str().map(str::to_owned);
}
pub fn pow(&self, mut n: Value, mut m: Value) -> Option<String> {
let mut r: Value = crate::precise::Precise::stringMul(&n, &Value::Str("1".into()));
let mut c: Value = self.parse_to_int(m);
if c.as_f64().unwrap_or(f64::NAN) < ((0i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" pow() requires m > 0.".into()))));
}
if (c.as_f64() == Some(0.0)) {
return Value::Str("1".into()).as_str().map(str::to_owned);
}
if c.as_f64().unwrap_or(f64::NAN) > ((100i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" pow() requires m < 100.".into()))));
}
{
let mut i: Value = Value::Int(1);
let mut __for_first_930: bool = true;
while { if !__for_first_930 { if let Value::Int(__n) = &mut i { *__n += 1; } } __for_first_930 = false; i.as_f64().unwrap_or(f64::NAN) < c.as_f64().unwrap_or(f64::NAN) } {
r = crate::precise::Precise::stringMul(&r, &n);
}
}
return r.as_str().map(str::to_owned);
}
pub fn hash_message(&self, mut message: Value) -> Option<String> {
let mut binaryMessage: Value = self.encode(message);
let mut binaryMessageLength: Value = self.binary_length(binaryMessage.clone(), &[]);
let mut x19: Value = self.base16_to_binary(Value::Str("19".into()), &[]);
let mut newline: Value = self.base16_to_binary(Value::Str("0a".into()), &[]);
let mut prefix: Value = self.binary_concat(x19, &[self.encode(Value::Str("Ethereum Signed Message:".into())), newline, self.encode(self.number_to_string(binaryMessageLength))]);
return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(self.binary_concat(prefix, &[binaryMessage]), 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) -> Option<String> {
self.check_required_credentials(&[]);
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);
let mut r: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut s: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut v: Value = self.int_to_base16(self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]), &[]);
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), r.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null)).into()), s.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null)).into()), v).into()).as_str().map(str::to_owned);
}
pub fn sign_l1_and_prepare_tx_info(&self, mut txInfo: Value, mut message: Value, mut privateKey: Value) -> Option<String> {
let mut hashMessage: Value = self.hash_message(message).map(Value::from).unwrap_or(Value::Null);
let mut signature: Value = self.sign_hash(hashMessage, privateKey).map(Value::from).unwrap_or(Value::Null);
let __ws_arg_4 = self.parse_json_value(txInfo);
let mut decTxInfo: Value = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m
}), &[__ws_arg_4]);
add_element_to_object(&mut decTxInfo, &Value::Str("L1Sig".into()), signature);
return json_stringify(&decTxInfo).as_str().map(str::to_owned);
}
pub async fn handle_builder_fee_approval(&mut self, mut accountIndex: Value, mut apiKeyIndex: Value) -> Value {
let mut buildFee: bool = self.safe_bool_k_opt(self.options.clone(), "builderFee", &[Value::Bool(true)]).unwrap_or(true);
if !(buildFee) {
return Value::Bool(false);
}
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 mut standardTier: bool = false;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut isStandardTier: Value = self.check_if_standard_tier(self.parse_to_int(accountIndex.clone())).await;
if isStandardTier.as_bool() == Some(true) {
standardTier = true;
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
} else {
let mut builder: Value = self.safe_integer_k(self.options.clone(), "integratorAccountIndex", &[Value::Int(718718)]);
let mut takerFeeRate: Value = self.safe_integer_k(self.options.clone(), "integratorTakerFee", &[Value::Int(1000)]);
let mut makerFeeRate: Value = self.safe_integer_k(self.options.clone(), "integratorMakerFee", &[Value::Int(1000)]);
Box::pin(self.approve_builder_fee(builder, takerFeeRate, makerFeeRate, accountIndex, apiKeyIndex, &[])).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)); }
}
if standardTier {
return Value::Bool(false);
}
return Value::Bool(true);
Value::Null
}
pub async fn check_if_standard_tier(&mut self, mut accountIndex: Value) -> Value {
let mut tiersForAccountIndexes: indexmap::IndexMap<String, Value> = self.safe_dict_k(self.options.clone(), "tiersForAccountIndexes", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut accountIndexStr: Value = self.number_to_string(accountIndex.clone());
let mut isStandardTier: Option<bool> = self.safe_bool_opt(Value::Map(tiersForAccountIndexes.clone()), accountIndexStr.clone(), &[]);
if (isStandardTier.is_some()) {
let mut cachedIsStandard: Value = (Value::Bool(isStandardTier == Some(true)));
return cachedIsStandard;
}
let mut accountLimits: Value = self.private_get_account_limits(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex);
m
})]).await;
let mut tier: Option<String> = self.safe_string_k(accountLimits, "user_tier", &[]).as_str().map(str::to_owned);
let mut isStandard: Value = (Value::Bool(tier.as_deref() == Some("standard")));
tiersForAccountIndexes.insert(crate::runtime::stringify_param(&accountIndexStr), isStandard.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("tiersForAccountIndexes".into(), Value::Map(tiersForAccountIndexes)); }
return isStandard;
Value::Null
}
pub async fn approve_builder_fee(&mut self, mut builder: Value, mut takerFeeRate: Value, mut makerFeeRate: Value, mut accountIndex: Value, mut apiKeyIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = Box::pin(self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[params.clone()])).await;
let __ws_arg_5 = self.extend(params.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("skipNonce".to_string(), Value::Bool(false));
m
})]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[__ws_arg_5]).await;
let mut expiry: Value = (match (&(self.milliseconds()), &((match (&(Value::Int(365)), &(Value::Int(864000))) { (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 signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("integrator_account_index".to_string(), builder);
m.insert("integrator_taker_fee".to_string(), takerFeeRate);
m.insert("integrator_maker_fee".to_string(), makerFeeRate);
m.insert("approval_expiry".to_string(), expiry);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_6 = self.extend(Value::Map(signRaw), &[params]);
let txTypetxInfomessageToSignVariable: Vec<Value> = self.lighter_sign_approve_integrator(signer, __ws_arg_6).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfomessageToSignVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfomessageToSignVariable.get(1).cloned().unwrap_or(Value::Null);
let mut messageToSign: Value = txTypetxInfomessageToSignVariable.get(2).cloned().unwrap_or(Value::Null);
let mut newTxInfo: Value = self.sign_l1_and_prepare_tx_info(txInfo, messageToSign, self.privateKey.clone()).map(Value::from).unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), newTxInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return response;
Value::Null
}
pub async fn change_api_key(&mut self, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("changeApiKey".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("changeApiKey".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signerNotLoad: Value = self.safe_value(self.safe_dict(self.safe_dict(self.safe_dict_k(self.options.clone(), "auths", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strAccountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), strApiKeyIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]), Value::Str("signer".into()), &[]);
let privateKeypublicKeyVariable: Vec<Value> = self.lighter_generate_api_key(signerNotLoad.clone()).as_array().cloned().unwrap_or_default();
let mut privateKey: Value = privateKeypublicKeyVariable.get(0).cloned().unwrap_or(Value::Null);
let mut publicKey: Value = privateKeypublicKeyVariable.get(1).cloned().unwrap_or(Value::Null);
let __ws_arg_7 = self.extend(paramsAccountIndex.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("skipNonce".to_string(), Value::Bool(false));
m
})]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[__ws_arg_7]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("pubkey".to_string(), self.encode(publicKey));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex.clone());
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let mut signer: Value = self.lighter_create_client(signerNotLoad, self.safe_integer_k(self.options.clone(), "chainId", &[]), privateKey.clone(), apiKeyIndex.clone(), accountIndex.clone());
let __ws_arg_8 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfomessageToSignVariable: Vec<Value> = self.lighter_sign_change_pubkey(signer.clone(), __ws_arg_8).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfomessageToSignVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfomessageToSignVariable.get(1).cloned().unwrap_or(Value::Null);
let mut messageToSign: Value = txTypetxInfomessageToSignVariable.get(2).cloned().unwrap_or(Value::Null);
let mut newTxInfo: Value = self.sign_l1_and_prepare_tx_info(txInfo, messageToSign, self.privateKey.clone()).map(Value::from).unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), newTxInfo);
m
});
self.public_post_send_tx(&[Value::Map(request)]).await;
self.set_auth_entry(strAccountIndex, strApiKeyIndex, Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("lighterPrivateKey".to_string(), privateKey);
m.insert("signer".to_string(), signer.clone());
m
})); Box::pin(self.handle_builder_fee_approval(accountIndex, apiKeyIndex)).await;
return signer;
Value::Null
}
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
self.super_set_sandbox_mode(enable.clone());
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("sandboxMode".into(), enable.clone()); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("chainId".into(), (if enable.as_bool() == Some(true) { Value::Int(300) } else { Value::Int(304) })); }
}
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()))));
}
if (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price argument".into()))));
}
let mut reduceOnly: bool = self.safe_bool2_opt(params.clone(), Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), &[Value::Bool(false)]).unwrap_or(false); let mut orderType: Value = (if let Some(__s) = type_var.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
let mut market: Value = self.market(symbol.clone());
let mut orderSide: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m
});
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("createOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_option_and_params2(paramsApiKeyIndex, Value::Str("createOrder".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let nonceparamsNonceVariable: Vec<Value> = self.handle_option_and_params(paramsAccountIndex, Value::Str("createOrder".into()), Value::Str("nonce".into()), &[]).as_array().cloned().unwrap_or_default();
let mut nonce: Value = nonceparamsNonceVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsNonce: Value = nonceparamsNonceVariable.get(1).cloned().unwrap_or(Value::Null);
let orderExpiryOptionparamsOrderExpiryVariable: Vec<Value> = self.handle_option_integer_and_params(paramsNonce, Value::Str("createOrder".into()), Value::Str("orderExpiry".into()), &[Value::Int(0)]).as_array().cloned().unwrap_or_default();
let mut orderExpiryOption: Value = orderExpiryOptionparamsOrderExpiryVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsOrderExpiry: Value = orderExpiryOptionparamsOrderExpiryVariable.get(1).cloned().unwrap_or(Value::Null);
let mut orderExpiry: Value = orderExpiryOption;
if (nonce != Value::Null) {
request.insert("nonce".into(), nonce);
}
request.insert("api_key_index".into(), apiKeyIndex);
request.insert("account_index".into(), self.parse_to_int(accountIndex));
let mut triggerPrice: Option<String> = self.safe_string2_opt(paramsOrderExpiry.clone(), Value::Str("triggerPrice".into()), Value::Str("stopPrice".into()), &[]);
let mut stopLossPrice: Value = self.safe_string_k(paramsOrderExpiry.clone(), "stopLossPrice", &[triggerPrice.map(Value::from).unwrap_or(Value::Null)]);
let mut takeProfitPrice: Option<String> = self.safe_string_k_opt(paramsOrderExpiry.clone(), "takeProfitPrice", &[]);
let mut stopLoss: Value = self.safe_dict_k(paramsOrderExpiry.clone(), "stopLoss", &[]);
let mut takeProfit: Value = self.safe_dict_k(paramsOrderExpiry.clone(), "takeProfit", &[]);
let mut hasStopLoss: bool = stopLoss != Value::Null;
let mut hasTakeProfit: bool = takeProfit != Value::Null;
let mut isConditional: bool = (stopLossPrice != Value::Null) || (takeProfitPrice.is_some());
let mut isMarketOrder: Value = (Value::Bool(orderType.as_str() == Some("MARKET")));
let mut timeInForce: Option<String> = self.safe_string_lower_k(paramsOrderExpiry.clone(), "timeInForce", &[Value::Str("gtt".into())]).as_str().map(str::to_owned);
let mut postOnly: Value = self.is_post_only(isMarketOrder.clone(), Value::Null, &[paramsOrderExpiry.clone()]);
let mut paramsOmitted: Value = self.omit(paramsOrderExpiry, Value::from(vec![Value::Str("stopLoss".into()), Value::Str("takeProfit".into()), Value::Str("timeInForce".into())]), &[]);
let mut orderTypeNum: Value = Value::Null;
let mut timeInForceNum: Value = Value::Null;
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(1);
timeInForceNum = Value::Int(0);
} else {
orderTypeNum = Value::Int(0);
}
if (orderSide.as_str() == Some("BUY")) {
request.insert("is_ask".into(), Value::Int(0));
} else {
request.insert("is_ask".into(), Value::Int(1));
}
if postOnly.as_bool() == Some(true) {
timeInForceNum = Value::Int(2);
orderExpiry = Value::Int(-1);
} else {
if !(matches!(&isMarketOrder, Value::Bool(true))) {
if (timeInForce.as_deref() == Some("ioc")) {
timeInForceNum = Value::Int(0);
orderExpiry = Value::Int(0);
} else if (timeInForce.as_deref() == Some("gtt")) {
timeInForceNum = Value::Int(1);
orderExpiry = Value::Int(-1);
}
}
}
let mut marketInfo: indexmap::IndexMap<String, Value> = self.safe_dict_k(market, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut amountStr: Value = Value::Null;
let mut priceStr: Value = self.price_to_precision(symbol.clone(), price);
let mut amountScale: Value = self.pow(Value::Str("10".into()), marketInfo.get("size_decimals").cloned().unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut priceScale: Value = self.pow(Value::Str("10".into()), marketInfo.get("price_decimals").cloned().unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut triggerPriceStr: Value = Value::Str("0".into()); let mut defaultClientOrderId: Value = self.rand_number(Value::Int(9)); let mut clientOrderId: Value = self.safe_integer2(paramsOmitted.clone(), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into()), &[defaultClientOrderId]);
let mut paramsRequest: Value = self.omit(paramsOmitted, Value::from(vec![Value::Str("reduceOnly".into()), Value::Str("reduce_only".into()), Value::Str("timeInForce".into()), Value::Str("postOnly".into()), Value::Str("nonce".into()), Value::Str("apiKeyIndex".into()), Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()),
Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into()), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into())]), &[]);
if isConditional {
amountStr = self.number_to_string(amount.clone());
if (stopLossPrice != Value::Null) {
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(2);
} else {
orderTypeNum = Value::Int(3);
}
triggerPriceStr = self.price_to_precision(symbol.clone(), stopLossPrice);
} else if (takeProfitPrice.is_some()) {
if matches!(&isMarketOrder, Value::Bool(true)) {
orderTypeNum = Value::Int(4);
} else {
orderTypeNum = Value::Int(5);
}
triggerPriceStr = self.price_to_precision(symbol.clone(), takeProfitPrice.map(Value::from).unwrap_or(Value::Null));
}
} else {
amountStr = self.amount_to_precision(symbol.clone(), amount);
}
request.insert("order_expiry".into(), orderExpiry);
request.insert("order_type".into(), orderTypeNum);
request.insert("time_in_force".into(), timeInForceNum);
request.insert("reduce_only".into(), (if reduceOnly { Value::Int(1) } else { Value::Int(0) }));
request.insert("client_order_index".into(), clientOrderId);
request.insert("base_amount".into(), self.parse_to_int(crate::precise::Precise::stringMul(&amountStr, &amountScale)));
request.insert("avg_execution_price".into(), self.parse_to_int(crate::precise::Precise::stringMul(&priceStr, &priceScale)));
request.insert("trigger_price".into(), self.parse_to_int(crate::precise::Precise::stringMul(&triggerPriceStr, &priceScale)));
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
request.insert("integrator_account_index".into(), self.safe_integer_k(self.options.clone(), "integratorAccountIndex", &[]));
request.insert("integrator_taker_fee".into(), self.safe_integer_k(self.options.clone(), "integratorTakerFee", &[]));
request.insert("integrator_maker_fee".into(), self.safe_integer_k(self.options.clone(), "integratorMakerFee", &[]));
}
let mut orders: Vec<Value> = Vec::new();
let mut firstOrder: Value = self.extend(Value::Map(request), &[paramsRequest.clone()]);
orders.push(firstOrder.clone());
if hasStopLoss || hasTakeProfit {
if let Value::Dict(__d) = &mut firstOrder { std::sync::Arc::make_mut(__d).insert("client_order_index".into(), Value::Int(0)); }; let mut triggerOrderSide: String = "".to_string();
if (orderSide.as_str() == Some("BUY")) {
triggerOrderSide = "sell".to_string();
} else {
triggerOrderSide = "buy".to_string();
}
let mut stopLossOrderTriggerPrice: Option<f64> = self.safe_number2_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_number2(stopLoss.clone(), Value::Str("price".into()), Value::Str("stopLossPrice".into()), &[Value::from(stopLossOrderTriggerPrice)]);
let mut takeProfitOrderTriggerPrice: Option<f64> = self.safe_number2_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_number2(takeProfit.clone(), Value::Str("price".into()), Value::Str("takeProfitPrice".into()), &[Value::from(takeProfitOrderTriggerPrice)]);
if (stopLoss != Value::Null) {
let __ws_arg_9 = self.create_order_request(symbol.clone(), stopLossOrderType, Value::from(triggerOrderSide.clone()), Value::Int(0), &[stopLossOrderLimitPrice, self.extend(paramsRequest.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("stopLossPrice".to_string(), Value::from(stopLossOrderTriggerPrice));
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})])]);
let mut orderObj: Value = self.safe_dict(__ws_arg_9, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut orderObj { std::sync::Arc::make_mut(__d).insert("client_order_index".into(), Value::Int(0)); }
orders.push(orderObj.clone());
}
if (takeProfit != Value::Null) {
let __ws_arg_10 = self.create_order_request(symbol, takeProfitOrderType, Value::from(triggerOrderSide), Value::Int(0), &[takeProfitOrderLimitPrice, self.extend(paramsRequest, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("takeProfitPrice".to_string(), Value::from(takeProfitOrderTriggerPrice));
m.insert("reduceOnly".to_string(), Value::Bool(true));
m
})])]);
let mut orderObj: Value = self.safe_dict(__ws_arg_10, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if let Value::Dict(__d) = &mut orderObj { std::sync::Arc::make_mut(__d).insert("client_order_index".into(), Value::Int(0)); }
orders.push(orderObj);
}
}
return Value::from(orders);
Value::Null
}
pub async fn fetch_nonce(&mut self, mut accountIndex: Value, mut apiKeyIndex: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
if (accountIndex == Value::Null) || (apiKeyIndex == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchNonce() requires accountIndex and apiKeyIndex.".into()))));
}
if (matches!(¶ms, Value::Dict(__d) if __d.contains_key("nonce"))) {
return self.parse_to_int(self.safe_integer_k(params.clone(), "nonce", &[]));
}
let mut nonceInOptions: Value = self.safe_integer_k(self.options.clone(), "nonce", &[]);
if (nonceInOptions != Value::Null) {
return self.parse_to_int(nonceInOptions);
}
let mut skipNonce: Value = self.handle_option_bool_and_params(params, Value::Str("fetchNonce".into()), Value::Str("skipNonce".into()), &[Value::Bool(true)]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
if skipNonce.as_bool() == Some(true) {
return self.milliseconds();
}
let mut response: Value = self.public_get_next_nonce(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex);
m.insert("api_key_index".to_string(), apiKeyIndex);
m
})]).await;
return self.parse_to_int(self.safe_integer_k(response, "nonce", &[]));
Value::Null
}
pub async fn sign_and_create_order(&mut self, mut method: 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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let mut accIndexAndParams: Value = self.handle_account_index(params.clone(), method.clone(), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await;
let mut accountIndex: Value = accIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut apiKeyIndexAndParams: Value = self.handle_api_key_index(params.clone(), method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]);
let mut apiKeyIndex: Value = apiKeyIndexAndParams.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[params.clone()]).await;
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
let mut isStandardTier: Value = self.check_if_standard_tier(accountIndex.clone()).await;
if isStandardTier.as_bool() == Some(true) {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("builderFee".into(), Value::Bool(false)); }
}
#[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)); }
}
let groupingTypeparamsGroupingTypeVariable: Vec<Value> = self.handle_option_integer_and_params(params, method, Value::Str("groupingType".into()), &[Value::Int(3)]).as_array().cloned().unwrap_or_default();
let mut groupingType: Value = groupingTypeparamsGroupingTypeVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsGroupingType: Value = groupingTypeparamsGroupingTypeVariable.get(1).cloned().unwrap_or(Value::Null); let mut orderRequests: Value = self.create_order_request(symbol, type_var, side, amount, &[price, paramsGroupingType]);
let mut totalOrderRequests: f64 = ((orderRequests.len() as i64) as f64);
if totalOrderRequests > ((1i64) as f64) {
let mut groupOrderExpiry: Value = self.sum(&[self.milliseconds(), Value::Int(2419200000)]); {
let mut i: Value = Value::Int(0);
let mut __for_first_931: bool = true;
while { if !__for_first_931 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_931 = false; i.as_f64().unwrap_or(f64::NAN) < totalOrderRequests } {
if (self.safe_integer(orderRequests.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), Value::Str("order_expiry".into()), &[]).as_f64() == Value::Int(-1).as_f64()) {
add_element_to_object(get_value_mut(&mut orderRequests, &i), &Value::Str("order_expiry".into()), groupOrderExpiry.clone());
}
}
}
}
let mut order: Value = Value::Null;
if totalOrderRequests > ((0i64) as f64) {
order = orderRequests.as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
}
if (self.safe_integer_k(order.clone(), "nonce", &[]) == Value::Null) {
add_element_to_object(&mut order, &Value::Str("nonce".into()), self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[]).await);
}
let mut txType: Value = Value::Null;
let mut txInfo: Value = Value::Null;
if totalOrderRequests < ((2i64) as f64) {
{ let __destr_tmp: Vec<Value> = self.lighter_sign_create_order(signer.clone(), order.clone()).as_array().cloned().unwrap_or_default(); txType = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); txInfo = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
} else {
let mut signingPayload: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("grouping_type".to_string(), groupingType);
m.insert("orders".to_string(), orderRequests);
m.insert("nonce".to_string(), self.safe_integer_k(order.clone(), "nonce", &[]));
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
signingPayload.insert("integrator_account_index".into(), self.safe_integer_k(order.clone(), "integrator_account_index", &[]));
signingPayload.insert("integrator_taker_fee".into(), self.safe_integer_k(order.clone(), "integrator_taker_fee", &[]));
signingPayload.insert("integrator_maker_fee".into(), self.safe_integer_k(order.clone(), "integrator_maker_fee", &[]));
}
{ let __destr_tmp: Vec<Value> = self.lighter_sign_create_grouped_orders(signer, Value::Map(signingPayload)).as_array().cloned().unwrap_or_default(); txType = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); txInfo = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
}
return Value::from(vec![txType, txInfo, order]);
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
}));
let txTypetxInfoorderVariable: Vec<Value> = self.sign_and_create_order(Value::Str("createOrder".into()), symbol.clone(), type_var, side, amount, &[price, params]).await.as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoorderVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoorderVariable.get(1).cloned().unwrap_or(Value::Null);
let mut order: Value = txTypetxInfoorderVariable.get(2).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_order(self.deep_extend(response, &[order]), &[market]);
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;
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("editOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("editOrder".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: Value = self.market(symbol.clone());
let mut marketInfo: indexmap::IndexMap<String, Value> = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]).as_map().cloned().unwrap_or_default();
let mut amountScale: Value = self.pow(Value::Str("10".into()), marketInfo.get("size_decimals").cloned().unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut priceScale: Value = self.pow(Value::Str("10".into()), marketInfo.get("price_decimals").cloned().unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut triggerPrice: Option<String> = self.safe_string_n_opt(paramsAccountIndex.clone(), Value::from(vec![Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::from(vec![Value::Str("stopPrice".into()), Value::Str("triggerPrice".into()), Value::Str("stopLossPrice".into()), Value::Str("takeProfitPrice".into())]), &[]);
let mut amountStr: Value = Value::Null;
let mut priceStr: Value = self.price_to_precision(symbol.clone(), price);
let mut triggerPriceStr: Value = Value::Str("0".into()); if (triggerPrice.is_some()) {
amountStr = self.number_to_string(amount.clone());
triggerPriceStr = self.price_to_precision(symbol.clone(), triggerPrice.map(Value::from).unwrap_or(Value::Null));
} else {
amountStr = self.amount_to_precision(symbol, amount);
}
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("index".to_string(), self.parse_to_int(id));
m.insert("base_amount".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&amountStr, &amountScale)));
m.insert("price".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&priceStr, &priceScale)));
m.insert("trigger_price".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&triggerPriceStr, &priceScale)));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if matches!(self.safe_bool_k(self.options.clone(), "builderFee", &[Value::Bool(true)]), Value::Bool(true)) {
signRaw.insert("integrator_account_index".into(), self.safe_integer_k(self.options.clone(), "integratorAccountIndex", &[]));
signRaw.insert("integrator_taker_fee".into(), self.safe_integer_k(self.options.clone(), "integratorTakerFee", &[]));
signRaw.insert("integrator_maker_fee".into(), self.safe_integer_k(self.options.clone(), "integratorMakerFee", &[]));
}
let __ws_arg_11 = self.extend(Value::Map(signRaw), &[paramsOmitted]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_modify_order(signer, __ws_arg_11).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_order(response, &[market]);
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 response: Value = self.root_get(&[params]).await;
let mut status: Option<String> = self.safe_string_k(response.clone(), "status", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), (if (status.as_deref() == Some("200")) { Value::Str("ok".into()) } else { Value::Str("error".into()) }));
m.insert("updated".to_string(), Value::Null);
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 response: Value = self.root_get(&[params]).await;
return self.safe_timestamp_k(response, "timestamp", &[]);
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 response: Value = self.public_get_order_book_details(&[params]).await;
let mut spotMarkets: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapMarkets: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut markets: Value = self.array_concat(spotMarkets, swapMarkets);
let mut result: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_932: bool = true;
while { if !__for_first_932 { i += 1; } __for_first_932 = false; i < (markets.len() as i64) } {
let mut market: Value = markets.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
let mut id: Option<String> = self.safe_string_k_opt(market.clone(), "market_id", &[]);
let mut type_var: Value = self.safe_string_k(market.clone(), "market_type", &[]);
if (type_var.as_str() == Some("perp")) {
type_var = Value::Str("swap".into());
}
let mut marketSymbol: Option<String> = self.safe_string_k_opt(market.clone(), "symbol", &[]);
let mut baseId: Value = marketSymbol.clone().map(Value::from).unwrap_or(Value::Null);
if (marketSymbol.is_some()) && (Value::Int(marketSymbol.as_deref().and_then(|__s| __s.find("/")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() != Value::Int(-1).as_f64()) {
let mut symbolParts: Vec<Value> = Value::Array(if let Some(__s) = marketSymbol.as_deref() { __s.split("/").map(Value::from).collect() } else { Vec::new() }).as_array().cloned().unwrap_or_default();
baseId = symbolParts.get(0).cloned().unwrap_or(Value::Null);
}
let mut quoteId: String = "USDC".to_string();
let mut settleId: Value = (if (type_var.as_str() == Some("swap")) { Value::Str("USDC".into()) } else { Value::Null });
let mut base: Value = self.safe_currency_code(baseId.clone(), &[]);
let mut quote: Value = self.safe_currency_code(Value::from(quoteId.clone()), &[]);
if (base == Value::Null) || (quote == Value::Null) {
continue;
}
let mut settle: Value = self.safe_currency_code(settleId.clone(), &[]);
let mut symbol: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", base, Value::Str("/".into())).into()), quote).into());
if (settle != Value::Null) {
symbol = Value::Str(format!("{}{}", Value::Str(format!("{}{}", symbol, Value::Str(":".into())).into()), settle).into());
}
let mut amountDecimals: Option<String> = self.safe_string2_opt(market.clone(), Value::Str("size_decimals".into()), Value::Str("supported_size_decimals".into()), &[]);
let mut priceDecimals: Option<String> = self.safe_string2_opt(market.clone(), Value::Str("price_decimals".into()), Value::Str("supported_price_decimals".into()), &[]);
let mut amountPrecision: Value = (if (amountDecimals.is_none()) { Value::Null } else { self.parse_number(self.parse_precision(&[amountDecimals.map(Value::from).unwrap_or(Value::Null)]), &[]) });
let mut pricePrecision: Value = (if (priceDecimals.is_none()) { Value::Null } else { self.parse_number(self.parse_precision(&[priceDecimals.map(Value::from).unwrap_or(Value::Null)]), &[]) });
let mut quoteMultiplier: Value = self.safe_number_k(market.clone(), "quote_multiplier", &[]);
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.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);
m.insert("quoteId".to_string(), Value::from(quoteId));
m.insert("settleId".to_string(), settleId);
m.insert("type".to_string(), type_var.clone());
m.insert("spot".to_string(), Value::Bool(type_var.as_str() == Some("spot")));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(type_var.as_str() == Some("swap")));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("active".to_string(), Value::Bool(self.safe_string_k(market.clone(), "status", &[]).as_str() == Some("active")));
m.insert("contract".to_string(), Value::Bool(type_var.as_str() == Some("swap")));
m.insert("linear".to_string(), (if (type_var.as_str() == Some("swap")) { Value::Bool(true) } else { Value::Null }));
m.insert("inverse".to_string(), (if (type_var.as_str() == Some("swap")) { Value::Bool(false) } else { Value::Null }));
m.insert("taker".to_string(), self.safe_number_k(market.clone(), "taker_fee", &[]));
m.insert("maker".to_string(), self.safe_number_k(market.clone(), "maker_fee", &[]));
m.insert("contractSize".to_string(), quoteMultiplier);
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(), amountPrecision);
m.insert("price".to_string(), pricePrecision);
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(), self.safe_number_k(market.clone(), "min_base_amount", &[]));
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.safe_number_k(market.clone(), "min_quote_amount", &[]));
m.insert("max".to_string(), self.safe_number_k(market.clone(), "order_quote_limit", &[]));
m
}));
m
}));
m.insert("created".to_string(), Value::Null);
m.insert("info".to_string(), market);
m
}));
}
}
return Value::from(result);
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
}));
let mut response: Value = self.public_get_asset_details(&[params]).await;
if self.check_required_credentials(&[Value::Bool(false)]).as_bool() == Some(true) {
self.pre_load_lighter_library(&[]).await;
}
let mut data: Value = self.safe_list_k(response, "asset_details", &[Value::from(vec![])]);
return self.parse_currencies(data);
Value::Null
}
pub fn parse_currency(&self, mut rawCurrency: Value) -> Value {
let mut id: Option<String> = self.safe_string_k_opt(rawCurrency.clone(), "asset_id", &[]);
let mut code: Value = self.safe_currency_code(self.safe_string_k(rawCurrency.clone(), "symbol", &[]), &[]);
let decimals: String = self.safe_string_k_opt(rawCurrency.clone(), "decimals", &[Value::Str("".into())]).unwrap_or_default();
let mut isUSDC: Value = (Value::Bool(code.as_str() == Some("USDC")));
let mut depositMin: Value = Value::Null;
let mut withdrawMin: Value = Value::Null;
if matches!(&isUSDC, Value::Bool(true)) {
depositMin = self.safe_number_k(rawCurrency.clone(), "min_transfer_amount", &[]);
withdrawMin = self.safe_number_k(rawCurrency.clone(), "min_withdrawal_amount", &[]);
}
return self.safe_currency_structure(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
m.insert("name".to_string(), code.clone());
m.insert("code".to_string(), code);
m.insert("precision".to_string(), self.parse_number(Value::Str(format!("{}{}", Value::Str("1e-".into()), decimals).into()), &[]));
m.insert("active".to_string(), Value::Bool(true));
m.insert("fee".to_string(), Value::Null);
m.insert("networks".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
m.insert("deposit".to_string(), isUSDC.clone());
m.insert("withdraw".to_string(), isUSDC);
m.insert("type".to_string(), Value::Str("crypto".into()));
m.insert("limits".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("deposit".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), depositMin);
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(), withdrawMin);
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("info".to_string(), rawCurrency);
m
}));
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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOrderBook() requires a symbol argument".into()))));
}
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("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("limit".to_string(), Value::Int(100));
m
});
if (limit != Value::Null) {
request.insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(250)));
}
let __ws_arg_12 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_order_book_orders(&[__ws_arg_12]).await;
let mut result: Value = self.parse_order_book(response, market.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null), &[Value::Null, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("remaining_base_amount".into())]);
return result;
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 marketId: Option<String> = self.safe_string_k_opt(ticker.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut symbol: Value = marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null);
let mut last: Option<String> = self.safe_string_k_opt(ticker.clone(), "last_trade_price", &[]);
let mut high: Option<String> = self.safe_string_k_opt(ticker.clone(), "daily_price_high", &[]);
let mut low: Option<String> = self.safe_string_k_opt(ticker.clone(), "daily_price_low", &[]);
let mut baseVolume: Option<String> = self.safe_string_k_opt(ticker.clone(), "daily_base_token_volume", &[]);
let mut quoteVolume: Option<String> = self.safe_string_k_opt(ticker.clone(), "daily_quote_token_volume", &[]);
let mut change: Option<String> = self.safe_string_k_opt(ticker.clone(), "daily_price_change", &[]);
return self.safe_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("symbol".to_string(), symbol);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), high.map(Value::from).unwrap_or(Value::Null));
m.insert("low".to_string(), low.map(Value::from).unwrap_or(Value::Null));
m.insert("bid".to_string(), Value::Null);
m.insert("bidVolume".to_string(), Value::Null);
m.insert("ask".to_string(), Value::Null);
m.insert("askVolume".to_string(), Value::Null);
m.insert("vwap".to_string(), Value::Null);
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), last.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("last".to_string(), last.map(Value::from).unwrap_or(Value::Null));
m.insert("previousClose".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), change.map(Value::from).unwrap_or(Value::Null));
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), baseVolume.map(Value::from).unwrap_or(Value::Null));
m.insert("quoteVolume".to_string(), quoteVolume.map(Value::from).unwrap_or(Value::Null));
m.insert("markPrice".to_string(), self.safe_string_k(ticker.clone(), "mark_price", &[]));
m.insert("indexPrice".to_string(), self.safe_string_k(ticker.clone(), "index_price", &[]));
m.insert("info".to_string(), ticker);
m
}), &[marketResolved]);
Value::Null
}
pub async fn fetch_ticker(&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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() requires a symbol argument".into()))));
}
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("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m
});
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_order_book_details(&[__ws_arg_13]).await;
let mut spotTickers: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapTickers: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut tickers: Value = self.array_concat(spotTickers, swapTickers);
let mut first: Value = self.safe_dict(tickers, Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_ticker(first, &[market]);
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 = self.public_get_order_book_details(&[params]).await;
let mut spotTickers: Value = self.safe_list_k(response.clone(), "spot_order_book_details", &[Value::from(vec![])]);
let mut swapTickers: Value = self.safe_list_k(response, "order_book_details", &[Value::from(vec![])]);
let mut tickers: Value = self.array_concat(spotTickers, swapTickers);
return self.parse_tickers(tickers, &[symbolsNormalized]);
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_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
let mut timeframe = get_arg(optional_args, 0, Value::Str("1h".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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() requires a symbol argument".into()))));
}
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", &[]);
let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("until".into())]), &[]);
let mut now: Value = self.milliseconds();
let mut startTs: Value = Value::Null;
let mut endTs: Value = Value::Null;
if (since != Value::Null) {
startTs = since.clone();
if (until != Value::Null) {
endTs = until.clone();
} else if (limit != Value::Null) {
let mut duration: Value = self.parse_timeframe(timeframe.clone());
endTs = self.sum(&[since.clone(), (match (&((match (&(duration), &(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(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 })]);
} else {
endTs = now.clone();
}
} else {
let mut count: Value = self.safe_integer(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), limit.clone());
m
}), Value::Str("limit".into()), &[Value::Int(100)]);
let mut timeframeMs: 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 });
let mut span: Value = (match (&(timeframeMs), &(count)) { (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 (until != Value::Null) {
endTs = until.clone();
startTs = (match (&(until), &(span)) { (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 });
} else {
endTs = now.clone();
startTs = (match (&(now), &(span)) { (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 request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("count_back".to_string(), Value::Int(0));
m.insert("resolution".to_string(), self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]));
m.insert("start_timestamp".to_string(), startTs);
m.insert("end_timestamp".to_string(), endTs);
m
});
let __ws_arg_14 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.public_get_candles(&[__ws_arg_14]).await;
let mut ohlcvs: Value = self.safe_list_k(response, "c", &[Value::from(vec![])]);
return self.parse_ohlc_vs(ohlcvs, &[market, timeframe, since, limit]);
Value::Null
}
pub fn parse_funding_rate(&self, mut contract: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut marketId: Option<String> = self.safe_string_k_opt(contract.clone(), "market_id", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), contract.clone());
m.insert("symbol".to_string(), self.safe_symbol(marketId.map(Value::from).unwrap_or(Value::Null), &[market]));
m.insert("markPrice".to_string(), Value::Null);
m.insert("indexPrice".to_string(), Value::Null);
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(), self.safe_number_k(contract, "rate", &[]));
m.insert("fundingTimestamp".to_string(), Value::Null);
m.insert("fundingDatetime".to_string(), Value::Null);
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::Null);
m
});
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 __ws_arg_15 = self.extend(params, &[]);
let mut response: Value = self.public_get_funding_rates(&[__ws_arg_15]).await;
let mut data: Vec<Value> = self.safe_list_k(response, "funding_rates", &[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_933: bool = true;
while { if !__for_first_933 { i += 1; } __for_first_933 = false; i < (data.len() as i64) } {
let mut exchange: Option<String> = self.safe_string_k(data.get(i as usize).cloned().unwrap_or(Value::Null), "exchange", &[]).as_str().map(str::to_owned);
if (exchange.as_deref() == Some("lighter")) {
result.push(data.get(i as usize).cloned().unwrap_or(Value::Null));
}
}
}
return self.parse_funding_rates(Value::from(result), &[symbols]);
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(params, Value::Str("fetchBalance".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut defaultType: Value = self.safe_string2(self.options.clone(), Value::Str("fetchBalance".into()), Value::Str("defaultType".into()), &[Value::Str("spot".into())]);
let mut type_var: Option<String> = self.safe_string_k(paramsAccountIndex.clone(), "type", &[defaultType]).as_str().map(str::to_owned);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_16 = self.extend(Value::Map(request), &[paramsAccountIndex]);
let mut response: Value = self.public_get_account(&[__ws_arg_16]).await;
let mut result: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), response.clone());
m
});
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
{
let mut i: i64 = 0;
let mut __for_first_935: bool = true;
while { if !__for_first_935 { i += 1; } __for_first_935 = false; i < (accounts.len() as i64) } {
let mut account: Value = self.safe_dict(accounts.clone(), Value::Int(i), &[]);
if (type_var.as_deref() == Some("spot")) {
let mut assets: Value = self.safe_list_k(account.clone(), "assets", &[Value::from(vec![])]);
{
let mut j: i64 = 0;
let mut __for_first_934: bool = true;
while { if !__for_first_934 { j += 1; } __for_first_934 = false; j < (assets.len() as i64) } {
let mut asset: Value = self.safe_dict(assets.clone(), Value::Int(j), &[]);
let mut codeId: Option<String> = self.safe_string_k_opt(asset.clone(), "symbol", &[]);
let mut code: Value = self.safe_currency_code(codeId.map(Value::from).unwrap_or(Value::Null), &[]);
let __ws_arg_17 = self.account();
let __ws_arg_18 = self.safe_dict(Value::Map(result.clone()), code.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut balance: Value = self.extend(__ws_arg_17, &[__ws_arg_18]);
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&balance, "total"), &self.safe_string_k(asset.clone(), "balance", &[])); if let Value::Dict(__d) = &mut balance { std::sync::Arc::make_mut(__d).insert("total".into(), __be_tmp); } }
{ let __be_tmp = crate::precise::Precise::stringAdd(&crate::value::get_value_k(&balance, "used"), &self.safe_string_k(asset, "locked_balance", &[])); if let Value::Dict(__d) = &mut balance { std::sync::Arc::make_mut(__d).insert("used".into(), __be_tmp); } }
if (code != Value::Null) {
result.insert(crate::runtime::stringify_param(&code), balance);
}
}
}
} else {
let __ws_arg_19 = self.account();
let __ws_arg_20 = self.safe_dict(Value::Map(result.clone()), Value::Str("USDC".into()), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut perpBalance: Value = self.extend(__ws_arg_19, &[__ws_arg_20]);
let mut perpTotal: Value = self.safe_string_k(perpBalance.clone(), "total", &[Value::Str("0".into())]);
let mut perpFree: Value = self.safe_string_k(perpBalance.clone(), "free", &[Value::Str("0".into())]);
let mut perpUSDCTotal: Value = self.safe_string_k(account.clone(), "collateral", &[Value::Str("0".into())]);
let mut perpUSDCFree: Value = self.safe_string_k(account, "available_balance", &[Value::Str("0".into())]);
if let Value::Dict(__d) = &mut perpBalance { std::sync::Arc::make_mut(__d).insert("total".into(), crate::precise::Precise::stringAdd(&perpTotal, &perpUSDCTotal)); }
if let Value::Dict(__d) = &mut perpBalance { std::sync::Arc::make_mut(__d).insert("free".into(), crate::precise::Precise::stringAdd(&perpFree, &perpUSDCFree)); }
result.insert("USDC".into(), perpBalance);
}
}
}
return self.safe_balance(Value::Map(result));
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 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 accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(params, Value::Str("fetchPositions".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_21 = self.extend(Value::Map(request), &[paramsAccountIndex]);
let mut response: Value = self.public_get_account(&[__ws_arg_21]).await;
let mut allPositions: Vec<Value> = Vec::new();
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
{
let mut i: i64 = 0;
let mut __for_first_937: bool = true;
while { if !__for_first_937 { i += 1; } __for_first_937 = false; i < (accounts.len() as i64) } {
let mut account: Value = self.safe_dict(accounts.clone(), Value::Int(i), &[]);
let mut positions: Vec<Value> = self.safe_list_k(account, "positions", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
{
let mut j: i64 = 0;
let mut __for_first_936: bool = true;
while { if !__for_first_936 { j += 1; } __for_first_936 = false; j < (positions.len() as i64) } {
allPositions.push(positions.get(j as usize).cloned().unwrap_or(Value::Null));
}
}
}
}
return self.parse_positions(Value::from(allPositions), &[symbols]);
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 marketId: Option<String> = self.safe_string_k_opt(position.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut sign: Option<i64> = self.safe_integer_k(position.clone(), "sign", &[]).as_i64();
let mut side: Value = Value::Null;
if (sign.is_some()) {
side = (if (sign == Some(1)) { Value::Str("long".into()) } else { Value::Str("short".into()) });
}
let mut marginModeId: Option<i64> = self.safe_integer_k(position.clone(), "margin_mode", &[]).as_i64();
let mut marginMode: Value = Value::Null;
if (marginModeId.is_some()) {
marginMode = (if (marginModeId == Some(0)) { Value::Str("cross".into()) } else { Value::Str("isolated".into()) });
}
let mut imfStr: Option<String> = self.safe_string_k_opt(position.clone(), "initial_margin_fraction", &[]);
let mut leverage: Value = Value::Null;
if (imfStr.is_some()) {
let mut imf: Value = self.parse_to_int(imfStr.map(Value::from).unwrap_or(Value::Null));
if imf.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
leverage = (match ((Value::Int(100)).as_f64(), (imf).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null });
}
}
let mut contractsString: Option<String> = self.safe_string_k_opt(position.clone(), "position", &[]);
let mut positionValueString: Option<String> = self.safe_string_k_opt(position.clone(), "position_value", &[]);
let mut markPriceString: Value = crate::precise::Precise::stringDiv(&positionValueString.clone().map(Value::from).unwrap_or(Value::Null), &contractsString.clone().map(Value::from).unwrap_or(Value::Null));
let mut positionMargin: Value = Value::Null;
if (marginMode.as_str() == Some("isolated")) {
positionMargin = self.safe_number_k(position.clone(), "allocated_margin", &[]);
}
return self.safe_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), position.clone());
m.insert("id".to_string(), Value::Null);
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("isolated".to_string(), (Value::Bool(marginMode.as_str() == Some("isolated"))));
m.insert("hedged".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("contracts".to_string(), self.parse_number(contractsString.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("contractSize".to_string(), Value::Null);
m.insert("entryPrice".to_string(), self.safe_number_k(position.clone(), "avg_entry_price", &[]));
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(), leverage);
m.insert("positionMargin".to_string(), positionMargin);
m.insert("collateral".to_string(), Value::Null);
m.insert("initialMargin".to_string(), Value::Null);
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.safe_number_k(position.clone(), "unrealized_pnl", &[]));
m.insert("liquidationPrice".to_string(), self.safe_number_k(position, "liquidation_price", &[]));
m.insert("marginMode".to_string(), marginMode);
m.insert("percentage".to_string(), Value::Null);
m
}));
Value::Null
}
pub async fn fetch_accounts(&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.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(params, Value::Str("fetchAccounts".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("by".to_string(), self.safe_string_k(paramsAccountIndex.clone(), "by", &[Value::Str("index".into())]));
m.insert("value".to_string(), accountIndex);
m
});
let __ws_arg_22 = self.extend(Value::Map(request), &[paramsAccountIndex.clone()]);
let mut response: Value = self.public_get_account(&[__ws_arg_22]).await;
let mut accounts: Value = self.safe_list_k(response, "accounts", &[Value::from(vec![])]);
return self.parse_accounts(accounts, &[paramsAccountIndex]);
Value::Null
}
pub fn parse_account(&self, mut account: Value) -> Value {
let mut accountType: Option<String> = self.safe_string_k(account.clone(), "account_type", &[]).as_str().map(str::to_owned);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(account.clone(), "account_index", &[]));
m.insert("type".to_string(), (if (accountType.as_deref() == Some("0")) { Value::Str("main".into()) } else { Value::Str("subaccount".into()) }));
m.insert("code".to_string(), Value::Null);
m.insert("info".to_string(), account);
m
});
Value::Null
}
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
}));
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(params, Value::Str("fetchOpenOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchOpenOrders".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_23 = self.extend(Value::Map(request), &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_account_active_orders(&[__ws_arg_23]).await;
let mut data: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_orders(data, &[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 (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchClosedOrders() requires a symbol argument".into()))));
}
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(params, Value::Str("fetchClosedOrders".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchClosedOrders".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("account_index".to_string(), accountIndex);
m.insert("limit".to_string(), Value::Int(100));
m
});
if (limit != Value::Null) {
request.insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100)));
}
let __ws_arg_24 = self.extend(Value::Map(request), &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_account_inactive_orders(&[__ws_arg_24]).await;
let mut data: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
return self.parse_orders(data, &[market, since, limit]);
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 marketId: Option<String> = self.safe_string_k_opt(order.clone(), "market_index", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Value = self.safe_timestamp_k(order.clone(), "timestamp", &[]);
let mut isAsk: Option<bool> = self.safe_bool_k_opt(order.clone(), "is_ask", &[]);
let mut isAskAsInteger: Option<i64> = self.safe_integer_k(order.clone(), "is_ask", &[]).as_i64();
let mut side: Value = Value::Null;
if (isAsk.is_some()) {
side = (if isAsk == Some(true) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
} else if (isAskAsInteger.is_some()) {
side = (if (isAskAsInteger == Some(1)) { Value::Str("sell".into()) } else { Value::Str("buy".into()) });
}
let mut type_var: Value = self.safe_string_k(order.clone(), "type", &[]);
if (type_var == Value::Null) {
let mut typeAsInteger: Value = self.safe_integer_k(order.clone(), "order_type", &[]);
type_var = self.parse_order_type_integer(typeAsInteger).map(Value::from).unwrap_or(Value::Null);
}
let mut triggerPrice: Value = self.parse_number(self.omit_zero(self.safe_string_k(order.clone(), "trigger_price", &[])), &[]);
let mut stopLossPrice: Value = Value::Null;
let mut takeProfitPrice: Value = Value::Null;
if (type_var != Value::Null) {
if type_var.as_str().unwrap_or("").contains("stop-loss") {
stopLossPrice = triggerPrice.clone();
}
if type_var.as_str().unwrap_or("").contains("take-profit") {
takeProfitPrice = triggerPrice.clone();
}
}
let mut tifAsInteger: Value = self.safe_integer_k(order.clone(), "time_in_force", &[]);
let mut tif: Value = (if (tifAsInteger != Value::Null) { self.parse_order_time_in_force_integer(tifAsInteger).map(Value::from).unwrap_or(Value::Null) } else { self.safe_string_k(order.clone(), "time_in_force", &[]) });
let mut reduceOnlyAsBool: Value = self.safe_bool_k(order.clone(), "reduce_only", &[]);
let mut reduceOnlyAsInteger: Option<i64> = self.safe_integer_k(order.clone(), "reduce_only", &[]).as_i64();
let mut reduceOnly: Value = reduceOnlyAsBool.clone();
if (reduceOnlyAsBool == Value::Null) && (reduceOnlyAsInteger.is_some()) {
reduceOnly = (Value::Bool(reduceOnlyAsInteger == Some(1)));
}
let mut status: Option<String> = self.safe_string_k_opt(order.clone(), "status", &[]);
return self.safe_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), order.clone());
m.insert("id".to_string(), self.safe_string_k(order.clone(), "order_id", &[]));
m.insert("clientOrderId".to_string(), self.omit_zero(self.safe_string2(order.clone(), Value::Str("client_order_id".into()), Value::Str("client_order_index".into()), &[])));
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), self.safe_timestamp_k(order.clone(), "updated_at", &[]));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("type".to_string(), self.parse_order_type(type_var).map(Value::from).unwrap_or(Value::Null));
m.insert("timeInForce".to_string(), self.parse_order_time_in_force(tif.clone()).map(Value::from).unwrap_or(Value::Null));
m.insert("postOnly".to_string(), Value::Bool(tif.as_str() == Some("post-only")));
m.insert("reduceOnly".to_string(), reduceOnly);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_string_k(order.clone(), "price", &[]));
m.insert("triggerPrice".to_string(), triggerPrice);
m.insert("stopLossPrice".to_string(), stopLossPrice);
m.insert("takeProfitPrice".to_string(), takeProfitPrice);
m.insert("amount".to_string(), self.safe_string_k(order.clone(), "initial_base_amount", &[]));
m.insert("cost".to_string(), self.safe_string_k(order.clone(), "filled_quote_amount", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("filled".to_string(), self.safe_string_k(order.clone(), "filled_base_amount", &[]));
m.insert("remaining".to_string(), self.safe_string_k(order, "remaining_base_amount", &[]));
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> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("in-progress".to_string(), Value::Str("open".into()));
m.insert("pending".to_string(), Value::Str("open".into()));
m.insert("open".to_string(), Value::Str("open".into()));
m.insert("filled".to_string(), Value::Str("closed".into()));
m.insert("canceled".to_string(), Value::Str("canceled".into()));
m.insert("canceled-post-only".to_string(), Value::Str("canceled".into()));
m.insert("canceled-reduce-only".to_string(), Value::Str("canceled".into()));
m.insert("canceled-position-not-allowed".to_string(), Value::Str("rejected".into()));
m.insert("canceled-margin-not-allowed".to_string(), Value::Str("rejected".into()));
m.insert("canceled-too-much-slippage".to_string(), Value::Str("canceled".into()));
m.insert("canceled-not-enough-liquidity".to_string(), Value::Str("canceled".into()));
m.insert("canceled-self-trade".to_string(), Value::Str("canceled".into()));
m.insert("canceled-expired".to_string(), Value::Str("expired".into()));
m.insert("canceled-oco".to_string(), Value::Str("canceled".into()));
m.insert("canceled-child".to_string(), Value::Str("canceled".into()));
m.insert("canceled-liquidation".to_string(), Value::Str("canceled".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type(&self, mut type_var: Value) -> Option<String> {
let mut types: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("limit".to_string(), Value::Str("limit".into()));
m.insert("market".to_string(), Value::Str("market".into()));
m.insert("stop-loss".to_string(), Value::Str("market".into()));
m.insert("stop-loss-limit".to_string(), Value::Str("limit".into()));
m.insert("take-profit".to_string(), Value::Str("market".into()));
m.insert("take-profit-limit".to_string(), Value::Str("limit".into()));
m.insert("twap".to_string(), Value::Str("twap".into()));
m.insert("twap-sub".to_string(), Value::Str("twap".into()));
m.insert("liquidation".to_string(), Value::Str("market".into()));
m
});
return self.safe_string(Value::Map(types), type_var.clone(), &[type_var.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_type_integer(&self, mut typeInteger: Value) -> Option<String> {
if (typeInteger == Value::Null) {
return None;
}
let mut types: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("limit".into()));
m.insert("1".to_string(), Value::Str("market".into()));
m.insert("2".to_string(), Value::Str("stop-loss".into()));
m.insert("3".to_string(), Value::Str("stop-loss-limit".into()));
m.insert("4".to_string(), Value::Str("take-profit".into()));
m.insert("5".to_string(), Value::Str("take-profit-limit".into()));
m.insert("6".to_string(), Value::Str("twap".into()));
m.insert("7".to_string(), Value::Str("twap-sub".into()));
m.insert("8".to_string(), Value::Str("liquidation".into()));
m
});
return self.safe_string(types, Value::Str(format!("{}", typeInteger).into()), &[]).as_str().map(str::to_owned);
}
pub fn parse_order_time_in_force(&self, mut tif: Value) -> Option<String> {
let mut timeInForces: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("immediate-or-cancel".to_string(), Value::Str("IOC".into()));
m.insert("good-till-time".to_string(), Value::Str("GTC".into()));
m.insert("post-only".to_string(), Value::Str("PO".into()));
m.insert("Unknown".to_string(), Value::Null);
m
});
return self.safe_string(Value::Map(timeInForces), tif.clone(), &[tif.clone()]).as_str().map(str::to_owned);
}
pub fn parse_order_time_in_force_integer(&self, mut tifInteger: Value) -> Option<String> {
let mut timeInForces: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("0".to_string(), Value::Str("immediate-or-cancel".into()));
m.insert("1".to_string(), Value::Str("good-till-time".into()));
m.insert("2".to_string(), Value::Str("post-only".into()));
m
});
return self.safe_string(timeInForces, self.number_to_string(tifInteger), &[]).as_str().map(str::to_owned);
}
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("transfer".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("transfer".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let toAccountIndexparamsToAccountIndexVariable: Vec<Value> = self.handle_option_and_params2(paramsAccountIndex, Value::Str("transfer".into()), Value::Str("toAccountIndex".into()), Value::Str("to_account_index".into()), &[accountIndex.clone()]).as_array().cloned().unwrap_or_default();
let mut toAccountIndex: Value = toAccountIndexparamsToAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsToAccountIndex: Value = toAccountIndexparamsToAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsToAccountIndex.clone()]).await;
let mut currency: indexmap::IndexMap<String, Value> = self.currency(code.clone()).as_map().cloned().unwrap_or_default();
let mut currencyCode: Value = currency.get("code").cloned().unwrap_or(Value::Null);
if (currencyCode.as_str() != Some("USDC")) && (currencyCode.as_str() != Some("ETH")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" transfer() only supports USDC and ETH transfers".into()))));
}
let mut amountDecimals: Value = (if (currencyCode.as_str() == Some("USDC")) { Value::Str("6".into()) } else { Value::Str("8".into()) });
let mut amountScaled: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), amountDecimals).map(Value::from).unwrap_or(Value::Null), &self.currency_to_precision(code, amount, &[])));
let mut fromRouteType: Value = (if (fromAccount.as_str() == Some("perp")) { Value::Int(0) } else { Value::Int(1) }); let mut toRouteType: Value = (if (toAccount.as_str() == Some("perp")) { Value::Int(0) } else { Value::Int(1) });
let mut memo: Value = self.safe_string_k(paramsToAccountIndex.clone(), "memo", &[Value::Str("0x000000000000000000000000000000".into())]);
let mut paramsOmitted: Value = self.omit(paramsToAccountIndex, Value::from(vec![Value::Str("memo".into())]), &[]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("to_account_index".to_string(), toAccountIndex);
m.insert("asset_index".to_string(), self.parse_to_int(currency.get("id").cloned().unwrap_or(Value::Null)));
m.insert("from_route_type".to_string(), fromRouteType);
m.insert("to_route_type".to_string(), toRouteType);
m.insert("amount".to_string(), amountScaled);
m.insert("usdc_fee".to_string(), Value::Int(0));
m.insert("memo".to_string(), memo);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_25 = self.extend(Value::Map(signRaw), &[paramsOmitted]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_transfer(signer, __ws_arg_25).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_transfer(response, &[]);
Value::Null
}
pub async fn fetch_transfers(&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 paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchTransfers".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_cursor(Value::Str("fetchTransfers".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsPaginate, Value::Str("fetchTransfers".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex.clone());
m
});
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchTransfers".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
}
let __ws_arg_26 = self.extend(Value::Map(request), &[paramsApiKeyIndex.clone()]);
let mut response: Value = self.private_get_transfer_history(&[__ws_arg_26]).await;
let mut rows: Value = self.safe_list_k(response.clone(), "transfers", &[Value::from(vec![])]);
let mut cursor: Option<String> = self.safe_string_k_opt(response, "cursor", &[]);
let mut first: Value = self.safe_dict(rows.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor.is_some()) {
add_element_to_object(get_value_mut(&mut rows, &Value::Int(0)), &Value::Str("cursor".into()), cursor.map(Value::from).unwrap_or(Value::Null));
}
return self.parse_transfers(rows, &[currency, since, limit, paramsApiKeyIndex]);
Value::Null
}
pub fn parse_transfer(&self, mut transfer: Value, optional_args: &[Value]) -> Value {
let mut currency = get_arg(optional_args, 0, Value::Null);
let mut currencyId: Option<String> = self.safe_string_k_opt(transfer.clone(), "asset_id", &[]);
let mut code: Value = self.safe_currency_code(currencyId.map(Value::from).unwrap_or(Value::Null), &[currency]);
let mut timestamp: Option<i64> = self.safe_integer_k(transfer.clone(), "timestamp", &[]).as_i64();
let mut fromAccount: Value = self.safe_dict_k(transfer.clone(), "from", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut toAccount: Value = self.safe_dict_k(transfer.clone(), "to", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(transfer.clone(), "id", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("currency".to_string(), code);
m.insert("amount".to_string(), self.safe_number_k(transfer.clone(), "amount", &[]));
m.insert("fromAccount".to_string(), self.safe_string_k(fromAccount, "from_account_index", &[]));
m.insert("toAccount".to_string(), self.safe_string_k(toAccount, "to_account_index", &[]));
m.insert("status".to_string(), Value::Null);
m.insert("info".to_string(), transfer);
m
});
Value::Null
}
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 paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchDeposits".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_cursor(Value::Str("fetchDeposits".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let addressparamsAddressVariable: Vec<Value> = self.handle_option_string_and_params2(paramsPaginate, Value::Str("fetchDeposits".into()), Value::Str("address".into()), Value::Str("l1_address".into()), &[]).as_array().cloned().unwrap_or_default();
let mut address: Value = addressparamsAddressVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAddress: Value = addressparamsAddressVariable.get(1).cloned().unwrap_or(Value::Null);
if (address == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchDeposits() requires an address parameter".into()))));
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsAddress, Value::Str("fetchDeposits".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("account_index".to_string(), accountIndex.clone());
m.insert("l1_address".to_string(), address);
m
});
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchDeposits".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
request.insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
let __ws_arg_27 = self.extend(Value::Map(request), &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_deposit_history(&[__ws_arg_27]).await;
let mut data: Value = self.safe_list_k(response.clone(), "deposits", &[Value::from(vec![])]);
let mut cursor: Option<String> = self.safe_string_k_opt(response, "cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor.is_some()) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("cursor".into()), cursor.map(Value::from).unwrap_or(Value::Null));
}
return self.parse_transactions(data, &[currency, 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
}));
let paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchWithdrawals".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_cursor(Value::Str("fetchWithdrawals".into()), &[code.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsPaginate, Value::Str("fetchWithdrawals".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.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("account_index".to_string(), accountIndex.clone());
m
});
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchWithdrawals".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex);
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut currency: Value = Value::Null;
if (code != Value::Null) {
currency = self.currency(code);
request.insert("coin".into(), currency.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
let __ws_arg_28 = self.extend(Value::Map(request), &[paramsApiKeyIndex]);
let mut response: Value = self.private_get_withdraw_history(&[__ws_arg_28]).await;
let mut data: Value = self.safe_list_k(response.clone(), "withdraws", &[Value::from(vec![])]);
let mut cursor: Option<String> = self.safe_string_k_opt(response, "cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (cursor.is_some()) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("cursor".into()), cursor.map(Value::from).unwrap_or(Value::Null));
}
return self.parse_transactions(data, &[currency, since, limit]);
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 type_var: Value = self.safe_string_k(transaction.clone(), "type", &[]);
if (type_var == Value::Null) {
type_var = Value::Str("deposit".into());
} else {
type_var = Value::Str("withdrawal".into());
}
let mut timestamp: Option<i64> = self.safe_integer_k(transaction.clone(), "timestamp", &[]).as_i64();
let mut status: Option<String> = self.safe_string_k_opt(transaction.clone(), "status", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), transaction.clone());
m.insert("id".to_string(), self.safe_string_k(transaction.clone(), "id", &[]));
m.insert("txid".to_string(), self.safe_string_k(transaction.clone(), "l1_tx_hash", &[]));
m.insert("type".to_string(), type_var);
m.insert("currency".to_string(), self.safe_currency_code(self.safe_string_k(transaction.clone(), "asset_id", &[]), &[currency]));
m.insert("network".to_string(), Value::Null);
m.insert("amount".to_string(), self.safe_number_k(transaction, "amount", &[]));
m.insert("status".to_string(), self.parse_transaction_status(status.map(Value::from).unwrap_or(Value::Null)).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("address".to_string(), Value::Null);
m.insert("addressFrom".to_string(), Value::Null);
m.insert("addressTo".to_string(), Value::Null);
m.insert("tag".to_string(), Value::Null);
m.insert("tagFrom".to_string(), Value::Null);
m.insert("tagTo".to_string(), Value::Null);
m.insert("updated".to_string(), Value::Null);
m.insert("comment".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("internal".to_string(), Value::Null);
m
});
Value::Null
}
pub fn parse_transaction_status(&self, mut status: Value) -> Option<String> {
let mut statuses: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("failed".to_string(), Value::Str("failed".into()));
m.insert("pending".to_string(), Value::Str("pending".into()));
m.insert("completed".to_string(), Value::Str("ok".into()));
m.insert("claimable".to_string(), Value::Str("ok".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("withdraw".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("withdraw".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut currency: indexmap::IndexMap<String, Value> = self.currency(code.clone()).as_map().cloned().unwrap_or_default();
let mut currencyCode: Value = currency.get("code").cloned().unwrap_or(Value::Null);
if (currencyCode.as_str() != Some("USDC")) && (currencyCode.as_str() != Some("ETH")) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" withdraw() only supports USDC and ETH transfers".into()))));
}
let mut amountDecimals: Value = (if (currencyCode.as_str() == Some("USDC")) { Value::Str("6".into()) } else { Value::Str("8".into()) });
let mut amountScaled: Value = self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), amountDecimals).map(Value::from).unwrap_or(Value::Null), &self.currency_to_precision(code, amount, &[])));
let mut routeType: Option<i64> = self.safe_integer_k(paramsAccountIndex.clone(), "routeType", &[Value::Int(0)]).as_i64(); let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::Str("routeType".into()), &[]);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("asset_index".to_string(), self.parse_to_int(currency.get("id").cloned().unwrap_or(Value::Null)));
m.insert("route_type".to_string(), Value::from(routeType));
m.insert("amount".to_string(), amountScaled);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_29 = self.extend(Value::Map(signRaw), &[paramsOmitted]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_withdraw(signer, __ws_arg_29).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_transaction(response, &[]);
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
}));
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("market_id".to_string(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
m.insert("limit".to_string(), Value::Int(100));
m
});
if (limit != Value::Null) {
request.insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100)));
}
let __ws_arg_30 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.public_get_recent_trades(&[__ws_arg_30]).await;
let mut trades: Value = self.safe_list_k(response, "trades", &[Value::from(vec![])]);
return self.parse_trades(trades, &[market, since, limit]);
Value::Null
}
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let paginateparamsPaginateVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default();
let mut paginate: Value = paginateparamsPaginateVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPaginate: Value = paginateparamsPaginateVariable.get(1).cloned().unwrap_or(Value::Null);
if paginate.as_bool() == Some(true) {
return self.fetch_paginated_call_cursor(Value::Str("fetchMyTrades".into()), &[symbol.clone(), since.clone(), limit.clone(), paramsPaginate.clone(), Value::Str("next_cursor".into()), Value::Str("cursor".into()), Value::Null, Value::Int(50)]).await;
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsPaginate, Value::Str("fetchMyTrades".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(paramsAccountIndex, Value::Str("fetchMyTrades".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex);
self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsApiKeyIndex.clone()]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("sort_by".to_string(), Value::Str("timestamp".into()));
m.insert("limit".to_string(), Value::Int(100));
m.insert("account_index".to_string(), accountIndex.clone());
m
});
if (limit != Value::Null) {
request.insert("limit".into(), crate::runtime::Math::min(&limit, &Value::Int(100)));
}
let untilparamsUntilVariable: Vec<Value> = self.handle_option_integer_and_params2(paramsApiKeyIndex, Value::Str("fetchMyTrades".into()), Value::Str("until".into()), Value::Str("from".into()), &[]).as_array().cloned().unwrap_or_default();
let mut until: Value = untilparamsUntilVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsUntil: Value = untilparamsUntilVariable.get(1).cloned().unwrap_or(Value::Null);
if (until != Value::Null) {
request.insert("from".into(), until);
}
let mut market: Value = Value::Null;
if (symbol != Value::Null) {
market = self.market(symbol);
request.insert("market_id".into(), market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
}
let __ws_arg_31 = self.extend(Value::Map(request), &[paramsUntil.clone()]);
let mut response: Value = self.private_get_trades(&[__ws_arg_31]).await;
let mut data: Value = self.safe_list_k(response.clone(), "trades", &[Value::from(vec![])]);
{
let mut i: Value = Value::Int(0);
let mut __for_first_938: bool = true;
while { if !__for_first_938 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_938 = false; i.as_f64().unwrap_or(f64::NAN) < ((data.len() as i64) as f64) } {
add_element_to_object(get_value_mut(&mut data, &i), &Value::Str("account_index".into()), accountIndex.clone());
}
}
let mut nextCursor: Option<String> = self.safe_string_k_opt(response, "next_cursor", &[]);
let mut first: Value = self.safe_dict(data.clone(), Value::Int(0), &[]);
if (first != Value::Null) && (nextCursor.is_some()) {
add_element_to_object(get_value_mut(&mut data, &Value::Int(0)), &Value::Str("next_cursor".into()), nextCursor.map(Value::from).unwrap_or(Value::Null));
}
return self.parse_trades(data, &[market, since, limit, paramsUntil]);
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 marketId: Option<String> = self.safe_string_k_opt(trade.clone(), "market_id", &[]);
let mut marketResolved: Value = self.safe_market(&[marketId.map(Value::from).unwrap_or(Value::Null), market]);
let mut timestamp: Option<i64> = self.safe_integer_k(trade.clone(), "timestamp", &[]).as_i64();
let mut accountIndex: Value = self.safe_string_k(trade.clone(), "account_index", &[]);
let mut askAccountId: Value = self.safe_string_k(trade.clone(), "ask_account_id", &[]);
let mut bidAccountId: Value = self.safe_string_k(trade.clone(), "bid_account_id", &[]);
let mut isMakerAsk: Option<bool> = self.safe_bool_k_opt(trade.clone(), "is_maker_ask", &[]);
let mut side: Value = Value::Null;
let mut orderId: Value = Value::Null;
if (accountIndex != Value::Null) {
if (accountIndex == askAccountId) {
side = Value::Str("sell".into());
orderId = self.safe_string_k(trade.clone(), "ask_id", &[]);
} else if (accountIndex == bidAccountId) {
side = Value::Str("buy".into());
orderId = self.safe_string_k(trade.clone(), "bid_id", &[]);
}
}
if (side == Value::Null) && (isMakerAsk.is_some()) {
side = (if isMakerAsk == Some(true) { Value::Str("buy".into()) } else { Value::Str("sell".into()) });
}
let mut takerOrMaker: Value = Value::Null;
if (side != Value::Null) && (isMakerAsk.is_some()) {
let mut isMaker: Value = (if (side.as_str() == Some("sell")) { (Value::Bool(isMakerAsk == Some(true))) } else { (Value::Bool(isMakerAsk == Some(false))) });
takerOrMaker = (if isMaker.as_bool() == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
return self.safe_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), trade.clone());
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "trade_id", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("symbol".to_string(), marketResolved.as_map().and_then(|__m| __m.get("symbol")).cloned().unwrap_or(Value::Null));
m.insert("order".to_string(), orderId);
m.insert("type".to_string(), self.safe_string_k(trade.clone(), "type", &[]));
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), self.safe_string_k(trade.clone(), "price", &[]));
m.insert("amount".to_string(), self.safe_string_k(trade.clone(), "size", &[]));
m.insert("cost".to_string(), self.safe_string_k(trade, "usd_amount", &[]));
m.insert("fee".to_string(), Value::Null);
m
}), &[marketResolved]);
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()))));
}
let marginModeparamsMarginModeVariable: Vec<Value> = self.handle_option_string_and_params2(params, Value::Str("setLeverage".into()), Value::Str("marginMode".into()), Value::Str("margin_mode".into()), &[]).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);
if (marginMode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setLeverage() requires an marginMode parameter".into()))));
}
return self.modify_leverage_and_margin_mode(leverage, marginMode, &[symbol, paramsMarginMode]).await;
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 (marginMode == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires an marginMode parameter".into()))));
}
let leverageparamsLeverageVariable: Vec<Value> = self.handle_option_and_params(params, Value::Str("setMarginMode".into()), Value::Str("leverage".into()), &[]).as_array().cloned().unwrap_or_default();
let mut leverage: Value = leverageparamsLeverageVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsLeverage: Value = leverageparamsLeverageVariable.get(1).cloned().unwrap_or(Value::Null);
if (leverage == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMarginMode() requires an leverage parameter".into()))));
}
return self.modify_leverage_and_margin_mode(leverage, marginMode, &[symbol, paramsLeverage]).await;
Value::Null
}
pub async fn modify_leverage_and_margin_mode(&mut self, mut leverage: Value, 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 (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (marginMode.as_str() != Some("cross")) && (marginMode.as_str() != Some("isolated")) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" modifyLeverageAndMarginMode() requires a marginMode parameter that must be either cross or isolated".into()))));
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("modifyLeverageAndMarginMode".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" modifyLeverageAndMarginMode() requires a symbol argument".into()))));
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("modifyLeverageAndMarginMode".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.get("id").cloned().unwrap_or(Value::Null)));
m.insert("initial_margin_fraction".to_string(), self.parse_to_int((match ((Value::Int(10000)).as_f64(), (leverage).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })));
m.insert("margin_mode".to_string(), (if (marginMode.as_str() == Some("cross")) { Value::Int(0) } else { Value::Int(1) }));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_32 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_update_leverage(signer, __ws_arg_32).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
return self.public_post_send_tx(&[Value::Map(request)]).await;
Value::Null
}
pub async fn sign_and_cancel_order(&mut self, mut method: Value, 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!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), method).into()), Value::Str(" requires a symbol argument".into()))));
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, method.clone(), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
let mut clientOrderId: Option<String> = self.safe_string2_opt(paramsAccountIndex.clone(), Value::Str("client_order_index".into()), Value::Str("clientOrderId".into()), &[]);
let mut paramsOmitted: Value = self.omit(paramsAccountIndex, Value::from(vec![Value::Str("client_order_index".into()), Value::Str("clientOrderId".into())]), &[]);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsOmitted.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsOmitted.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.get("id").cloned().unwrap_or(Value::Null)));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if (clientOrderId.is_some()) {
signRaw.insert("order_index".into(), self.parse_to_int(clientOrderId.map(Value::from).unwrap_or(Value::Null)));
} else if (id != Value::Null) {
signRaw.insert("order_index".into(), self.parse_to_int(id.clone()));
} else {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), method).into()), Value::Str(" requires order id or client order id".into()))));
}
let __ws_arg_33 = self.extend(Value::Map(signRaw), &[paramsOmitted]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_cancel_order(signer, __ws_arg_33).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
return Value::from(vec![txType, txInfo]);
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
}));
let txTypetxInfoVariable: Vec<Value> = self.sign_and_cancel_order(Value::Str("cancelOrder".into()), id, &[symbol.clone(), params]).await.as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut market: Value = self.market(symbol);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_order(response, &[market]);
Value::Null
}
pub async fn sign_and_cancel_all_orders(&mut self, mut method: 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;
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, method.clone(), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, method, Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("time_in_force".to_string(), Value::Int(0));
m.insert("time".to_string(), Value::Int(0));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
if (symbol != Value::Null) {
let mut market: indexmap::IndexMap<String, Value> = self.market(symbol).as_map().cloned().unwrap_or_default();
signRaw.insert("cancel_all_market_index".into(), self.parse_to_int(market.get("id").cloned().unwrap_or(Value::Null)));
}
let __ws_arg_34 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_cancel_all_orders(signer, __ws_arg_34).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
return Value::from(vec![txType, txInfo]);
Value::Null
}
pub async fn cancel_all_orders(&mut self, 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 txTypetxInfoVariable: Vec<Value> = self.sign_and_cancel_all_orders(Value::Str("cancelAllOrdersWs".into()), &[symbol, params]).await.as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_orders(Value::from(vec![response]), &[]);
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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
if (timeout == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelAllOrdersAfter() requires a timeout argument".into()))));
}
let mut isScheduled: bool = timeout.as_f64() != Some(0.0);
if isScheduled && ((timeout.as_f64().unwrap_or(f64::NAN) < ((300000i64) as f64)) || (timeout.as_f64().unwrap_or(f64::NAN) > ((1296000000i64) as f64))) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" timeout should be between 5 minutes and 15 days, or 0 to cancel the timer.".into()))));
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("cancelOrder".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("cancelAllOrdersAfter".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut timeInForce: Value = Value::Int(2); let mut cancelTime: Value = Value::Int(0);
if isScheduled {
timeInForce = Value::Int(1);
cancelTime = self.sum(&[self.milliseconds(), timeout]);
}
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("time_in_force".to_string(), timeInForce);
m.insert("time".to_string(), cancelTime);
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_35 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_cancel_all_orders(signer, __ws_arg_35).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[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
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("direction".to_string(), Value::Int(1));
m
});
let __ws_arg_36 = self.extend(Value::Map(request), &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_36]).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
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("direction".to_string(), Value::Int(0));
m
});
let __ws_arg_37 = self.extend(Value::Map(request), &[params]);
return self.set_margin(symbol, amount, &[__ws_arg_37]).await;
Value::Null
}
pub async fn set_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
}));
if (self.markets.clone() == Value::Null) {
self.load_markets(&[]).await;
}
let apiKeyIndexparamsApiKeyIndexVariable: Vec<Value> = self.handle_api_key_index(params, Value::Str("setMargin".into()), Value::Str("apiKeyIndex".into()), Value::Str("api_key_index".into()), &[]).as_array().cloned().unwrap_or_default();
let mut apiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsApiKeyIndex: Value = apiKeyIndexparamsApiKeyIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut direction: Option<i64> = self.safe_integer_k(paramsApiKeyIndex.clone(), "direction", &[]).as_i64(); if (direction.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a direction parameter either 1 (increase margin) or 0 (decrease margin)".into()))));
}
if !(self.in_array(Value::from(direction), Value::from(vec![Value::Int(0), Value::Int(1)])).as_bool() == Some(true)) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a direction parameter either 1 (increase margin) or 0 (decrease margin)".into()))));
}
if (symbol == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" setMargin() requires a symbol argument".into()))));
}
let accountIndexparamsAccountIndexVariable: Vec<Value> = self.handle_account_index(paramsApiKeyIndex, Value::Str("setMargin".into()), Value::Str("accountIndex".into()), Value::Str("account_index".into()), &[]).await.as_array().cloned().unwrap_or_default();
let mut accountIndex: Value = accountIndexparamsAccountIndexVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsAccountIndex: Value = accountIndexparamsAccountIndexVariable.get(1).cloned().unwrap_or(Value::Null);
let mut strAccountIndex: Value = self.number_to_string(accountIndex.clone());
let mut strApiKeyIndex: Value = self.number_to_string(apiKeyIndex.clone());
let mut signer: Value = self.load_account(self.safe_integer_k(self.options.clone(), "chainId", &[]), self.get_lighter_private_key(strAccountIndex.clone(), strApiKeyIndex.clone()), strApiKeyIndex, strAccountIndex, &[paramsAccountIndex.clone()]).await;
let mut market: Value = self.market(symbol);
let mut nonce: Value = self.fetch_nonce(accountIndex.clone(), apiKeyIndex.clone(), &[paramsAccountIndex.clone()]).await;
let mut signRaw: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("market_index".to_string(), self.parse_to_int(market.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null)));
m.insert("usdc_amount".to_string(), self.parse_to_int(crate::precise::Precise::stringMul(&self.pow(Value::Str("10".into()), Value::Str("6".into())).map(Value::from).unwrap_or(Value::Null), &self.currency_to_precision(Value::Str("USDC".into()), amount, &[]))));
m.insert("direction".to_string(), Value::from(direction));
m.insert("nonce".to_string(), nonce);
m.insert("api_key_index".to_string(), apiKeyIndex);
m.insert("account_index".to_string(), accountIndex);
m
});
let __ws_arg_38 = self.extend(Value::Map(signRaw), &[paramsAccountIndex]);
let txTypetxInfoVariable: Vec<Value> = self.lighter_sign_update_margin(signer, __ws_arg_38).as_array().cloned().unwrap_or_default();
let mut txType: Value = txTypetxInfoVariable.get(0).cloned().unwrap_or(Value::Null);
let mut txInfo: Value = txTypetxInfoVariable.get(1).cloned().unwrap_or(Value::Null);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("tx_type".to_string(), txType);
m.insert("tx_info".to_string(), txInfo);
m
});
let mut response: Value = self.public_post_send_tx(&[Value::Map(request)]).await;
return self.parse_margin_modification(response, &[market]);
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);
let mut timestamp: Option<i64> = self.safe_integer_k(data.clone(), "predicted_execution_time_ms", &[]).as_i64();
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("info".to_string(), data);
m.insert("symbol".to_string(), self.safe_string_k(market, "symbol", &[]));
m.insert("type".to_string(), Value::Null);
m.insert("marginMode".to_string(), Value::Null);
m.insert("amount".to_string(), Value::Null);
m.insert("total".to_string(), Value::Null);
m.insert("code".to_string(), Value::Str("USDC".into()));
m.insert("status".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m
});
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 url: Value = Value::Null;
if (apiName.as_str() == Some("root")) {
let mut baseApiUrl: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), Value::Str("public".into()), &[]);
if (baseApiUrl.is_none()) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
url = self.implode_hostname(baseApiUrl.map(Value::from).unwrap_or(Value::Null));
} else {
let mut baseApiUrl2: Option<String> = self.safe_string_opt(self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null), apiName.clone(), &[]);
if (baseApiUrl2.is_none()) {
panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" sign() has no API URL for this endpoint".into()))));
}
url = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.implode_hostname(baseApiUrl2.map(Value::from).unwrap_or(Value::Null)), Value::Str("/api/".into())).into()), self.version.clone()).into()), Value::Str("/".into())).into()), path).into());
}
let mut authHeaders: Value = Value::Null;
if (apiName.as_str() == Some("private")) {
authHeaders = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Authorization".to_string(), self.create_auth(&[params.clone()]).map(Value::from).unwrap_or(Value::Null));
m
});
}
if ((Value::Array(params.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).len() as i64) as f64) > ((0i64) as f64) {
if (method.as_str() == Some("POST")) {
let mut multipartHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("Content-Type".to_string(), Value::Str("multipart/form-data".into()));
m
});
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), params.clone());
m.insert("headers".to_string(), Value::Map(multipartHeaders));
m
});
}
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.rawencode(params, &[])).into())).into());
}
if (apiName.as_str() == Some("private")) {
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("url".to_string(), url.clone());
m.insert("method".to_string(), method.clone());
m.insert("body".to_string(), Value::Null);
m.insert("headers".to_string(), authHeaders);
m
});
}
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(), Value::Null);
m.insert("headers".to_string(), Value::Null);
m
});
Value::Null
}
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 codeError: Option<String> = self.safe_string_k_opt(response.clone(), "code", &[]);
let mut message: Option<String> = self.safe_string_k_opt(response, "message", &[]);
if (codeError.is_some()) && (codeError.as_deref() != Some("0")) && (codeError.as_deref() != Some("200")) {
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), message.map(Value::from).unwrap_or(Value::Null), feedback.clone());
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), codeError.map(Value::from).unwrap_or(Value::Null), feedback.clone());
panic!("{}", crate::exchange_errors::exchange_error(feedback));
}
return Value::Null;
Value::Null
}
}