// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;
pub struct PredictfunCore {
pub exchange: crate::prediction_exchange::PredictionExchange,
}
impl PredictfunCore {
pub fn new(config: Option<crate::Value>) -> Self {
let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::new(config) };
s.init();
s
}
pub fn init(&mut self) {
let described = PredictfunCore::describe(self);
self.initialize_properties(described);
// compatibility for sandbox/testnet options in userConfig
let user_config = self.userConfig.clone();
<Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
}
/// Compatibility no-op. The old pointer-based dispatch needed a post-move
/// `bind()`; static trait dispatch (review #1) needs no binding, so this
/// just exists so callers that still call it keep compiling.
#[inline]
pub fn bind(&mut self) {}
}
impl crate::exchange::DerivedExchange for PredictfunCore {
fn nonce(&self, ) -> crate::Value {
// Forward to the inherent method on PredictfunCore.
PredictfunCore::nonce(self, )
}
fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PredictfunCore.
PredictfunCore::parse_prediction_trade(self, trade, &[market])
}
fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PredictfunCore.
PredictfunCore::parse_prediction_order(self, order, &[market])
}
fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
// Forward to the inherent method on PredictfunCore.
PredictfunCore::parse_prediction_position(self, position, &[market])
}
fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
// Forward to the inherent method on PredictfunCore.
PredictfunCore::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 {
// Forward to the inherent method on PredictfunCore.
#[allow(invalid_reference_casting)]
let me = unsafe { &mut *(self as *const PredictfunCore as *mut PredictfunCore) };
PredictfunCore::handle_errors(me, code, reason, url, method, headers, body, response, request_headers, request_body)
}
}
impl crate::exchange_generated::ExchangeBase for PredictfunCore {
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 {
"approve" => self.approve(&args[..]).await,
"authenticate" => self.authenticate(&args[..]).await,
"cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"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,
"fetch_closed_orders" => self.fetch_closed_orders(&args[..]).await,
"fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_events" => self.fetch_events(&args[..]).await,
"fetch_markets" => self.fetch_markets(&args[..]).await,
"fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
"fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
"fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_orders_helper" => self.fetch_orders_helper(&args[..]).await,
"fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_positions" => self.fetch_positions(&args[..]).await,
"fetch_raw_topics_by_queries" => self.fetch_raw_topics_by_queries(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null),
args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
"handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
"nonce" => self.nonce(),
"order_book_message_hashes" => self.order_book_message_hashes(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"outcome_for_token" => self.outcome_for_token(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"outcomes_by_market_id" => self.outcomes_by_market_id(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"parse_topic_market" => self.parse_topic_market(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"parse_wallet_event_order" => self.parse_wallet_event_order(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"parse_wallet_event_trade" => self.parse_wallet_event_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"pong" => self.pong(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
"request_id" => self.request_id(),
"sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"sign_evm_transaction" => self.sign_evm_transaction(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
"sign_predictfun_order" => self.sign_predictfun_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).map(|v| v.is_truthy()).unwrap_or(false), args.get(2).map(|v| v.is_truthy()).unwrap_or(false)),
"un_watch_my_trades" => self.un_watch_my_trades(&args[..]).await,
"un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"un_watch_orders" => self.un_watch_orders(&args[..]).await,
"un_watch_wallet_events" => self.un_watch_wallet_events(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"wallet_event_message_hashes" => self.wallet_event_message_hashes(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
"wallet_event_outcome" => self.wallet_event_outcome(args.get(0).cloned().unwrap_or(crate::Value::Null)),
"wallet_events_topic" => self.wallet_events_topic().await,
"watch_my_trades" => self.watch_my_trades(&args[..]).await,
"watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
"watch_orders" => self.watch_orders(&args[..]).await,
"watch_wallet_events" => self.watch_wallet_events(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
// Prediction Core: fall through to prediction base methods (then Exchange base).
_ => self.call_dynamic_prediction_base(method, args).await,
}
})
}
}
impl crate::prediction_exchange_generated::PredictionBase for PredictfunCore {
fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}
impl std::ops::Deref for PredictfunCore {
type Target = crate::exchange::Exchange;
fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}
impl std::ops::DerefMut for PredictfunCore {
fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}
impl PredictfunCore {
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("predictfun".into()));
m.insert("name".to_string(), Value::Str("predict.fun".into()));
m.insert("countries".to_string(), Value::from(vec![]));
m.insert("rateLimit".to_string(), Value::Int(250));
m.insert("version".to_string(), Value::Str("v1".into()));
m.insert("certified".to_string(), Value::Bool(false));
m.insert("pro".to_string(), Value::Bool(true));
m.insert("has".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CORS".to_string(), Value::Null);
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("approve".to_string(), Value::Bool(true));
m.insert("cancelAllOrders".to_string(), Value::Bool(false));
m.insert("cancelOrder".to_string(), Value::Bool(true));
m.insert("cancelOrders".to_string(), Value::Bool(true));
m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(false));
m.insert("createOrder".to_string(), Value::Bool(true));
m.insert("createOrders".to_string(), Value::Bool(false));
m.insert("fetchBalance".to_string(), Value::Bool(false));
m.insert("fetchClosedOrders".to_string(), Value::Bool(true));
m.insert("fetchCurrencies".to_string(), Value::Bool(false));
m.insert("fetchDeposits".to_string(), Value::Bool(false));
m.insert("fetchEvent".to_string(), Value::Bool(true));
m.insert("fetchEvents".to_string(), Value::Bool(true));
m.insert("fetchLedger".to_string(), Value::Bool(false));
m.insert("fetchMarkets".to_string(), Value::Bool(true));
m.insert("fetchMyTrades".to_string(), Value::Bool(true));
m.insert("fetchOHLCV".to_string(), Value::Bool(false));
m.insert("fetchOpenInterest".to_string(), Value::Bool(false));
m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
m.insert("fetchOrder".to_string(), Value::Bool(true));
m.insert("fetchOrderBook".to_string(), Value::Bool(true));
m.insert("fetchOrders".to_string(), Value::Bool(false));
m.insert("fetchOrderTrades".to_string(), Value::Bool(false));
m.insert("fetchPosition".to_string(), Value::Bool(true));
m.insert("fetchPositions".to_string(), Value::Bool(true));
m.insert("fetchStatus".to_string(), Value::Bool(false));
m.insert("fetchTicker".to_string(), Value::Bool(true));
m.insert("fetchTickers".to_string(), Value::Bool(false));
m.insert("fetchTime".to_string(), Value::Bool(false));
m.insert("fetchTrades".to_string(), Value::Bool(true));
m.insert("fetchTradingFee".to_string(), Value::Bool(false));
m.insert("fetchWithdrawals".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("unWatchMyTrades".to_string(), Value::Bool(true));
m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
m.insert("unWatchOrders".to_string(), Value::Bool(true));
m.insert("watchMyTrades".to_string(), Value::Bool(true));
m.insert("watchOrderBook".to_string(), Value::Bool(true));
m.insert("watchOrders".to_string(), Value::Bool(true));
m.insert("watchTicker".to_string(), Value::Bool(false));
m.insert("watchTrades".to_string(), Value::Bool(false));
m
}));
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/9fb5dccf-faa3-4b5a-b144-81d6994bc598".into()));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("predictfun".to_string(), Value::Str("https://api.predict.fun".into()));
m.insert("ws".to_string(), Value::Str("wss://ws.predict.fun/ws".into()));
m
}));
m.insert("test".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("predictfun".to_string(), Value::Str("https://api-testnet.predict.fun".into()));
m
}));
m.insert("www".to_string(), Value::Str("https://predict.fun".into()));
m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.predict.fun".into())]));
m
}));
m.insert("api".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("predictfun".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("v1/auth/message".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/categories".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/categories/{slug}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/tags".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}/stats".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}/last-sale".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}/orderbook".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}/timeseries".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/markets/{id}/timeseries/latest".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders/{hash}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders/matches".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/account".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/account/activity".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/positions/{address}".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/search".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("v1/auth".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders/remove".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/orders/remove-by-hash".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/account/referral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/oauth/finalize".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/oauth/orders".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/oauth/orders/create".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/oauth/orders/cancel".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m.insert("v1/oauth/positions".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("cost".to_string(), Value::Int(1));
m
}));
m
}));
m
}));
m
}));
m.insert("requiredCredentials".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("apiKey".to_string(), Value::Bool(true));
m.insert("secret".to_string(), Value::Bool(false));
m.insert("walletAddress".to_string(), Value::Bool(false));
m.insert("privateKey".to_string(), Value::Bool(false));
m
}));
m.insert("fees".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("trading".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("maker".to_string(), Value::Int(0));
m.insert("taker".to_string(), Value::Float(0.02));
m
}));
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("unauthorized".to_string(), Value::Str("AuthenticationError".into()));
m.insert("bad_request".to_string(), Value::Str("BadRequest".into()));
m.insert("not_found".to_string(), Value::Str("BadRequest".into()));
m.insert("create_order_hash_mismatch".to_string(), Value::Str("InvalidOrder".into()));
m.insert("create_order_insufficient_collateral_allowance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("create_order_insufficient_shares_allowance".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("create_order_min_order_value_not_met".to_string(), Value::Str("InvalidOrder".into()));
m.insert("create_order_price_out_of_range".to_string(), Value::Str("InvalidOrder".into()));
m.insert("create_order_market_not_trading".to_string(), Value::Str("MarketClosed".into()));
m
}));
m.insert("broad".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("do not belong to".to_string(), Value::Str("OrderNotFound".into()));
m.insert("order hash must be a".to_string(), Value::Str("BadRequest".into()));
m.insert("Orderbook not found".to_string(), Value::Str("BadSymbol".into()));
m.insert("market not found".to_string(), Value::Str("BadSymbol".into()));
m.insert("not currently trading".to_string(), Value::Str("MarketClosed".into()));
m.insert("allowance is less than".to_string(), Value::Str("InsufficientFunds".into()));
m.insert("price per share must be".to_string(), Value::Str("InvalidOrder".into()));
m.insert("must have a value of at least".to_string(), Value::Str("InvalidOrder".into()));
m
}));
m
}));
m.insert("options".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("allowUnscopedFetchEvents".to_string(), Value::Bool(true));
m.insert("maxFetchEventsResults".to_string(), Value::Int(100));
m.insert("tokenExpiresIn".to_string(), Value::Int(86400000));
m.insert("marketBuyPrice".to_string(), Value::Float(0.99));
m.insert("marketSellPrice".to_string(), Value::Float(0.01));
m.insert("warnOnMarketOrderWithoutPrice".to_string(), Value::Bool(true));
m.insert("chainId".to_string(), Value::Int(56));
m.insert("rpcUrls".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Str("https://bsc-dataseed.bnbchain.org/".into()));
m.insert("97".to_string(), Value::Str("https://bsc-testnet-dataseed.bnbchain.org/".into()));
m
}));
m.insert("collateral".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Str("0x55d398326f99059fF775485246999027B3197955".into()));
m.insert("97".to_string(), Value::Str("0xB32171ecD878607FFc4F8FC0bCcE6852BB3149E0".into()));
m
}));
m.insert("defaultExpiration".to_string(), Value::Int(3600));
m.insert("marketOrderExpiration".to_string(), Value::Int(300));
m.insert("exchanges".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CTF_EXCHANGE".to_string(), Value::Str("0x8BC070BEdAB741406F4B1Eb65A72bee27894B689".into()));
m.insert("NEG_RISK_CTF_EXCHANGE".to_string(), Value::Str("0x365fb81bd4A24D6303cd2F19c349dE6894D8d58A".into()));
m.insert("YIELD_BEARING_CTF_EXCHANGE".to_string(), Value::Str("0x6bEb5a40C032AFc305961162d8204CDA16DECFa5".into()));
m.insert("YIELD_BEARING_NEG_RISK_CTF_EXCHANGE".to_string(), Value::Str("0x8A289d458f5a134bA40015085A8F50Ffb681B41d".into()));
m
}));
m.insert("97".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CTF_EXCHANGE".to_string(), Value::Str("0x2A6413639BD3d73a20ed8C95F634Ce198ABbd2d7".into()));
m.insert("NEG_RISK_CTF_EXCHANGE".to_string(), Value::Str("0xd690b2bd441bE36431F6F6639D7Ad351e7B29680".into()));
m.insert("YIELD_BEARING_CTF_EXCHANGE".to_string(), Value::Str("0x8a6B4Fa700A1e310b106E7a48bAFa29111f66e89".into()));
m.insert("YIELD_BEARING_NEG_RISK_CTF_EXCHANGE".to_string(), Value::Str("0x95D5113bc50eD201e319101bbca3e0E250662fCC".into()));
m
}));
m
}));
m.insert("conditionalTokens".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CONDITIONAL_TOKENS".to_string(), Value::Str("0x22DA1810B194ca018378464a58f6Ac2B10C9d244".into()));
m.insert("NEG_RISK_CONDITIONAL_TOKENS".to_string(), Value::Str("0x22DA1810B194ca018378464a58f6Ac2B10C9d244".into()));
m.insert("YIELD_BEARING_CONDITIONAL_TOKENS".to_string(), Value::Str("0x9400F8Ad57e9e0F352345935d6D3175975eb1d9F".into()));
m.insert("YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS".to_string(), Value::Str("0xF64b0b318AAf83BD9071110af24D24445719A07F".into()));
m
}));
m.insert("97".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("CONDITIONAL_TOKENS".to_string(), Value::Str("0x2827AAef52D71910E8FBad2FfeBC1B6C2DA37743".into()));
m.insert("NEG_RISK_CONDITIONAL_TOKENS".to_string(), Value::Str("0x2827AAef52D71910E8FBad2FfeBC1B6C2DA37743".into()));
m.insert("YIELD_BEARING_CONDITIONAL_TOKENS".to_string(), Value::Str("0x38BF1cbD66d174bb5F3037d7068E708861D68D7f".into()));
m.insert("YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS".to_string(), Value::Str("0x26e865CbaAe99b62fbF9D18B55c25B5E079A93D5".into()));
m
}));
m
}));
m.insert("adapters".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("56".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("NEG_RISK_ADAPTER".to_string(), Value::Str("0xc3Cf7c252f65E0d8D88537dF96569AE94a7F1A6E".into()));
m.insert("YIELD_BEARING_NEG_RISK_ADAPTER".to_string(), Value::Str("0x41dCe1A4B8FB5e6327701750aF6231B7CD0B2A40".into()));
m
}));
m.insert("97".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("NEG_RISK_ADAPTER".to_string(), Value::Str("0x285c1B939380B130D7EBd09467b93faD4BA623Ed".into()));
m.insert("YIELD_BEARING_NEG_RISK_ADAPTER".to_string(), Value::Str("0xb74aea04bdeBE912Aa425bC9173F9668e6f11F99".into()));
m
}));
m
}));
m.insert("createOrder".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("taker".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
m
}));
m
}));
m
})]);
Value::Null
}
/*
* @method
* @name predictfun#fetchMarkets
* @description Retrieves all outcome markets from outcomeMeta.
* Each binary outcome becomes one CCXT prediction market with two outcomes: YES and NO.
* @see https://dev.predict.fun/get-categories-25326910e0
* @see https://dev.predict.fun/search-categories-and-markets-27399810e0
* @param {object} [params] extra parameters
* @param {string} [params.query] a single search term — routes the call through the search endpoint and returns only the matching markets
* @param {string[]} [params.queries] multiple search terms (alternative to query), the results are merged and deduplicated
* @param {string[]} [params.tags] predictfun tag ids
* @param {string} [params.slug] direct lookup by event slug
* @param {int} [params.limit] the maximum number of events to collect markets from
* @returns {Market[]} array of market structures
*/
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 events: Value = self.fetch_events(&[params]).await;
let mut eventsLength: f64 = ((events.len() as i64) as f64);
let mut markets: Vec<Value> = Vec::new();
{
let mut ei: Value = Value::Int(0);
let mut __for_first_1459: bool = true;
while { if !__for_first_1459 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1459 = false; ei.as_f64().unwrap_or(f64::NAN) < eventsLength } {
let mut eventMarkets: Vec<Value> = self.safe_list(events.as_array().and_then(|__arr| match &ei { 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("markets".into()), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1458: bool = true;
while { if !__for_first_1458 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1458 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
markets.push(eventMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
}
}
}
}
return Value::from(markets);
Value::Null
}
/*
* @method
* @name predictfun#fetchEvent
* @description fetches a single prediction-market event (market topic)
* @see https://dev.predict.fun/get-category-by-slug-25326911e0
* @param {string} id event slug
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.slug] event slug, overrides the id argument when both are given
* @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// the id argument is the event slug, per the base fetchEvent (id) contract - params.slug
// overrides it so a caller can pass the slug the same way fetchEvents () takes it
let mut slug: Value = self.safe_string_k(params.clone(), "slug", &[id.clone()]);
if (slug == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchEvent() requires the \"id\" argument or the \"slug\" parameter".into()))));
}
let __ws_arg_0 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug);
m
}), &[params]);
let mut events: Value = self.fetch_events(&[__ws_arg_0]).await;
return self.safe_dict(events, Value::Int(0), &[]);
Value::Null
}
/*
* @method
* @name predictfun#fetchEvents
* @description fetches prediction-market events (market topics); the call must be scoped by query/queries/tags, eventId, or an l1Category/l2Category listing filter
* @see https://dev.predict.fun/get-categories-25326910e0
* @see https://dev.predict.fun/search-categories-and-markets-27399810e0
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.query] a single search term — routes the call through GET /v1/search instead of the categories listing
* @param {string[]} [params.queries] multiple search terms (alternative to query), searched one by one and merged deduplicated by event slug
* @param {string[]} [params.tags] predictfun tag ids
* @param {string} [params.slug] direct lookup by event slug
* @param {int} [params.limit] the maximum number of events to return, capped at 25 per search term when searching
* @param {string} [params.sort] 'VOLUME_24H_DESC' | 'VOLUME_ALL_DESC' | 'PUBLISHED_AT_ASC' | 'PUBLISHED_AT_DESC'
* @param {string} [params.status] 'OPEN' | 'RESOLVED'
* @param {string} [params.marketVariant] predictfun enum value ('SPORTS_MATCH', 'CRYPTO_UP_DOWN' etc.)
* @returns {object[]} a list of [prediction event structures](https://docs.ccxt.com/#/?id=prediction-event-structure)
*/
pub async fn fetch_events(&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 allowUnscopedFetchEvents: bool = self.safe_bool_k_opt(self.options.clone(), "allowUnscopedFetchEvents", &[Value::Bool(false)]).unwrap_or(false);
if !(allowUnscopedFetchEvents) {
self.require_event_query(&[params.clone()]);
}
let mut queries: Value = self.parse_search_queries(&[params.clone()]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut paramsValue: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
// keys dropped before the client-side pass; the categories listing also drops its limit
let mut postOmitKeys: Vec<Value> = vec![Value::Str("tags".into())];
let mut userLimit: Value = self.safe_integer_k(paramsValue.clone(), "limit", &[]);
let mut fetchCap: Value = self.safe_integer_k(self.options.clone(), "maxFetchEventsResults", &[Value::Int(100)]);
if (userLimit != Value::Null) {
fetchCap = userLimit;
}
let mut slug: Option<String> = self.safe_string2_opt(paramsValue.clone(), Value::Str("slug".into()), Value::Str("eventId".into()), &[]);
let mut rest: Value = self.omit(paramsValue.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("tags".into()), Value::Str("marketVariant".into())]), &[]);
if (self.markets.clone() == Value::Null) {
{ let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
}
let mut rawTopics: Value = Value::from(vec![]);
if (slug.is_some()) {
let __ws_arg_1 = self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[rest]);
let mut response: Value = self.predictfun_get_v1_categories_slug(&[__ws_arg_1]).await;
let mut data: Value = self.safe_dict_k(response, "data", &[]);
rawTopics = Value::from(vec![data.clone()]);
} else if queriesLength > ((0i64) as f64) {
// a query/queries scope is answered by the dedicated search endpoint — the categories
// listing has no text filter, so paging it and matching client-side would both miss
// the venue's semantic matches and cost one request per page
rawTopics = self.fetch_raw_topics_by_queries(queries.clone(), &[paramsValue.clone()]).await;
} else {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let mut tags: Value = self.safe_list_k(paramsValue.clone(), "tags", &[Value::from(vec![])]);
if ((tags.len() as i64) as f64) > ((0i64) as f64) {
request.insert("tagIds".into(), join(&tags, &Value::Str(",".into())));
}
postOmitKeys.push(Value::Str("limit".into()));
let mut paramsCategories: Value = self.omit(paramsValue.clone(), Value::from(vec![Value::Str("limit".into()), Value::Str("tags".into())]), &[]);
let mut extendedRequest: Value = self.extend(Value::Map(request), &[paramsCategories]);
let mut rawTopicsResponse: Value = self.predictfun_get_v1_categories(&[extendedRequest.clone()]).await;
//
// {
// "cursor": "NDA1MDA0",
// "data": [
// {
// "createdAt": "2026-08-26T14:00:02.000Z",
// "description": "This market will resolve to \"Up\" if the ETH/USDT price at the end of the time range specified in the title is greater than the price at the beginning of that range.\r\n\r\nIt will resolve to \"Down\" if the ETH/USDT price at the end of the time range is lower than the price at the beginning of that range.\r\n\r\nIf the two prices are exactly equal, the market will resolve 50-50.\r\n\r\nThe primary resolution source for this market is Chainlink, specifically the ETH/USDT data stream available at https://data.chain.link/streams/eth-usdt-topofbook-datalink?timeframe=1d&chart=candlestick.\r\n\r\nTo verify the final price, use the close price of the 5m candlestick just before the market's end time. For example, for a market running from 1:00 to 1:15 PM ET or 1:10 to 1:15 PM ET, use the close price of the 1:10 PM candlestick as the final price.\r\n\r\nThe Chainlink stream uses the mid-price, which is calculated as the average price between the bid and ask prices from Binance's Top of Book, converted into the quote currency.\r\n\r\nThis market is based solely on the price reported by the Chainlink ETH/USDT data stream, not on other sources or spot markets.\r\n\r\nIf Chainlink data is unavailable or otherwise unusable for resolution, the market will resolve based on a consensus of reliable sources.\n2026-08-27T14:00:00Z",
// "endsAt": "2026-08-27T14:15:00.000Z",
// "id": 405022,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isNegRisk": false,
// "isVisible": true,
// "isYieldBearing": false,
// "marketVariant": "CRYPTO_UP_DOWN",
// "markets": [
// {
// "boostEndsAt": "2026-08-27T14:15:00.000Z",
// "boostStartsAt": "2026-08-27T14:00:00.000Z",
// "categorySlug": "eth-updown-15m-1787839200",
// "conditionId": "0xa8e9c348c299989329debd86aaef81a1c4880d42c3954a684bdc731f7a113487",
// "createdAt": "2026-08-26T14:00:02.000Z",
// "decimalPrecision": 2,
// "description": "This market will resolve to \"Up\" if the ETH/USDT price at the end of the time range specified in the title is greater than the price at the beginning of that range.\r\n\r\nIt will resolve to \"Down\" if the ETH/USDT price at the end of the time range is lower than the price at the beginning of that range.\r\n\r\nIf the two prices are exactly equal, the market will resolve 50-50.\r\n\r\nThe primary resolution source for this market is Chainlink, specifically the ETH/USDT data stream available at https://data.chain.link/streams/eth-usdt-topofbook-datalink?timeframe=1d&chart=candlestick.\r\n\r\nTo verify the final price, use the close price of the 5m candlestick just before the market's end time. For example, for a market running from 1:00 to 1:15 PM ET or 1:10 to 1:15 PM ET, use the close price of the 1:10 PM candlestick as the final price.\r\n\r\nThe Chainlink stream uses the mid-price, which is calculated as the average price between the bid and ask prices from Binance's Top of Book, converted into the quote currency.\r\n\r\nThis market is based solely on the price reported by the Chainlink ETH/USDT data stream, not on other sources or spot markets.\r\n\r\nIf Chainlink data is unavailable or otherwise unusable for resolution, the market will resolve based on a consensus of reliable sources.",
// "feeRateBps": 200,
// "id": 1739803,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isBoosted": false,
// "isNegRisk": false,
// "isVisible": true,
// "isYieldBearing": false,
// "kalshiMarketTicker": null,
// "marketType": null,
// "marketVariant": "CRYPTO_UP_DOWN",
// "oracleQuestionId": "0x6ab55f25f108508e7c6cc9bb22e3304d3fcecd0771d741fdf6d67e6b7ab9af2c",
// "outcomes": [
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 1,
// "name": "Up",
// "onChainId": "63015212288887519605689521802215931005858239156918107575780791658588345185817",
// "status": null,
// "team": null,
// "variantData": null
// },
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 2,
// "name": "Down",
// "onChainId": "111913554301217491431600756326792444318464112865057816486042507140136158411642",
// "status": null,
// "team": null,
// "variantData": null
// }
// ],
// "polymarketConditionIds": [],
// "question": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "questionIndex": null,
// "resolution": null,
// "resolverAddress": "0x77620FAb2969dF2D5696F1f081940E416Cf17cA5",
// "rewards": {
// "current": null,
// "schedule": [
// {
// "endsAt": "2026-08-27T14:15:00.000Z",
// "hourlyRate": 3000,
// "startsAt": "2026-08-27T14:00:00.000Z"
// }
// ]
// },
// "shareThreshold": 100,
// "spreadThreshold": 0.06,
// "status": "REGISTERED",
// "team": null,
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "tradingStatus": "OPEN",
// "variantData": {
// "endPrice": null,
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT",
// "startPrice": null,
// "type": "CRYPTO_UP_DOWN"
// }
// }
// ],
// "negRiskOnChainId": null,
// "parentSlug": null,
// "publishedAt": "2026-08-26T14:00:20.780Z",
// "resolutionProvider": "CHAINLINK",
// "shortTitle": "ETH Up or Down 15m",
// "slug": "eth-updown-15m-1787839200",
// "startsAt": "2026-08-27T14:00:00.000Z",
// "stats": null,
// "status": "OPEN",
// "tags": [
// {
// "id": "2",
// "level": 1,
// "makerRebateBps": 0,
// "name": "Crypto",
// "parentId": null
// },
// {
// "id": "7",
// "level": null,
// "makerRebateBps": 0,
// "name": "ETH",
// "parentId": null
// },
// {
// "id": "111",
// "level": 2,
// "makerRebateBps": 2500,
// "name": "Up/Down",
// "parentId": "2"
// },
// {
// "id": "146",
// "level": 2,
// "makerRebateBps": 0,
// "name": "15 Min",
// "parentId": "2"
// }
// ],
// "teams": null,
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "variantData": {
// "endPrice": null,
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT",
// "startPrice": null,
// "type": "CRYPTO_UP_DOWN"
// },
// "variantDetails": {
// "crypto": {
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT"
// },
// "upDown": {
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT"
// }
// }
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(rawTopicsResponse.clone(), "data", &[Value::from(vec![])]);
rawTopics = self.array_concat(rawTopics.clone(), data.clone());
let mut topicsLength: i64 = rawTopics.len() as i64;
while (topicsLength as f64) < fetchCap.as_f64().unwrap_or(f64::NAN) {
let mut nextPageToken: Option<String> = self.safe_string_k_opt(rawTopicsResponse.clone(), "cursor", &[]);
if (nextPageToken.is_none()) {
break;
}
if let Value::Dict(__rda) = &mut extendedRequest { std::sync::Arc::make_mut(__rda).insert("after".to_string(), nextPageToken.map(Value::from).unwrap_or(Value::Null)); }
rawTopicsResponse = self.predictfun_get_v1_categories(&[extendedRequest.clone()]).await;
data = self.safe_list_k(rawTopicsResponse.clone(), "data", &[Value::from(vec![])]);
rawTopics = self.array_concat(rawTopics.clone(), data.clone());
topicsLength = rawTopics.len() as i64;
}
if (topicsLength as f64) > fetchCap.as_f64().unwrap_or(f64::NAN) {
rawTopics = self.array_slice(rawTopics.clone(), Value::Int(0), &[fetchCap]);
}
}
let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
let mut result: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1461: bool = true;
while { if !__for_first_1461 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1461 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
let mut parsedEvent: Value = self.parse_event(rawTopics.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));
result.push(parsedEvent.clone());
let mut parsedMarkets: Vec<Value> = self.safe_list_k(parsedEvent, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut parsedMarketsLength: f64 = ((parsedMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1460: bool = true;
while { if !__for_first_1460 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1460 = false; mi.as_f64().unwrap_or(f64::NAN) < parsedMarketsLength } {
let mut m: Value = parsedMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
// prediction market rows are keyed by the unified 'market' handle
let mut handle: Option<String> = self.safe_string_k_opt(m.clone(), "market", &[]);
if (handle.is_some()) {
if let Value::Dict(__d) = &mut self.markets { std::sync::Arc::make_mut(__d).insert(handle.as_deref().unwrap_or("null").to_string(), m.clone()); }
}
}
}
}
}
self.populate_outcomes();
// scoping already happened server-side: the tag filter needs an event-level tags field
// predictfun topics lack, and the query filter would drop semantic-search matches whose
// title uses different words than the query
let mut postParams: Value = self.omit(paramsValue.clone(), Value::from(postOmitKeys), &[]);
// status is documented as the venue enum ('OPEN' / 'RESOLVED') but the shared client-side
// pass speaks the unified vocabulary — translate so it doesn't discard every row it matched
let mut rawStatus: Option<String> = self.safe_string_k(paramsValue, "status", &[]).as_str().map(str::to_owned);
if (rawStatus.as_deref() == Some("OPEN")) {
postParams = self.extend(postParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("active".into()));
m
})]);
} else if (rawStatus.as_deref() == Some("RESOLVED")) {
postParams = self.extend(postParams.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("closed".into()));
m
})]);
}
return self.apply_event_fetch_params(Value::from(result), &[postParams, queries]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#fetchRawTopicsByQueries
* @description searches categories and markets for every query term and returns the raw market topics, deduplicated by slug
* @see https://dev.predict.fun/search-categories-and-markets-27399810e0
* @param {string[]} queries the search terms
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.status] anything other than 'active' asks the venue to include resolved rows
* @returns {object[]} an array of raw market topics, each with a nested markets list
*/
pub async fn fetch_raw_topics_by_queries(&mut self, mut queries: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
// always ask for the venue's maximum page size - this is the per-type page size of the
// search endpoint (it caps at 25 and defaults to 10), not the caller's event limit, which
// applyEventFetchParams () applies to the parsed events afterwards
let mut limit: Value = Value::Int(25);
// resolved rows are excluded unless asked for — the unified status filter drives that
let mut status: Option<String> = self.safe_string_k(params.clone(), "status", &[]).as_str().map(str::to_owned);
let mut includeResolved: String = "false".to_string();
if (status.is_some()) && (status.as_deref() != Some("active")) && (status.as_deref() != Some("OPEN")) {
includeResolved = "true".to_string();
}
// marketVariant/tags/sort are categories-listing filters the search endpoint does not accept
let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("status".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("tags".into()), Value::Str("marketVariant".into())]), &[]);
let mut queriesLength: f64 = ((queries.len() as i64) as f64);
let mut result: Vec<Value> = Vec::new();
// the venue answers every term separately and the same category comes back for each term
// that matches it - emit it once, otherwise applyEventFetchParams (), which slices to the
// caller's limit after filtering, spends a slot on a repeat instead of a distinct event
let mut seenSlugs: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
// market rows whose category row did not come back, bucketed by the slug they carry
let mut orphanMarkets: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut orphanSlugs: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1464: bool = true;
while { if !__for_first_1464 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1464 = false; i.as_f64().unwrap_or(f64::NAN) < queriesLength } {
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("query".to_string(), self.safe_string(queries.clone(), i.clone(), &[Value::Str("".into())]));
m.insert("limit".to_string(), limit.clone());
m.insert("includeResolved".to_string(), Value::from(includeResolved.clone()));
m
});
let __ws_arg_2 = self.extend(Value::Map(request), &[rest.clone()]);
let mut response: Value = self.predictfun_get_v1_search(&[__ws_arg_2]).await;
//
// {
// "data": {
// "categories": [
// {
// "id": 405022,
// "slug": "eth-updown-15m-1787839200",
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "description": "This market will resolve to \"Up\" ...",
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isNegRisk": false,
// "isYieldBearing": false,
// "marketVariant": "CRYPTO_UP_DOWN",
// "variantData": null,
// "createdAt": "2026-08-26T14:00:02.000Z",
// "publishedAt": "2026-08-26T14:00:20.780Z",
// "startsAt": "2026-08-27T14:00:00.000Z",
// "endsAt": "2026-08-27T14:15:00.000Z",
// "status": "OPEN",
// "isVisible": true,
// "tags": [ { "id": "2", "name": "Crypto" } ],
// "markets": [ { "id": 1739803, "categorySlug": "eth-updown-15m-1787839200", ... } ]
// }
// ],
// "markets": [
// {
// "id": 1739803,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "question": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "description": "This market will resolve to \"Up\" ...",
// "tradingStatus": "OPEN",
// "status": "REGISTERED",
// "isVisible": true,
// "isNegRisk": false,
// "isYieldBearing": false,
// "feeRateBps": 200,
// "conditionId": "0xa8e9c348c299989329debd86aaef81a1c4880d42c3954a684bdc731f7a113487",
// "outcomes": [ { "name": "Up", "indexSet": 1, "onChainId": "630152...", "status": null } ],
// "isBoosted": false,
// "categorySlug": "eth-updown-15m-1787839200",
// "marketVariant": "CRYPTO_UP_DOWN"
// }
// ]
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut categories: Value = self.safe_list_k(data.clone(), "categories", &[Value::from(vec![])]);
let mut categoriesLength: f64 = ((categories.len() as i64) as f64);
{
let mut ci: Value = Value::Int(0);
let mut __for_first_1462: bool = true;
while { if !__for_first_1462 { if let Value::Int(n) = &mut ci { *n += 1; } } __for_first_1462 = false; ci.as_f64().unwrap_or(f64::NAN) < categoriesLength } {
let mut category: Value = self.safe_dict(categories.clone(), ci.clone(), &[]);
let mut categorySlug: Option<String> = self.safe_string_k_opt(category.clone(), "slug", &[]);
if (categorySlug.is_none()) {
// nothing to key a duplicate on, keep the row rather than drop it
result.push(category.clone());
} else if !(matches!((&seenSlugs, &categorySlug.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seenSlugs { std::sync::Arc::make_mut(__d).insert(categorySlug.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
result.push(category);
}
}
}
// a term can match a market whose category row is not in the response - those rows are
// the other half of the payload and would otherwise be dropped, so bucket them by the
// categorySlug they carry
let mut rawMarkets: Vec<Value> = self.safe_list_k(data, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut mi: Value = Value::Int(0);
let mut __for_first_1463: bool = true;
while { if !__for_first_1463 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1463 = false; mi.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut rawMarket: Value = rawMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut marketSlug: Option<String> = self.safe_string_k_opt(rawMarket.clone(), "categorySlug", &[]);
if (marketSlug.is_some()) {
if (matches!((&orphanMarkets, &marketSlug.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
// push through a local and write the slice back - the go transpiler's
// AppendToArray reassigns only a local copy of a map-stored array
let mut bucket: Value = (if let (Some(__m), Some(__k)) = (orphanMarkets.as_map(), marketSlug.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
if let Value::Arr(__a) = &mut bucket { std::sync::Arc::make_mut(__a).push(rawMarket.clone()); };
crate::set_value(&mut orphanMarkets, &marketSlug.clone().map(Value::from).unwrap_or(Value::Null), bucket.clone());
if let Value::Dict(__d) = &mut orphanMarkets { std::sync::Arc::make_mut(__d).insert(marketSlug.as_deref().unwrap_or("null").to_string(), bucket); }
} else {
if let Value::Dict(__d) = &mut orphanMarkets { std::sync::Arc::make_mut(__d).insert(marketSlug.as_deref().unwrap_or("null").to_string(), Value::from(vec![rawMarket])); }
orphanSlugs.push(marketSlug.map(Value::from).unwrap_or(Value::Null));
}
}
}
}
}
}
// whatever the category rows did not claim is a market-only hit: synthesize the enclosing
// topic from the market rows themselves, without spending a request per slug
let mut orphanSlugsLength: f64 = ((orphanSlugs.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1465: bool = true;
while { if !__for_first_1465 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1465 = false; i.as_f64().unwrap_or(f64::NAN) < orphanSlugsLength } {
let mut orphanSlug: Value = orphanSlugs.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if !(matches!((&seenSlugs, &orphanSlug), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
if let Value::Dict(__d) = &mut seenSlugs { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&orphanSlug), Value::Bool(true)); }
let mut markets: Value = (if let (Some(__m), Some(__k)) = (orphanMarkets.as_map(), orphanSlug.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut first: Value = self.safe_dict(markets.clone(), Value::Int(0), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// the market row's 'status' is the registration enum ('REGISTERED' /
// 'DEREGISTERED'), while parseEvent () reads the topic vocabulary ('OPEN' /
// 'RESOLVED') - copying it verbatim would report resolved: false for a resolved hit
let mut marketStatus: Option<String> = self.safe_string_k(first.clone(), "status", &[]).as_str().map(str::to_owned);
let mut tradingStatus: Option<String> = self.safe_string_k(first.clone(), "tradingStatus", &[]).as_str().map(str::to_owned);
let mut topicStatus: Value = Value::Null;
if (marketStatus.as_deref() == Some("RESOLVED")) || (marketStatus.as_deref() == Some("SETTLED")) {
topicStatus = Value::Str("RESOLVED".into());
} else if (tradingStatus.as_deref() == Some("OPEN")) {
topicStatus = Value::Str("OPEN".into());
}
result.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orphanSlug.clone());
m.insert("slug".to_string(), orphanSlug.clone());
m.insert("title".to_string(), self.safe_string_k(first.clone(), "title", &[]));
m.insert("description".to_string(), self.safe_string_k(first.clone(), "description", &[]));
m.insert("imageUrl".to_string(), self.safe_string_k(first.clone(), "imageUrl", &[]));
m.insert("marketVariant".to_string(), self.safe_string_k(first.clone(), "marketVariant", &[]));
m.insert("isNegRisk".to_string(), self.safe_bool_k(first.clone(), "isNegRisk", &[]));
m.insert("isYieldBearing".to_string(), self.safe_bool_k(first.clone(), "isYieldBearing", &[]));
m.insert("isVisible".to_string(), self.safe_bool_k(first.clone(), "isVisible", &[]));
m.insert("status".to_string(), topicStatus);
m.insert("createdAt".to_string(), self.safe_string_k(first, "createdAt", &[]));
m.insert("markets".to_string(), markets);
m
}));
}
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parseEvent
* @description parses a raw predictfun market topic (with nested markets) into the unified event shape
* @param {object} rawTopic the raw market topic object
* @returns {object} an event structure
*/
pub fn parse_event(&self, mut rawTopic: Value) -> Value {
//
// {
// "createdAt": "2026-08-26T14:00:02.000Z",
// "description": "This market will resolve to \"Up\" if the ETH/USDT price at the end of the time range specified in the title is greater than the price at the beginning of that range.\r\n\r\nIt will resolve to \"Down\" if the ETH/USDT price at the end of the time range is lower than the price at the beginning of that range.\r\n\r\nIf the two prices are exactly equal, the market will resolve 50-50.\r\n\r\nThe primary resolution source for this market is Chainlink, specifically the ETH/USDT data stream available at https://data.chain.link/streams/eth-usdt-topofbook-datalink?timeframe=1d&chart=candlestick.\r\n\r\nTo verify the final price, use the close price of the 5m candlestick just before the market's end time. For example, for a market running from 1:00 to 1:15 PM ET or 1:10 to 1:15 PM ET, use the close price of the 1:10 PM candlestick as the final price.\r\n\r\nThe Chainlink stream uses the mid-price, which is calculated as the average price between the bid and ask prices from Binance's Top of Book, converted into the quote currency.\r\n\r\nThis market is based solely on the price reported by the Chainlink ETH/USDT data stream, not on other sources or spot markets.\r\n\r\nIf Chainlink data is unavailable or otherwise unusable for resolution, the market will resolve based on a consensus of reliable sources.\n2026-08-27T14:00:00Z",
// "endsAt": "2026-08-27T14:15:00.000Z",
// "id": 405022,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isNegRisk": false,
// "isVisible": true,
// "isYieldBearing": false,
// "marketVariant": "CRYPTO_UP_DOWN",
// "markets": [
// {
// "boostEndsAt": "2026-08-27T14:15:00.000Z",
// "boostStartsAt": "2026-08-27T14:00:00.000Z",
// "categorySlug": "eth-updown-15m-1787839200",
// "conditionId": "0xa8e9c348c299989329debd86aaef81a1c4880d42c3954a684bdc731f7a113487",
// "createdAt": "2026-08-26T14:00:02.000Z",
// "decimalPrecision": 2,
// "description": "This market will resolve to \"Up\" if the ETH/USDT price at the end of the time range specified in the title is greater than the price at the beginning of that range.\r\n\r\nIt will resolve to \"Down\" if the ETH/USDT price at the end of the time range is lower than the price at the beginning of that range.\r\n\r\nIf the two prices are exactly equal, the market will resolve 50-50.\r\n\r\nThe primary resolution source for this market is Chainlink, specifically the ETH/USDT data stream available at https://data.chain.link/streams/eth-usdt-topofbook-datalink?timeframe=1d&chart=candlestick.\r\n\r\nTo verify the final price, use the close price of the 5m candlestick just before the market's end time. For example, for a market running from 1:00 to 1:15 PM ET or 1:10 to 1:15 PM ET, use the close price of the 1:10 PM candlestick as the final price.\r\n\r\nThe Chainlink stream uses the mid-price, which is calculated as the average price between the bid and ask prices from Binance's Top of Book, converted into the quote currency.\r\n\r\nThis market is based solely on the price reported by the Chainlink ETH/USDT data stream, not on other sources or spot markets.\r\n\r\nIf Chainlink data is unavailable or otherwise unusable for resolution, the market will resolve based on a consensus of reliable sources.",
// "feeRateBps": 200,
// "id": 1739803,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isBoosted": false,
// "isNegRisk": false,
// "isVisible": true,
// "isYieldBearing": false,
// "kalshiMarketTicker": null,
// "marketType": null,
// "marketVariant": "CRYPTO_UP_DOWN",
// "oracleQuestionId": "0x6ab55f25f108508e7c6cc9bb22e3304d3fcecd0771d741fdf6d67e6b7ab9af2c",
// "outcomes": [
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 1,
// "name": "Up",
// "onChainId": "63015212288887519605689521802215931005858239156918107575780791658588345185817",
// "status": null,
// "team": null,
// "variantData": null
// },
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 2,
// "name": "Down",
// "onChainId": "111913554301217491431600756326792444318464112865057816486042507140136158411642",
// "status": null,
// "team": null,
// "variantData": null
// }
// ],
// "polymarketConditionIds": [],
// "question": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "questionIndex": null,
// "resolution": null,
// "resolverAddress": "0x77620FAb2969dF2D5696F1f081940E416Cf17cA5",
// "rewards": {
// "current": null,
// "schedule": [
// {
// "endsAt": "2026-08-27T14:15:00.000Z",
// "hourlyRate": 3000,
// "startsAt": "2026-08-27T14:00:00.000Z"
// }
// ]
// },
// "shareThreshold": 100,
// "spreadThreshold": 0.06,
// "status": "REGISTERED",
// "team": null,
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "tradingStatus": "OPEN",
// "variantData": {
// "endPrice": null,
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT",
// "startPrice": null,
// "type": "CRYPTO_UP_DOWN"
// }
// }
// ],
// "negRiskOnChainId": null,
// "parentSlug": null,
// "publishedAt": "2026-08-26T14:00:20.780Z",
// "resolutionProvider": "CHAINLINK",
// "shortTitle": "ETH Up or Down 15m",
// "slug": "eth-updown-15m-1787839200",
// "startsAt": "2026-08-27T14:00:00.000Z",
// "stats": null,
// "status": "OPEN",
// "tags": [
// {
// "id": "2",
// "level": 1,
// "makerRebateBps": 0,
// "name": "Crypto",
// "parentId": null
// },
// {
// "id": "7",
// "level": null,
// "makerRebateBps": 0,
// "name": "ETH",
// "parentId": null
// },
// {
// "id": "111",
// "level": 2,
// "makerRebateBps": 2500,
// "name": "Up/Down",
// "parentId": "2"
// },
// {
// "id": "146",
// "level": 2,
// "makerRebateBps": 0,
// "name": "15 Min",
// "parentId": "2"
// }
// ],
// "teams": null,
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "variantData": {
// "endPrice": null,
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT",
// "startPrice": null,
// "type": "CRYPTO_UP_DOWN"
// },
// "variantDetails": {
// "crypto": {
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT"
// },
// "upDown": {
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT"
// }
// }
// }
//
let mut rawMarkets: Vec<Value> = self.safe_list_k(rawTopic.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut marketsList: Vec<Value> = Vec::new();
let mut anyActive: Value = Value::Bool(false);
let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1466: bool = true;
while { if !__for_first_1466 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1466 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
let mut parsed: Value = self.parse_topic_market(rawMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), rawTopic.clone());
marketsList.push(parsed.clone());
if matches!(self.safe_bool_k(parsed, "active", &[Value::Bool(false)]), Value::Bool(true)) {
anyActive = Value::Bool(true);
}
}
}
let mut slug: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "slug", &[]);
let mut title: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "title", &[]);
let mut endDate: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "endsAt", &[]);
let mut created: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "createdAt", &[]);
let mut status: Option<String> = self.safe_string_k(rawTopic.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = anyActive;
if (rawMarketsLength == 0.0) {
active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
}
let mut resolved: Value = Value::Null;
if (status.is_some()) {
resolved = Value::Bool((status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED")));
}
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("event".to_string(), (if (slug.is_some()) { self.shorten_slug(slug.map(Value::from).unwrap_or(Value::Null)) } else { Value::Null }));
m.insert("title".to_string(), title.map(Value::from).unwrap_or(Value::Null));
m.insert("description".to_string(), self.safe_string_k(rawTopic.clone(), "description", &[]));
m.insert("markets".to_string(), Value::from(marketsList));
m.insert("active".to_string(), active);
m.insert("url".to_string(), Value::Null);
m.insert("image".to_string(), self.safe_string_k(rawTopic.clone(), "imageUrl", &[]));
m.insert("created".to_string(), self.parse8601(created.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("createdDatetime".to_string(), created.map(Value::from).unwrap_or(Value::Null));
m.insert("end".to_string(), self.parse8601(endDate.clone().map(Value::from).unwrap_or(Value::Null)));
m.insert("endDatetime".to_string(), endDate.map(Value::from).unwrap_or(Value::Null));
m.insert("category".to_string(), self.safe_string_k(rawTopic.clone(), "marketVariant", &[]));
m.insert("resolved".to_string(), resolved);
m.insert("info".to_string(), rawTopic);
m
});
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#stripPriceFormatting
* @description drops the formatting the venue puts in a price but not in its slug - the currency sign, and a comma that sits between two digits
* @param {string} [text] the raw title or outcome label
* @returns {string} the same text with '$' removed and thousands separators closed up
*/
pub fn strip_price_formatting(&self, mut text: Value) -> Option<String> {
if (text == Value::Null) {
return None;
}
let mut digits: String = "0123456789".to_string();
let mut chars: Value = self.string_to_chars_array(text);
let mut stripped: Value = Value::Str("".into());
{
let mut i: Value = Value::Int(0);
let mut __for_first_1467: bool = true;
while { if !__for_first_1467 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1467 = false; i.as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64) } {
let mut ch: Value = chars.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
let mut keep: bool = true;
if (ch.as_str() == Some("$")) {
keep = false;
} else if (ch.as_str() == Some(",")) {
// only a comma between two digits is a thousands separator: "1,500" has to close
// up to "1500" to match the venue's comma-free slug. a comma anywhere else is
// ordinary punctuation and stays, so it still separates words
let mut prevIsDigit: bool = (i.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) && ((match (&(Value::from(digits.clone())), &(chars.as_array().and_then(|__arr| match &((match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x),
Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null))) { (Value::Arr(__a), __nd) => Value::Int(__a.iter().position(|__it| match (__it, __nd) { (Value::Null,
Value::Null) => true, (Value::Bool(__x), Value::Bool(__y)) => __x == __y, (Value::Str(__x), Value::Str(__y)) => __x == __y, (Value::Int(__x), Value::Int(__y)) => __x == __y, (Value::Float(__x), Value::Float(__y)) => __x == __y, (__p, __q) => match ((match __p { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f),
Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), (match __q { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None })) { (Some(__x),
Some(__y)) => __x == __y, _ => false } }).map(|__i| __i as i64).unwrap_or(-1)), (Value::Str(__s), Value::Str(__nd)) => Value::Int(__s.find(&**__nd).map(|__i| __i as i64).unwrap_or(-1)), _ => Value::Int(-1) }).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64));
let mut nextIsDigit: bool = (((match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y),
_ => Value::Null })).as_f64().unwrap_or(f64::NAN) < ((chars.len() as i64) as f64)) && ((match (&(Value::from(digits.clone())), &(chars.as_array().and_then(|__arr| match &((match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y),
(Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null))) { (Value::Arr(__a), __nd) => Value::Int(__a.iter().position(|__it| match (__it,
__nd) { (Value::Null, Value::Null) => true, (Value::Bool(__x), Value::Bool(__y)) => __x == __y, (Value::Str(__x), Value::Str(__y)) => __x == __y, (Value::Int(__x), Value::Int(__y)) => __x == __y, (Value::Float(__x), Value::Float(__y)) => __x == __y, (__p, __q) => match ((match __p { Value::Int(__n) => Some(*__n as f64),
Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }), _ => None }), (match __q { Value::Int(__n) => Some(*__n as f64), Value::Float(__f) => Some(*__f), Value::Str(__s) => __s.parse::<f64>().ok(), Value::Bool(__b) => Some(if *__b { 1.0 } else { 0.0 }),
_ => None })) { (Some(__x), Some(__y)) => __x == __y, _ => false } }).map(|__i| __i as i64).unwrap_or(-1)), (Value::Str(__s), Value::Str(__nd)) => Value::Int(__s.find(&**__nd).map(|__i| __i as i64).unwrap_or(-1)), _ => Value::Int(-1) }).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64));
keep = !(prevIsDigit && nextIsDigit);
}
if keep {
stripped = Value::Str(format!("{}{}", stripped, ch).into());
}
}
}
return stripped.as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#titleForMarketSymbol
* @description decides what of a market title belongs in the unified symbol, given how many markets its topic holds
* @param {string} [topicSlug] the slug of the enclosing topic
* @param {string} [title] the market title
* @param {int} [marketCount] how many markets the topic carries
* @returns {string} the title to append, or the slug itself when the topic holds a single market
*/
pub fn title_for_market_symbol(&self, mut topicSlug: Value, mut title: Value, optional_args: &[Value]) -> Option<String> {
let mut marketCount = get_arg(optional_args, 0, Value::Null);
// a topic holding one market needs nothing to tell its markets apart, and the title there
// only restates the slug in another spelling - the venue writes the same window as
// btc-updown-5m-1789017900 and as "Bitcoin Up or Down - September 10, 1:25AM-1:30AM ET".
// returning the slug makes slugToMarketSymbol collapse the two halves into one part.
// inside a multi-market topic the title is what keeps the handles apart, so it stays
if (marketCount.as_f64() == Some(1.0)) && (topicSlug != Value::Null) {
return topicSlug.as_str().map(str::to_owned);
}
return self.strip_price_formatting(title);
}
/*
* @ignore
* @method
* @name predictfun#parseTopicMarket
* @description parses one nested market of a market topic into the unified market shape, building its outcome tokens
* @param {object} rawMarket the nested market object
* @param {object} rawTopic the enclosing raw market topic (carries slug/vendor/fees/dates)
* @returns {object} a market structure
*/
pub fn parse_topic_market(&self, mut rawMarket: Value, mut rawTopic: Value) -> Value {
let __rawTopic_empty = indexmap::IndexMap::new();
let rawTopic = rawTopic.as_map().unwrap_or(&__rawTopic_empty);
//
// {
// "boostEndsAt": "2026-08-27T14:15:00.000Z",
// "boostStartsAt": "2026-08-27T14:00:00.000Z",
// "categorySlug": "eth-updown-15m-1787839200",
// "conditionId": "0xa8e9c348c299989329debd86aaef81a1c4880d42c3954a684bdc731f7a113487",
// "createdAt": "2026-08-26T14:00:02.000Z",
// "decimalPrecision": 2,
// "description": "This market will resolve to \"Up\" if the ETH/USDT price at the end of the time range specified in the title is greater than the price at the beginning of that range.\r\n\r\nIt will resolve to \"Down\" if the ETH/USDT price at the end of the time range is lower than the price at the beginning of that range.\r\n\r\nIf the two prices are exactly equal, the market will resolve 50-50.\r\n\r\nThe primary resolution source for this market is Chainlink, specifically the ETH/USDT data stream available at https://data.chain.link/streams/eth-usdt-topofbook-datalink?timeframe=1d&chart=candlestick.\r\n\r\nTo verify the final price, use the close price of the 5m candlestick just before the market's end time. For example, for a market running from 1:00 to 1:15 PM ET or 1:10 to 1:15 PM ET, use the close price of the 1:10 PM candlestick as the final price.\r\n\r\nThe Chainlink stream uses the mid-price, which is calculated as the average price between the bid and ask prices from Binance's Top of Book, converted into the quote currency.\r\n\r\nThis market is based solely on the price reported by the Chainlink ETH/USDT data stream, not on other sources or spot markets.\r\n\r\nIf Chainlink data is unavailable or otherwise unusable for resolution, the market will resolve based on a consensus of reliable sources.",
// "feeRateBps": 200,
// "id": 1739803,
// "imageUrl": "https://static.predict.fun/automarket-eth-usd-15-minutes",
// "isBoosted": false,
// "isNegRisk": false,
// "isVisible": true,
// "isYieldBearing": false,
// "kalshiMarketTicker": null,
// "marketType": null,
// "marketVariant": "CRYPTO_UP_DOWN",
// "oracleQuestionId": "0x6ab55f25f108508e7c6cc9bb22e3304d3fcecd0771d741fdf6d67e6b7ab9af2c",
// "outcomes": [
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 1,
// "name": "Up",
// "onChainId": "63015212288887519605689521802215931005858239156918107575780791658588345185817",
// "status": null,
// "team": null,
// "variantData": null
// },
// {
// "bestAsk": {
// "price": 0.98,
// "size": 100
// },
// "bestBid": {
// "price": 0.02,
// "size": 100
// },
// "indexSet": 2,
// "name": "Down",
// "onChainId": "111913554301217491431600756326792444318464112865057816486042507140136158411642",
// "status": null,
// "team": null,
// "variantData": null
// }
// ],
// "polymarketConditionIds": [],
// "question": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "questionIndex": null,
// "resolution": null,
// "resolverAddress": "0x77620FAb2969dF2D5696F1f081940E416Cf17cA5",
// "rewards": {
// "current": null,
// "schedule": [
// {
// "endsAt": "2026-08-27T14:15:00.000Z",
// "hourlyRate": 3000,
// "startsAt": "2026-08-27T14:00:00.000Z"
// }
// ]
// },
// "shareThreshold": 100,
// "spreadThreshold": 0.06,
// "status": "REGISTERED",
// "team": null,
// "title": "Ethereum Up or Down - August 27, 10AM-10:15AM ET",
// "tradingStatus": "OPEN",
// "variantData": {
// "endPrice": null,
// "priceFeedId": "0x0003543336278a459ac24c2f239ffa36f279cadc71f4babc9f8126c6ff10011d",
// "priceFeedProvider": "CHAINLINK",
// "priceFeedSymbol": "ETHUSDT",
// "startPrice": null,
// "type": "CRYPTO_UP_DOWN"
// }
// }
//
let mut marketId: Option<String> = self.safe_string_k_opt(rawMarket.clone(), "id", &[]);
let mut topicSlug: Option<String> = self.safe_string_k_opt(rawMarket.clone(), "categorySlug", &[]);
// the same handle parseEvent () derives for the enclosing event - stamping it here is what
// lets every outcome-addressed structure (order, ticker, trade, position) report an event
let mut eventHandle: Value = Value::Null;
if (topicSlug.is_some()) {
eventHandle = self.shorten_slug(topicSlug.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut title: Value = self.safe_string_k(rawMarket.clone(), "title", &[marketId.clone().map(Value::from).unwrap_or(Value::Null)]);
let mut topicMarkets: Vec<Value> = (match rawTopic.get("markets") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }).as_array().cloned().unwrap_or_default();
let mut marketCount: Value = Value::Int(topicMarkets.len() as i64);
let mut symbolTitle: Value = self.title_for_market_symbol(topicSlug.clone().map(Value::from).unwrap_or(Value::Null), title, &[marketCount]).map(Value::from).unwrap_or(Value::Null);
let mut marketSymbol: Value = self.slug_to_market_symbol(topicSlug.clone().map(Value::from).unwrap_or(Value::Null), symbolTitle);
let mut tradingStatus: Option<String> = self.safe_string_k(rawMarket.clone(), "tradingStatus", &[]).as_str().map(str::to_owned);
let mut status: Option<String> = self.safe_string_k(rawMarket.clone(), "status", &[]).as_str().map(str::to_owned);
let mut active: Value = (Value::Bool(tradingStatus.as_deref() == Some("OPEN")));
if (tradingStatus.is_none()) {
active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
}
let mut resolved: Value = Value::Bool((status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED")));
let mut endDate: Value = (match rawTopic.get("endsAt") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
let mut feeRateBps: Value = self.safe_string_k(rawMarket.clone(), "feeRateBps", &[Value::Str("200".into())]); // todo check
let mut feeRate: Value = self.parse_number(crate::precise::Precise::stringDiv(&feeRateBps, &Value::Str("10000".into())), &[]);
let mut decimalPrecision: Value = self.safe_string_k(rawMarket.clone(), "decimalPrecision", &[Value::Str("2".into())]);
let mut pricePrecision: Value = self.parse_number(self.parse_precision(&[decimalPrecision]), &[]);
let mut precision: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("amount".to_string(), Value::Float(0.01));
m.insert("price".to_string(), pricePrecision);
m
});
let mut rawOutcomes: Vec<Value> = self.safe_list_k(rawMarket.clone(), "outcomes", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut outcomes: Vec<Value> = Vec::new();
let mut resolvedOutcomeRaw: Value = Value::Null;
let mut rawOutcomesLength: f64 = ((rawOutcomes.len() as i64) as f64);
{
let mut oi: Value = Value::Int(0);
let mut __for_first_1468: bool = true;
while { if !__for_first_1468 { if let Value::Int(n) = &mut oi { *n += 1; } } __for_first_1468 = false; oi.as_f64().unwrap_or(f64::NAN) < rawOutcomesLength } {
let mut rawOutcome: Value = rawOutcomes.get(oi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
// a label can carry a formatted price ("$1,800+"), and it goes into the outcome
// handle verbatim - strip the same formatting the title gets
let mut rawLabel: Option<String> = self.safe_string_upper_k_opt(rawOutcome.clone(), "name", &[]);
let mut label: Value = self.strip_price_formatting(rawLabel.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
let mut tokenId: Option<String> = self.safe_string_k_opt(rawOutcome.clone(), "onChainId", &[]);
let mut outcomeHandle: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", marketSymbol, Value::Str(":".into())).into()), label).into());
let mut winner: Value = Value::Null;
let mut outcomeStatus: Option<String> = self.safe_string_k(rawOutcome.clone(), "status", &[]).as_str().map(str::to_owned);
let mut settleFractionRaw: Value = Value::Null;
if (outcomeStatus.is_some()) {
winner = (Value::Bool(outcomeStatus.as_deref() == Some("WON")));
if winner.as_bool() == Some(true) {
settleFractionRaw = Value::Int(1);
resolvedOutcomeRaw = outcomeHandle.clone();
} else {
settleFractionRaw = Value::Int(0); // todo check
}
}
let mut settleFraction: Value = settleFractionRaw;
outcomes.push(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m.insert("outcome".to_string(), outcomeHandle);
m.insert("market".to_string(), marketSymbol.clone());
m.insert("event".to_string(), eventHandle.clone());
m.insert("label".to_string(), label);
m.insert("price".to_string(), Value::Null);
m.insert("active".to_string(), active.clone());
m.insert("winner".to_string(), winner);
m.insert("settleFraction".to_string(), settleFraction);
m.insert("precision".to_string(), Value::Map(precision.clone()));
m.insert("info".to_string(), self.extend(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
m
}), &[rawOutcome]));
m
}));
}
}
let mut resolvedOutcome: Value = resolvedOutcomeRaw;
let mut collateral: String = "USDT".to_string();
let mut marketType: String = "binary".to_string();
if rawOutcomesLength > ((2i64) as f64) {
marketType = "categorical".to_string();
}
let mut createdDatetime: Option<String> = self.safe_string_k_opt(rawMarket.clone(), "createdAt", &[]);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("market".to_string(), marketSymbol);
m.insert("base".to_string(), Value::from(collateral.clone()));
m.insert("quote".to_string(), Value::from(collateral.clone()));
m.insert("settle".to_string(), Value::Null);
m.insert("baseId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("quoteId".to_string(), Value::from(collateral.clone()));
m.insert("settleId".to_string(), Value::Null);
m.insert("type".to_string(), Value::Str("prediction".into()));
m.insert("marketType".to_string(), Value::from(marketType));
m.insert("executionModel".to_string(), Value::Str("clob".into()));
m.insert("collateral".to_string(), Value::from(collateral));
m.insert("spot".to_string(), Value::Bool(false));
m.insert("margin".to_string(), Value::Bool(false));
m.insert("swap".to_string(), Value::Bool(false));
m.insert("future".to_string(), Value::Bool(false));
m.insert("option".to_string(), Value::Bool(false));
m.insert("prediction".to_string(), Value::Bool(true));
m.insert("active".to_string(), active);
m.insert("resolved".to_string(), resolved);
m.insert("resolvedOutcome".to_string(), resolvedOutcome);
m.insert("contract".to_string(), Value::Bool(false));
m.insert("linear".to_string(), Value::Null);
m.insert("inverse".to_string(), Value::Null);
m.insert("contractSize".to_string(), Value::Null);
m.insert("expiry".to_string(), self.parse8601(endDate.clone()));
m.insert("expiryDatetime".to_string(), endDate);
m.insert("strike".to_string(), Value::Null);
m.insert("optionType".to_string(), Value::Null);
m.insert("taker".to_string(), feeRate);
m.insert("maker".to_string(), Value::Int(0));
m.insert("percentage".to_string(), Value::Bool(true));
m.insert("tierBased".to_string(), Value::Bool(false));
m.insert("feeSide".to_string(), Value::Str("get".into()));
m.insert("precision".to_string(), Value::Map(precision));
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::Int(1));
m.insert("max".to_string(), Value::Int(1));
m
}));
m.insert("amount".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Null);
m.insert("max".to_string(), Value::Null);
m
}));
m.insert("price".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Float(0.01));
m.insert("max".to_string(), Value::Float(0.99));
m
}));
m.insert("cost".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("min".to_string(), Value::Int(1));
m.insert("max".to_string(), Value::Null);
m
}));
m
}));
m.insert("outcomes".to_string(), Value::from(outcomes));
m.insert("info".to_string(), rawMarket);
m.insert("created".to_string(), self.parse8601(createdDatetime.map(Value::from).unwrap_or(Value::Null)));
m
});
Value::Null
}
/*
* @method
* @name predictfun#fetchOrderBook
* @description fetches the order book for a single prediction outcome token
* @see https://dev.predict.fun/get-the-orderbook-for-a-market-25326908e0
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {int} [limit] not used by predictfun fetchOrderBook
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a prediction [order book structure](https://docs.ccxt.com/#/?id=order-book-structure)
*/
pub async fn fetch_order_book(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(info.clone(), "marketId", &[]));
m
});
let __ws_arg_3 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_get_v1_markets_id_orderbook(&[__ws_arg_3]).await;
//
// {
// "data":
// {
// "asks": [
// [ 0.99, 101 ]
// ],
// "bids": [
// [ 0.01, 101 ]
// ],
// "lastOrderSettled": null,
// "marketId": 1743016,
// "updateTimestampMs": 1787770521244
// },
// "success":true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut timestamp: Option<i64> = self.safe_integer_k(data.clone(), "updateTimestampMs", &[]).as_i64();
// The outcome lables are not the same as the outcome indexSet values, so we need to check the indexSet to determine which outcome is being requested
let mut indexSet: Option<i64> = self.safe_integer_k(info, "indexSet", &[]).as_i64();
let mut isYesOutcome: bool = indexSet == Some(1);
let mut outcomeSymbol: Value = self.safe_outcome_symbol(outcome, &[outcomeObj.clone()]);
// the book endpoint is quoted in the yes token, the no side mirrors at 1 - price with bids and asks swapped
if isYesOutcome {
let mut yesOrderbook: Value = self.parse_order_book(data.clone(), outcomeSymbol, &[Value::from(timestamp), Value::Str("bids".into()), Value::Str("asks".into()), Value::Int(0), Value::Int(1)]);
return self.safe_prediction_order_book(yesOrderbook, &[outcomeObj.clone()]);
} else {
let mut bids: Value = self.safe_list_k(data.clone(), "bids", &[Value::from(vec![])]);
let mut asks: Value = self.safe_list_k(data, "asks", &[Value::from(vec![])]);
let mut noBids: Vec<Value> = Vec::new();
let mut noAsks: Vec<Value> = Vec::new();
{
let mut i: i64 = 0;
let mut __for_first_1469: bool = true;
while { if !__for_first_1469 { i += 1; } __for_first_1469 = false; i < (bids.len() as i64) } {
let mut bid: Value = self.safe_list(bids.clone(), Value::Int(i), &[]);
let mut bidPrice: Option<String> = self.safe_string_opt(bid.clone(), Value::Int(0), &[]);
let mut bidSize: Value = self.parse_number(self.safe_string(bid, Value::Int(1), &[]), &[]);
let mut complementPrice: Value = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &bidPrice.clone().map(Value::from).unwrap_or(Value::Null)), &[]);
noAsks.push(Value::from(vec![complementPrice.clone(), bidSize]));
}
}
{
let mut i: i64 = 0;
let mut __for_first_1470: bool = true;
while { if !__for_first_1470 { i += 1; } __for_first_1470 = false; i < (asks.len() as i64) } {
let mut ask: Value = self.safe_list(asks.clone(), Value::Int(i), &[]);
let mut askPrice: Option<String> = self.safe_string_opt(ask.clone(), Value::Int(0), &[]);
let mut askSize: Value = self.parse_number(self.safe_string(ask, Value::Int(1), &[]), &[]);
let mut complementPrice: Value = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &askPrice.clone().map(Value::from).unwrap_or(Value::Null)), &[]);
noBids.push(Value::from(vec![complementPrice, askSize]));
}
}
let mut noOrderbook: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), self.sort_by(Value::from(noBids), Value::Int(0), &[Value::Bool(true)]));
m.insert("asks".to_string(), self.sort_by(Value::from(noAsks), Value::Int(0), &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("nonce".to_string(), Value::Null);
m
});
return self.safe_prediction_order_book(Value::Map(noOrderbook), &[outcomeObj]);
}
Value::Null
}
/*
* @method
* @name predictfun#fetchTicker
* @description fetches the best bid and ask for a single prediction outcome token
* @see https://dev.predict.fun/get-market-by-id-25552989e0
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(info, "marketId", &[]));
m
});
// the market detail carries a bestBid/bestAsk per outcome, already sided for the NO
// outcome - last price and volume live behind /last-sale and /stats, one request each,
// so they are left undefined rather than spending extra calls on them
let __ws_arg_4 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_get_v1_markets_id(&[__ws_arg_4]).await;
//
// {
// "data": {
// "id": 2107,
// "title": "Will Trump acquire Greenland before 2027?",
// "tradingStatus": "OPEN",
// "status": "REGISTERED",
// "decimalPrecision": 2,
// "feeRateBps": 200,
// "outcomes": [
// {
// "name": "Yes",
// "indexSet": 1,
// "onChainId": "43765171147442247918432418752066697760469767620931280624762484655579631167373",
// "bestBid": { "price": 0.02, "size": 1448.4122448979592 },
// "bestAsk": { "price": 0.032, "size": 675.29 },
// "status": null
// },
// {
// "name": "No",
// "indexSet": 2,
// "bestBid": { "price": 0.968, "size": 675.29 },
// "bestAsk": { "price": 0.98, "size": 1448.4122448979592 },
// "status": null
// }
// ]
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_ticker(data, &[outcomeObj]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parsePredictionTicker
* @description parses a raw market detail into a unified prediction ticker for one of its outcomes
* @param {object} ticker the raw market object, with a nested outcomes list
* @param {object} [market] the outcome the ticker belongs to
* @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
*/
pub fn parse_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// {
// "id": 2107,
// "title": "Will Trump acquire Greenland before 2027?",
// "tradingStatus": "OPEN",
// "status": "REGISTERED",
// "decimalPrecision": 2,
// "feeRateBps": 200,
// "outcomes": [
// {
// "name": "Yes",
// "indexSet": 1,
// "onChainId": "43765171147442247918432418752066697760469767620931280624762484655579631167373",
// "bestBid": { "price": 0.02, "size": 1448.4122448979592 },
// "bestAsk": { "price": 0.032, "size": 675.29 },
// "status": null
// },
// {
// "name": "No",
// "indexSet": 2,
// "bestBid": { "price": 0.968, "size": 675.29 },
// "bestAsk": { "price": 0.98, "size": 1448.4122448979592 },
// "status": null
// }
// ]
// }
//
let mut info: Value = self.safe_dict_k(market.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut indexSet: Value = self.safe_integer_k(info, "indexSet", &[]);
let mut rawOutcomes: Vec<Value> = self.safe_list_k(ticker.clone(), "outcomes", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rawOutcomesLength: f64 = ((rawOutcomes.len() as i64) as f64);
let mut rawOutcome: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut outcomeFound: bool = false;
{
let mut i: Value = Value::Int(0);
let mut __for_first_1471: bool = true;
while { if !__for_first_1471 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1471 = false; i.as_f64().unwrap_or(f64::NAN) < rawOutcomesLength } {
let mut candidate: Value = rawOutcomes.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut candidateIndexSet: Value = self.safe_integer_k(candidate.clone(), "indexSet", &[]);
if (candidateIndexSet.as_f64() == indexSet.as_f64()) {
rawOutcome = candidate;
outcomeFound = true;
break;
}
}
}
if !(outcomeFound) {
// an unmatched indexSet would otherwise return a ticker whose every quote is
// undefined, which reads as an empty book rather than as a market that never
// carried this outcome
let requested: String = self.safe_string_k_opt(market.clone(), "outcome", &[Value::Str("".into())]).unwrap_or_default();
panic!("{}", crate::exchange_errors::bad_symbol(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTicker() did not find ".into())).into()), requested).into()), Value::Str(" among the outcomes of its market".into()))));
}
// the venue quotes each outcome on its own side of the book, so no complement is needed
let mut bestBid: Value = self.safe_dict_k(rawOutcome.clone(), "bestBid", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut bestAsk: Value = self.safe_dict_k(rawOutcome, "bestAsk", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_prediction_ticker(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(market, "event", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("high".to_string(), Value::Null);
m.insert("low".to_string(), Value::Null);
m.insert("bid".to_string(), self.safe_number_k(bestBid.clone(), "price", &[]));
m.insert("bidVolume".to_string(), self.safe_number_k(bestBid, "size", &[]));
m.insert("ask".to_string(), self.safe_number_k(bestAsk.clone(), "price", &[]));
m.insert("askVolume".to_string(), self.safe_number_k(bestAsk, "size", &[]));
m.insert("open".to_string(), Value::Null);
m.insert("close".to_string(), Value::Null);
m.insert("last".to_string(), Value::Null);
m.insert("change".to_string(), Value::Null);
m.insert("percentage".to_string(), Value::Null);
m.insert("average".to_string(), Value::Null);
m.insert("baseVolume".to_string(), Value::Null);
m.insert("quoteVolume".to_string(), Value::Null);
m.insert("info".to_string(), ticker);
m
}), &[]);
Value::Null
}
/*
* @method
* @name predictfun#fetchMyTrades
* @description fetches the settled matches the wallet took part in, on either side of the book
* @see https://dev.predict.fun/get-order-match-events-25663812e0
* @param {string} [outcome] unified outcome handle, restricts the call to that outcome's market
* @param {int} [since] timestamp in ms of the earliest trade to return, applied client side
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.after] cursor from a previous response, the venue pages back from the most recent match
* @param {bool} [params.isSignerMaker] true keeps only the matches the wallet rested, false only the ones it took
* @param {string} [params.signerAddress] read another wallet's matches instead of the configured one
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut signerAddress: Value = self.safe_string_k(params.clone(), "signerAddress", &[self.walletAddress.clone()]);
if (signerAddress == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchMyTrades() requires a walletAddress, or a \"signerAddress\" parameter for any other address".into()))));
}
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("signerAddress".to_string(), signerAddress.clone());
m
});
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
request.insert("marketId".into(), self.safe_string_k(info, "marketId", &[]));
}
let mut query: Value = self.omit(params, Value::Str("signerAddress".into()), &[]);
// the endpoint carries no time filter, it pages back from the most recent match, so
// since is applied client side by parsePredictionTrades
let __ws_arg_5 = self.extend(Value::Map(request), &[query]);
let mut response: Value = self.predictfun_get_v1_orders_matches(&[__ws_arg_5]).await;
// the venue answers with the shape documented in fetchTrades below
let mut data: Vec<Value> = self.safe_list_k(response, "data", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut wallet: Value = (if let Some(__s) = signerAddress.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null });
// a settlement names one taker and several makers, and the wallet may sit on either side,
// so the legs it signed are the ones to report - a self trade legitimately yields two rows
let mut flattenTrades: Vec<Value> = Vec::new();
let mut dataLength: f64 = ((data.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1473: bool = true;
while { if !__for_first_1473 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1473 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength } {
let mut entry: Value = data.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut taker: Value = self.safe_dict_k(entry.clone(), "taker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut takerSigner: Option<String> = self.safe_string_lower_k_opt(taker.clone(), "signer", &[]);
if (takerSigner.as_deref() == wallet.as_str()) {
let mut takerParty: Value = self.extend(taker, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("role".to_string(), Value::Str("taker".into()));
m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
m.insert("type".to_string(), Value::Str("market".into()));
m
})]);
flattenTrades.push(self.extend(entry.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("partyToParse".to_string(), takerParty);
m
})]));
}
let mut makers: Vec<Value> = self.safe_list_k(entry.clone(), "makers", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut makersLength: f64 = ((makers.len() as i64) as f64);
{
let mut j: Value = Value::Int(0);
let mut __for_first_1472: bool = true;
while { if !__for_first_1472 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1472 = false; j.as_f64().unwrap_or(f64::NAN) < makersLength } {
let mut maker: Value = makers.get(j.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut makerSigner: Option<String> = self.safe_string_lower_k_opt(maker.clone(), "signer", &[]);
if (makerSigner.as_deref() == wallet.as_str()) {
let mut makerParty: Value = self.extend(maker, &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("role".to_string(), Value::Str("maker".into()));
m.insert("takerOrMaker".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("limit".into()));
m
})]);
flattenTrades.push(self.extend(entry.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("partyToParse".to_string(), makerParty);
m
})]));
}
}
}
}
}
return self.parse_prediction_trades(Value::from(flattenTrades), &[outcomeObj, since, limit]);
Value::Null
}
/*
* @method
* @name predictfun#fetchTrades
* @description fetches the most recent settled matches for a single prediction outcome token
* @see https://dev.predict.fun/get-order-match-events-25663812e0
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {int} [since] timestamp in ms of the earliest trade to return, applied client side
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.after] cursor from a previous response, the venue pages back from the most recent match
* @param {string} [params.minValueUsdtWei] only return matches worth at least this many wei
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn fetch_trades(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), self.safe_string_k(info.clone(), "marketId", &[]));
m
});
// the endpoint carries no time filter, it pages back from the most recent match, so
// since is applied client side by parsePredictionTrades
let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_get_v1_orders_matches(&[__ws_arg_6]).await;
//
// {
// "cursor": "eyJjcmVhdGVkQXQiOiIyMDI2LTA5LTA1VDIzOjU1OjU2WiJ9",
// "data": [
// {
// "amountFilled": "8409090909090909720",
// "executedAt": "2026-09-06T11:45:23.000Z",
// "priceExecuted": "111200000000000000",
// "settlementId": "01a07689-955a-7070-86af-a100b7b7350c",
// "transactionHash": "0x435863c29443ff45b2f8966c52428d3bb3a29a38de24dc6c17ca0817951fda79",
// "taker": {
// "amount": "8409090909090909720",
// "fee": { "amount": "151363636363636374", "type": "SHARES" },
// "hash": "0x0a0eab35c68fda64ced0989aec9313f5884e5ecba51d780f9b7da634cc979027",
// "outcome": { "indexSet": 1, "name": "Up", "onChainId": "44616422429987613582483910707767544579739686077414897363305263997555112684875" },
// "price": "112000000000000000",
// "quoteType": "Bid",
// "signer": "0x6Da6Cb464F92AE7aD4Ec3d239c81719Cb1D0Ae03"
// },
// "makers": [
// {
// "amount": "1009090909090909720",
// "fee": { "amount": "0", "type": "SHARES" },
// "hash": "0x0950ef588b53e2489f95cb1d830a6e0cb0bffc0f4baf4286e3b2e03bad2eba47",
// "outcome": { "indexSet": 2, "name": "Down", "onChainId": "39857821499700810175970492505692306870421072168717601114846981613437602260320" },
// "price": "880000000000000000",
// "quoteType": "Bid",
// "signer": "0x6Da6Cb464F92AE7aD4Ec3d239c81719Cb1D0Ae03"
// }
// ],
// "market": { "id": 1965449 }
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
let mut flattenTrades: Vec<Value> = Vec::new();
let mut dataLength: f64 = ((data.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1475: bool = true;
while { if !__for_first_1475 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1475 = false; i.as_f64().unwrap_or(f64::NAN) < dataLength } {
let mut entry: Value = self.safe_dict(data.clone(), i.clone(), &[]);
let mut taker: Value = self.safe_dict_k(entry.clone(), "taker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut takerOutcome: Value = self.safe_dict_k(taker, "outcome", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut takerIndexSet: Value = self.safe_integer_k(takerOutcome, "indexSet", &[]);
let mut outcomeIndexSet: Value = self.safe_integer_k(info.clone(), "indexSet", &[]);
let mut partyToParse: Value = self.safe_dict_k(entry.clone(), "taker", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (takerIndexSet.as_f64() == outcomeIndexSet.as_f64()) {
// a public print carries no takerOrMaker: the unified fetchTrades contract allows
// only 'taker' or nothing there, and the leg that matches the requested outcome is
// genuinely the maker one whenever the taker crossed into the opposite outcome.
// the role is kept for pricing and surfaces as the type of the order behind the leg
let mut takerParty: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("role".to_string(), Value::Str("taker".into()));
m.insert("type".to_string(), Value::Str("market".into()));
m
});
partyToParse = self.extend(partyToParse.clone(), &[Value::Map(takerParty)]);
flattenTrades.push(self.extend(entry.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("partyToParse".to_string(), partyToParse.clone());
m
})]));
} else {
let mut makers: Vec<Value> = self.safe_list_k(entry.clone(), "makers", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut makersLength: f64 = ((makers.len() as i64) as f64);
let mut makerParty: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("role".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("limit".into()));
m
});
{
let mut j: Value = Value::Int(0);
let mut __for_first_1474: bool = true;
while { if !__for_first_1474 { if let Value::Int(n) = &mut j { *n += 1; } } __for_first_1474 = false; j.as_f64().unwrap_or(f64::NAN) < makersLength } {
let mut maker: Value = makers.get(j.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut makerOutcome: Value = self.safe_dict_k(maker.clone(), "outcome", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut makerIndexSet: Value = self.safe_integer_k(makerOutcome, "indexSet", &[]);
if (makerIndexSet.as_f64() == outcomeIndexSet.as_f64()) {
partyToParse = maker;
partyToParse = self.extend(partyToParse.clone(), &[Value::Map(makerParty.clone())]);
flattenTrades.push(self.extend(entry.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("partyToParse".to_string(), partyToParse.clone());
m
})]));
}
}
}
}
}
}
return self.parse_prediction_trades(Value::from(flattenTrades), &[outcomeObj, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parsePredictionTrade
* @description parses a raw order match event into a unified prediction trade for one of the two outcomes
* @param {object} trade the raw match event
* @param {object} [market] the outcome the trade belongs to
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut party: Value = self.safe_dict_k(trade.clone(), "partyToParse", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// fetchMyTrades spans several markets at once, so the row's identity comes from the party
// it carries rather than from the outcome the caller asked for
let mut partyOutcome: Value = self.safe_dict_k(party.clone(), "outcome", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenId: Option<String> = self.safe_string_k_opt(partyOutcome, "onChainId", &[]);
let mut outcomeObj: Value = self.outcome_for_token(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
let mut role: Option<String> = self.safe_string_k(party.clone(), "role", &[]).as_str().map(str::to_owned);
// a resting maker fills at its own price, so the party price is the execution price for
// that leg. the taker's party price is only its limit: the settlement records what it
// actually paid, and the difference is the price improvement the book gave it
let mut priceStr: Value = self.safe_string_k(party.clone(), "price", &[]);
if (role.as_deref() == Some("taker")) {
priceStr = self.safe_string_k(trade.clone(), "priceExecuted", &[priceStr.clone()]);
}
priceStr = crate::precise::Precise::stringDiv(&priceStr, &Value::Str("1000000000000000000".into()));
let mut amountStr: Value = self.safe_string_k(party.clone(), "amount", &[]);
amountStr = crate::precise::Precise::stringDiv(&amountStr, &Value::Str("1000000000000000000".into()));
let mut side: Value = Value::Null;
let mut order: Value = Value::Null;
let mut fee: Value = Value::Null;
let mut quoteType: Option<String> = self.safe_string_lower_k(party.clone(), "quoteType", &[]).as_str().map(str::to_owned);
if (quoteType.as_deref() == Some("bid")) {
side = Value::Str("buy".into());
} else if (quoteType.as_deref() == Some("ask")) {
side = Value::Str("sell".into());
}
order = self.safe_string_k(party.clone(), "hash", &[]);
let mut rawFee: Value = self.safe_dict_k(party.clone(), "fee", &[]);
if (rawFee != Value::Null) {
let mut feeType: Option<String> = self.safe_string_k(rawFee.clone(), "type", &[]).as_str().map(str::to_owned);
let mut feeCost: Option<String> = self.safe_string_k_opt(rawFee, "amount", &[]);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), (if (feeType.as_deref() == Some("COLLATERAL")) { Value::Str("USDT".into()) } else { Value::Null }));
m.insert("cost".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&feeCost.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1000000000000000000".into())), &[]));
m
});
}
let mut timestamp: Value = self.parse8601(self.safe_string_k(trade.clone(), "executedAt", &[]));
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(trade.clone(), "settlementId", &[]));
m.insert("order".to_string(), order);
m.insert("timestamp".to_string(), timestamp.clone());
m.insert("datetime".to_string(), self.iso8601(timestamp));
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("type".to_string(), self.safe_string_k(party.clone(), "type", &[]));
m.insert("side".to_string(), side);
m.insert("takerOrMaker".to_string(), self.safe_string_k(party, "takerOrMaker", &[]));
m.insert("price".to_string(), self.parse_number(priceStr, &[]));
m.insert("amount".to_string(), self.parse_number(amountStr, &[]));
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), fee);
m.insert("info".to_string(), self.omit(trade, Value::Str("partyToParse".into()), &[]));
m
}), &[]);
Value::Null
}
/*
* @method
* @name predictfun#setSandboxMode
* @description switches between BNB mainnet and the BNB testnet
* @param {bool} enable whether to use the testnet
* @returns {undefined}
*/
pub fn set_sandbox_mode(&mut self, mut enable: Value) {
// read before the flag is overwritten: only an actual switch touches the token, so calling
// this twice with the same value is a no-op rather than a forced re-authentication
let mut wasSandbox: Value = self.safe_bool_k(self.options.clone(), "sandboxMode", &[Value::Bool(false)]);
self.super_set_sandbox_mode(enable.clone());
// the testnet is a different chain, so the EIP-712 chainId and every verifying contract
// change with it - and the venue serves the testnet without an api key
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(97) } else { Value::Int(56) })); }
if let Value::Dict(__d) = &mut self.requiredCredentials { std::sync::Arc::make_mut(__d).insert("apiKey".into(), Value::Bool(!is_true(&enable))); }
if (wasSandbox.as_bool() != enable.as_bool()) {
// a token minted for one host is not valid on the other, so the live one is set aside
// on the way in and taken back on the way out - a round trip through the sandbox then
// costs no re-authentication. the sandbox token is not kept: it dies with the switch
if enable.as_bool() == Some(true) {
{ let __be_tmp = self.safe_string_k(self.options.clone(), "jwtToken", &[]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("backupJwtToken".into(), __be_tmp); } }
{ let __be_tmp = self.safe_integer_k(self.options.clone(), "jwtTokenExpiresAt", &[Value::Int(0)]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("backupJwtTokenExpiresAt".into(), __be_tmp); } }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtToken".into(), Value::Null); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtTokenExpiresAt".into(), Value::Int(0)); }
} else {
{ let __be_tmp = self.safe_string_k(self.options.clone(), "backupJwtToken", &[]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtToken".into(), __be_tmp); } }
{ let __be_tmp = self.safe_integer_k(self.options.clone(), "backupJwtTokenExpiresAt", &[Value::Int(0)]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtTokenExpiresAt".into(), __be_tmp); } }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("backupJwtToken".into(), Value::Null); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("backupJwtTokenExpiresAt".into(), Value::Int(0)); }
}
}
}
/*
* @ignore
* @method
* @name predictfun#hashMessage
* @description hashes a message the way eth_personal_sign does, prefixing it before the keccak
* @param {string} message the message to hash
* @returns {string} the 0x prefixed hash
*/
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);
}
/*
* @ignore
* @method
* @name predictfun#signHash
* @description signs a 32 byte hash with the wallet's private key
* @param {string} hash the hash to sign
* @param {string} privateKey the wallet private key
* @returns {string} the 65 byte signature, 0x prefixed
*/
pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Option<String> {
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);
// assign before padStart so the php str_pad regex matches, it only handles a bare identifier
let mut rRaw: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
let mut sRaw: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
let mut r: Value = rRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
let mut s: Value = sRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
// ecrecover wants v in {27,28} while the raw recovery id is {0,1}
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)]), &[]);
// assign before toLowerCase so the php regex matches, it only handles a bare identifier
let mut signatureHex: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), r).into()), s).into()), v).into());
return (if let Some(__s) = signatureHex.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#authenticate
* @description exchanges a wallet signature for the JWT that authorises order actions, and caches it
* @see https://dev.predict.fun/get-auth-message-25326899e0
* @see https://dev.predict.fun/get-jwt-with-valid-signature-25326900e0
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {string} the JWT
*/
pub async fn authenticate(&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.walletAddress.clone() == Value::Null) || (self.privateKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" authenticate() requires a walletAddress and a privateKey".into()))));
}
let mut now: Value = self.milliseconds();
let mut cached: Value = self.safe_string_k(self.options.clone(), "jwtToken", &[]);
let mut expiresAt: Value = self.safe_integer_k(self.options.clone(), "jwtTokenExpiresAt", &[Value::Int(0)]);
// a token outlives its window silently: the venue answers 401 on every order action once
// it lapses, so re-issue before that rather than after the first failure
if (cached != Value::Null) && (now.as_f64().unwrap_or(f64::NAN) < expiresAt.as_f64().unwrap_or(f64::NAN)) {
return cached;
}
let mut messageResponse: Value = self.predictfun_get_v1_auth_message(&[params]).await;
//
// { "data": { "message": "Sign this message to authenticate ..." }, "success": true }
//
let mut messageData: Value = self.safe_dict_k(messageResponse, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut message: Option<String> = self.safe_string_k_opt(messageData, "message", &[]);
if (message.is_none()) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" authenticate() got an auth reply without the \"message\" field to sign".into()))));
}
let mut signature: Value = self.sign_hash(self.hash_message(message.clone().map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null), 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("signer".to_string(), self.walletAddress.clone());
m.insert("message".to_string(), message.map(Value::from).unwrap_or(Value::Null));
m.insert("signature".to_string(), signature);
m
});
let mut response: Value = self.predictfun_post_v1_auth(&[Value::Map(request)]).await;
//
// { "data": { "token": "eyJhbGciOi..." }, "success": true }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut token: Value = self.safe_string_k(data, "token", &[]);
if (token == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" authenticate() did not return a token".into()))));
}
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtToken".into(), token.clone()); }
// measured from before the round trip, so the cached window closes a little early rather
// than a little late
let mut tokenExpiresIn: Value = self.safe_integer_k(self.options.clone(), "tokenExpiresIn", &[Value::Int(86400000)]);
{ let __be_tmp = self.sum(&[now, tokenExpiresIn]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtTokenExpiresAt".into(), __be_tmp); } }
return token;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#signPredictfunOrder
* @description signs a contract order with the EIP-712 scheme of the exchange that settles it
* @param {object} order the contract order, as sent to the venue
* @param {bool} isNegRisk whether the market settles through the negative risk exchange
* @param {bool} isYieldBearing whether the market settles through the yield bearing exchange
* @returns {object} a dictionary with the order hash and the signature
*/
pub fn sign_predictfun_order(&self, mut order: Value, isNegRisk: bool, isYieldBearing: bool) -> Value {
// chainIdValue, not chainId - the php regex transpiler rewrites the substring "chainId"
// inside the domain literal to a local var, which would corrupt the domain type hash
let mut chainIdValue: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(56)]).as_i64();
let mut verifyingContract: Value = self.exchange_address(isNegRisk, isYieldBearing).map(Value::from).unwrap_or(Value::Null);
let mut domain: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("predict.fun CTF Exchange".into()));
m.insert("version".to_string(), Value::Str("1".into()));
m.insert("chainId".to_string(), Value::from(chainIdValue));
m.insert("verifyingContract".to_string(), verifyingContract);
m
});
let mut orderStruct: Value = Value::from(vec![Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("salt".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("maker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signer".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("taker".into()));
m.insert("type".to_string(), Value::Str("address".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("tokenId".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("makerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("takerAmount".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("expiration".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("nonce".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("feeRateBps".into()));
m.insert("type".to_string(), Value::Str("uint256".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("side".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
}), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("name".to_string(), Value::Str("signatureType".into()));
m.insert("type".to_string(), Value::Str("uint8".into()));
m
})]);
// ethEncodeStructuredData returns the EIP-712 digest, which is both what gets signed and
// the order hash the venue indexes the order by
let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("Order".to_string(), orderStruct);
m
}), order);
// ethEncodeStructuredData returns the 0x1901 || domainSeparator || structHash preimage,
// the digest that gets signed - and that the venue indexes the order by - is its keccak
let mut hash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(encoded, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), hash.clone());
m.insert("signature".to_string(), self.sign_hash(hash, self.privateKey.clone()).map(Value::from).unwrap_or(Value::Null));
m
});
Value::Null
}
/*
* @method
* @name predictfun#createOrder
* @description creates a LIMIT or MARKET order on a single prediction outcome token
* @see https://dev.predict.fun/create-an-order-32534694e0
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {string} type 'limit' or 'market'
* @param {string} side 'buy' or 'sell'
* @param {float} amount the number of outcome shares
* @param {float} [price] the price per share between 0 and 1, required for a limit order, and for a market order too unless warnOnMarketOrderWithoutPrice is turned off
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {int} [params.expiration] unix timestamp in seconds the limit order expires at
* @param {bool} [params.postOnly] reject the order if it would take liquidity
* @param {bool} [params.isFillOrKill] fill the order completely or cancel it
* @param {string} [params.slippageBps] slippage tolerance for a market order, in basis points
* @param {bool} [params.warnOnMarketOrderWithoutPrice] set to false to sign a priceless market order at 0.99 to buy or 0.01 to sell, the worst price it accepts
* @param {string} [params.selfTradePrevention] 'CANCEL_MAKER' | 'CANCEL_TAKER' | 'CANCEL_BOTH'
* @param {string} [params.salt] order salt, pin it to retry an order idempotently
* @param {string} [params.nonce] the maker's on chain nonce, defaults to 0
* @param {string} [params.feeRateBps] fee in basis points, read from the market when omitted
* @param {bool} [params.isNegRisk] override the market's negative risk flag
* @param {bool} [params.isYieldBearing] override the market's yield bearing flag
* @returns {object} an [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn create_order(&mut self, mut outcome: 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
}));
self.authenticate(&[]).await;
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
if (tokenId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder() could not resolve the on chain token id of ".into())).into()), outcome)));
}
let mut strategy: String = "LIMIT".to_string();
if (type_var.as_str() == Some("market")) {
strategy = "MARKET".to_string();
}
let mut isMarket: Value = (Value::Bool((strategy == "MARKET")));
if (!(matches!(&isMarket, Value::Bool(true)))) && (price == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a \"price\" argument for a limit order".into()))));
}
let mut isBuy: bool = side.as_str() == Some("buy");
// amounts cross the wire as collateral wei, the venue truncates the price to three
// significant digits and the quantity to five, so send what it will actually use
// the venue sizes an order from both legs and refuses anything else: a limitless style
// takerAmount sentinel of 1 is rejected as create_order_min_order_value_not_met (the order
// value is read off the taker leg) and signing at the maximum price of 1 is rejected as
// create_order_price_out_of_range (it wants 0 < price < 1)
let mut amountString: Value = self.number_to_string(amount);
let mut priceString: Value = self.number_to_string(price.clone());
let mut priceToProvide: Value = priceString.clone();
// read through the extractor rather than off the instance, so one call can opt in without
// reconfiguring the exchange - and so the key is taken out of params instead of riding
// along into the request body
let warnOnMarketOrderWithoutPriceparamsWarnOnMarketOrderWithoutPriceVariable: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("createOrder".into()), Value::Str("warnOnMarketOrderWithoutPrice".into()), &[Value::Bool(true)]).as_array().cloned().unwrap_or_default();
let mut warnOnMarketOrderWithoutPrice: Value = warnOnMarketOrderWithoutPriceparamsWarnOnMarketOrderWithoutPriceVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsWarnOnMarketOrderWithoutPrice: Value = warnOnMarketOrderWithoutPriceparamsWarnOnMarketOrderWithoutPriceVariable.get(1).cloned().unwrap_or(Value::Null);
if (price == Value::Null) {
// a priceless limit order already threw above, so this is a market order
if warnOnMarketOrderWithoutPrice.as_bool() == Some(true) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() market orders require a \"price\" argument. To use default values turn \"warnOnMarketOrderWithoutPrice\" off in options".into()))));
}
// it still has to name a price, so it takes the aggressive end of the range the venue
// allows: 0.99 crosses any ask, 0.01 is crossed by any bid. the fill happens at the
// book's own prices, this is only the worst price the order accepts - which is also
// the collateral the maker leg has to cover
priceToProvide = (if (isBuy) { self.number_to_string(self.safe_number_k(self.options.clone(), "marketBuyPrice", &[Value::Float(0.99)])) } else { self.number_to_string(self.safe_number_k(self.options.clone(), "marketSellPrice", &[Value::Float(0.01)])) });
}
let mut quantityWei: Value = crate::precise::Precise::stringMul(&amountString, &Value::Str("1000000000000000000".into()));
let mut priceWei: Value = crate::precise::Precise::stringMul(&priceToProvide, &Value::Str("1000000000000000000".into()));
// the collateral leg follows from the price and the size, exactly as for a limit order -
// both legs have to agree or the venue rejects the order
let mut costWei: Value = crate::precise::Precise::stringMul(&priceToProvide, &quantityWei);
let mut makerAmount: Value = quantityWei.clone();
let mut takerAmount: Value = costWei.clone();
if isBuy {
// a buy pays collateral for shares, a sell hands over shares for collateral
makerAmount = costWei;
takerAmount = quantityWei.clone();
}
let mut slippageBps: Value = self.safe_string_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "slippageBps", &[Value::Str("0".into())]);
if crate::precise::Precise::stringGt(&slippageBps, &Value::Str("0".into())).as_bool() == Some(true) {
if isBuy {
// widen what the taker is willing to pay, capped at one unit of collateral a share
makerAmount = crate::precise::Precise::stringMin(&crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&makerAmount, &crate::precise::Precise::stringAdd(&Value::Str("10000".into()), &slippageBps)), &Value::Str("10000".into())), &quantityWei);
} else {
takerAmount = crate::precise::Precise::stringMax(&crate::precise::Precise::stringDiv(&crate::precise::Precise::stringMul(&takerAmount, &crate::precise::Precise::stringSub(&Value::Str("10000".into()), &slippageBps)), &Value::Str("10000".into())), &Value::Str("0".into()));
}
}
// feeRateBps and the two exchange selectors live on the market row, not on the outcome
// row - signing with the wrong pair places the order under a different verifying contract
// and the venue answers create_order_hash_mismatch
let mut marketSymbol: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "market", &[]);
let mut marketObj: Value = self.safe_dict(self.markets.clone(), marketSymbol.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketRow: Value = self.safe_dict_k(marketObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketFeeRateBps: Value = self.safe_string_k(marketRow.clone(), "feeRateBps", &[Value::Str("200".into())]); // should be at least 200
let mut feeRateBps: Value = self.safe_string_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "feeRateBps", &[marketFeeRateBps]);
let mut marketIsNegRisk: Value = self.safe_bool_k(marketRow.clone(), "isNegRisk", &[Value::Bool(false)]);
let mut isNegRisk: bool = self.safe_bool_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "isNegRisk", &[marketIsNegRisk]).as_bool() == Some(true);
let mut marketIsYieldBearing: Value = self.safe_bool_k(marketRow, "isYieldBearing", &[Value::Bool(false)]);
let mut isYieldBearing: bool = self.safe_bool_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "isYieldBearing", &[marketIsYieldBearing]).as_bool() == Some(true);
let mut defaultExpiration: Value = self.safe_integer_k(self.options.clone(), "defaultExpiration", &[Value::Int(3600)]); // 1 hour
let mut expirationDelta: Value = defaultExpiration.clone();
let mut expiration: Value = self.safe_integer_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "expiration", &[]);
if (expiration == Value::Null) {
if matches!(&isMarket, Value::Bool(true)) {
expirationDelta = self.safe_integer_k(self.options.clone(), "marketOrderExpiration", &[defaultExpiration]);
}
let mut now: Value = self.seconds();
expiration = self.sum(&[now, expirationDelta]);
}
let mut nonce: Value = self.incrementing_nonce();
let mut salt: Value = self.safe_string_k(paramsWarnOnMarketOrderWithoutPrice.clone(), "salt", &[self.number_to_string(nonce)]);
let mut taker: String = "0x0000000000000000000000000000000000000000".to_string();
let takerOptionparamsTakerVariable: Vec<Value> = self.handle_option_and_params(paramsWarnOnMarketOrderWithoutPrice, Value::Str("createOrder".into()), Value::Str("taker".into()), &[Value::from(taker)]).as_array().cloned().unwrap_or_default();
let mut takerOption: Value = takerOptionparamsTakerVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsTaker: Value = takerOptionparamsTakerVariable.get(1).cloned().unwrap_or(Value::Null);
let mut contractOrder: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("salt".to_string(), salt);
m.insert("maker".to_string(), self.walletAddress.clone());
m.insert("signer".to_string(), self.walletAddress.clone());
m.insert("taker".to_string(), takerOption);
m.insert("tokenId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
m.insert("makerAmount".to_string(), self.decimal_to_precision(makerAmount, Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]));
m.insert("takerAmount".to_string(), self.decimal_to_precision(takerAmount, Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]));
m.insert("expiration".to_string(), expiration);
m.insert("nonce".to_string(), self.safe_string_k(paramsTaker.clone(), "nonce", &[Value::Str("0".into())]));
m.insert("feeRateBps".to_string(), feeRateBps);
m.insert("side".to_string(), (if isBuy { Value::Int(0) } else { Value::Int(1) }));
m.insert("signatureType".to_string(), Value::Int(0));
m
});
let mut signed: Value = self.sign_predictfun_order(Value::Map(contractOrder.clone()), isNegRisk, isYieldBearing);
let __ws_arg_7 = self.safe_string_k(signed.clone(), "hash", &[]);
let __ws_arg_8 = self.safe_string_k(signed, "signature", &[]);
let mut orderPayload: Value = self.extend(Value::Map(contractOrder), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), __ws_arg_7);
m.insert("signature".to_string(), __ws_arg_8);
m
})]);
let mut data: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("order".to_string(), orderPayload);
m.insert("pricePerShare".to_string(), self.decimal_to_precision(priceWei, Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]));
m.insert("strategy".to_string(), Value::str(strategy));
m
});
let mut postOnly: Value = self.safe_bool_k(paramsTaker.clone(), "isPostOnly", &[Value::Bool(false)]);
let postOnlyOptionparamsPostOnlyVariable: Vec<Value> = self.handle_post_only(isMarket, postOnly, &[paramsTaker]).as_array().cloned().unwrap_or_default();
let mut postOnlyOption: Value = postOnlyOptionparamsPostOnlyVariable.get(0).cloned().unwrap_or(Value::Null);
let mut paramsPostOnly: Value = postOnlyOptionparamsPostOnlyVariable.get(1).cloned().unwrap_or(Value::Null);
if postOnlyOption.as_bool() == Some(true) {
data.insert("isPostOnly".into(), postOnlyOption);
}
let mut timeInForce: Option<String> = self.safe_string_upper_k(paramsPostOnly.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
if (timeInForce.as_deref() == Some("FOK")) {
data.insert("isFillOrKill".into(), Value::Bool(true));
}
// documented, and the venue takes it inside data rather than as a top level key
let mut selfTradePrevention: Option<String> = self.safe_string_upper_k_opt(paramsPostOnly.clone(), "selfTradePrevention", &[]);
if (selfTradePrevention.is_some()) {
data.insert("selfTradePrevention".into(), selfTradePrevention.map(Value::from).unwrap_or(Value::Null));
}
// every param the method consumes itself has to come out, otherwise it survives into the
// extend below and is posted as a top level key next to 'data'
let mut paramsOmitted: Value = self.omit(paramsPostOnly, Value::from(vec![Value::Str("isPostOnly".into()), Value::Str("timeInForce".into()), Value::Str("isFillOrKill".into()), Value::Str("feeRateBps".into()), Value::Str("isNegRisk".into()), Value::Str("isYieldBearing".into()), Value::Str("slippageBps".into()), Value::Str("salt".into()),
Value::Str("nonce".into()), Value::Str("expiration".into()), Value::Str("selfTradePrevention".into()), Value::Str("taker".into())]), &[]);
// the JWT authorises the order, the api key only authorises the request
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("data".to_string(), Value::Map(data));
m
});
let __ws_arg_9 = self.extend(Value::Map(request), &[paramsOmitted]);
let mut response: Value = self.predictfun_post_v1_orders(&[__ws_arg_9]).await;
//
// {
// "data": {
// "code": "OK",
// "orderHash": "0x5ae1a7893b1a804530151dec3866cd0bb8ffe4e4c3640aca1b3ab5ef26c57747",
// "orderId": "415535",
// "removalLockedUntil": null
// },
// "success ": true
// }
//
let mut result: Value = self.safe_dict_k(response.clone(), "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(result, Value::Str("orderHash".into()), Value::Str("hash".into()), &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("info".to_string(), response);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("status".to_string(), Value::Null);
m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(outcomeObj, "event", &[]));
m.insert("type".to_string(), type_var);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.parse_number(priceString, &[]));
m.insert("amount".to_string(), self.parse_number(amountString, &[]));
m.insert("filled".to_string(), Value::Null);
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), Value::Null);
m.insert("fee".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m
}), &[]);
Value::Null
}
/*
* @method
* @name predictfun#fetchPositions
* @description fetches the outcome shares the wallet holds
* @see https://dev.predict.fun/get-positions-32675933e0
* @see https://dev.predict.fun/get-positions-by-address-32675934e0
* @param {string[]} [outcomes] unified outcome handles to keep, all of them when omitted
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.address] read another wallet's positions, which needs no JWT
* @param {string} [params.marketId] only positions on this market
* @param {bool} [params.isResolved] only resolved, or only unresolved, positions
* @param {string} [params.sort] 'AMOUNT_DESC' | 'EVENT_BLOCK_ASC' | 'EVENT_BLOCK_DESC' | 'SHARES_VALUE_DESC' | 'RETURN_DESC'
* @param {int} [params.first] the maximum number of positions to return
* @param {string} [params.after] cursor from a previous response
* @returns {object[]} a list of [position structures](https://docs.ccxt.com/#/?id=position-structure)
*/
pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
let mut outcomes = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomesLength: i64 = 0;
if (outcomes != Value::Null) {
outcomesLength = outcomes.len() as i64;
self.load_outcomes(&[outcomes.clone()]).await;
}
let mut address: Option<String> = self.safe_string_k_opt(params.clone(), "address", &[]);
let mut response: Value = Value::Null;
if (address.is_some()) {
// the by-address endpoint reads any wallet and is happy with just the api key
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("address".to_string(), address.clone().map(Value::from).unwrap_or(Value::Null));
m
});
let mut rest: Value = self.omit(params.clone(), Value::Str("address".into()), &[]);
let __ws_arg_10 = self.extend(Value::Map(request), &[rest]);
response = self.predictfun_get_v1_positions_address(&[__ws_arg_10]).await;
} else {
// the JWT is what names the wallet whose positions come back
self.authenticate(&[]).await;
response = self.predictfun_get_v1_positions(&[params]).await;
}
//
// {
// "cursor": "eyJtYXJrZXRJZCI6MjAzMjU3OCwib3V0Y29tZUlkIjo0MDAyOTQ3fQ==",
// "data": [
// {
// "id": "eyJtYXJrZXRJZCI6MjAzMjU4MSwib3V0Y29tZUlkIjo0MDAyOTUyfQ==",
// "amount": "11819508771929824562",
// "averageBuyPriceUsd": "0.57",
// "pnlUsd": 0,
// "valueUsd": 6.74,
// "market": { "id": 2032581, "categorySlug": "btc-updown-5m-1788776400", "status": "REGISTERED", "tradingStatus": "OPEN" },
// "outcome": {
// "indexSet": 1,
// "name": "Up",
// "onChainId": "104613341090911893615899927839535241203421132680281479852748534361460565051967",
// "status": null,
// "bestBid": { "price": 0.57, "size": 192.88842738205366 },
// "bestAsk": { "price": 0.58, "size": 58 }
// }
// }
// ],
// "success": true
// }
//
let mut rows: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
if (((outcomesLength as f64) == 0.0)) {
return self.parse_prediction_positions(rows.clone(), &[]);
}
let mut parsed: Vec<Value> = self.parse_prediction_positions(rows, &[]).as_array().cloned().unwrap_or_default();
// the venue filters by marketId only, so a set of outcome handles is applied here
let mut wanted: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut wantedOutcomes: Value = self.to_array(outcomes);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1476: bool = true;
while { if !__for_first_1476 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1476 = false; i.as_f64().unwrap_or(f64::NAN) < (outcomesLength as f64) } {
let mut outcomeObj: Value = self.outcome(self.safe_string(wantedOutcomes.clone(), i.clone(), &[]));
let mut wantedId: Value = self.safe_string_k(outcomeObj, "outcomeId", &[Value::Str("".into())]);
if let Value::Dict(__d) = &mut wanted { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&wantedId), Value::Bool(true)); }
}
}
let mut result: Vec<Value> = Vec::new();
let mut parsedLength: f64 = ((parsed.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1477: bool = true;
while { if !__for_first_1477 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1477 = false; i.as_f64().unwrap_or(f64::NAN) < parsedLength } {
let mut position: Value = parsed.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut outcomeId: Option<String> = self.safe_string_k_opt(position.clone(), "outcomeId", &[]);
if (outcomeId.is_some()) && (matches!((&wanted, &outcomeId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
result.push(position);
}
}
}
return Value::from(result);
Value::Null
}
/*
* @method
* @name predictfun#fetchPosition
* @description fetches the shares the wallet holds of a single outcome
* @see https://dev.predict.fun/get-positions-32675933e0
* @param {string} outcome unified outcome handle, or an outcome token id
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.address] read another wallet's position, which needs no JWT
* @returns {object} a [position structure](https://docs.ccxt.com/#/?id=position-structure)
*/
pub async fn fetch_position(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// scope the call to the outcome's market so the wallet's other positions are not paged through
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("marketId".to_string(), self.safe_string_k(info, "marketId", &[]));
m
});
let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
let mut positions: Value = self.fetch_positions(&[Value::from(vec![outcome]), __ws_arg_11]).await;
return self.safe_dict(positions, Value::Int(0), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parsePredictionPosition
* @description parses a raw position row into the unified position structure
* @param {object} position the raw position row
* @param {object} [market] not used by predictfun parsePredictionPosition
* @returns {object} a [position structure](https://docs.ccxt.com/#/?id=position-structure)
*/
pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
let mut rawOutcome: Value = self.safe_dict_k(position.clone(), "outcome", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rawMarket: Value = self.safe_dict_k(position.clone(), "market", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut tokenId: Option<String> = self.safe_string_k_opt(rawOutcome.clone(), "onChainId", &[]);
let mut outcomeObj: Value = self.outcome_for_token(tokenId.clone().map(Value::from).unwrap_or(Value::Null), &[market]);
// shares are collateral wei, the usd figures come back already scaled
let mut contracts: Value = crate::precise::Precise::stringDiv(&self.safe_string_k(position.clone(), "amount", &[]), &Value::Str("1000000000000000000".into()));
let mut entryPrice: Option<String> = self.safe_string_k_opt(position.clone(), "averageBuyPriceUsd", &[]);
let mut notional: Option<String> = self.safe_string_k_opt(position.clone(), "valueUsd", &[]);
let mut pnl: Option<String> = self.safe_string_k_opt(position.clone(), "pnlUsd", &[]);
// what the shares cost, which is also the collateral committed to the position
let mut collateral: Value = crate::precise::Precise::stringMul(&entryPrice.clone().map(Value::from).unwrap_or(Value::Null), &contracts);
let mut markPrice: Value = Value::Null;
if (notional.is_some()) && (contracts != Value::Null) && crate::precise::Precise::stringGt(&contracts, &Value::Str("0".into())).as_bool() == Some(true) {
markPrice = crate::precise::Precise::stringDiv(¬ional.clone().map(Value::from).unwrap_or(Value::Null), &contracts);
}
let mut percentage: Value = Value::Null;
if (pnl.is_some()) && (collateral != Value::Null) && crate::precise::Precise::stringGt(&collateral, &Value::Str("0".into())).as_bool() == Some(true) {
percentage = crate::precise::Precise::stringMul(&crate::precise::Precise::stringDiv(&pnl.clone().map(Value::from).unwrap_or(Value::Null), &collateral), &Value::Str("100".into()));
}
// a settled outcome reports WON or LOST, an open one leaves the field null - and the
// market can read RESOLVED while the outcome has not been marked yet, so the two are
// tracked apart: the position is resolved, but which side won is not yet known
let mut outcomeStatus: Option<String> = self.safe_string_k(rawOutcome.clone(), "status", &[]).as_str().map(str::to_owned);
let mut marketStatus: Option<String> = self.safe_string_k(rawMarket, "status", &[]).as_str().map(str::to_owned);
let mut settled: bool = (outcomeStatus.as_deref() == Some("WON")) || (outcomeStatus.as_deref() == Some("LOST"));
let mut resolved: bool = settled || (marketStatus.as_deref() == Some("RESOLVED")) || (marketStatus.as_deref() == Some("SETTLED"));
let mut won: Value = Value::Null;
let mut settleFraction: Value = Value::Null;
let mut payout: Value = Value::Null;
if settled {
won = (Value::Bool(outcomeStatus.as_deref() == Some("WON")));
settleFraction = (if (won).as_bool() == Some(true) { Value::Str("1".into()) } else { Value::Str("0".into()) });
// a winning share redeems for one unit of collateral, a losing one for nothing
payout = (if (won).as_bool() == Some(true) { contracts.clone() } else { Value::Str("0".into()) });
}
// pnl is realized once the market has resolved, unrealized while it is still trading
let mut realizedPnl: Value = Value::Null;
let mut unrealizedPnl: Value = pnl.clone().map(Value::from).unwrap_or(Value::Null);
if resolved {
realizedPnl = pnl.map(Value::from).unwrap_or(Value::Null);
unrealizedPnl = Value::Null;
}
return self.safe_prediction_position(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("contracts".to_string(), self.parse_number(contracts, &[]));
m.insert("contractSize".to_string(), Value::Int(1));
m.insert("side".to_string(), Value::Str("long".into()));
m.insert("notional".to_string(), self.parse_number(notional.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("unrealizedPnl".to_string(), self.parse_number(unrealizedPnl, &[]));
m.insert("realizedPnl".to_string(), self.parse_number(realizedPnl, &[]));
m.insert("collateral".to_string(), self.parse_number(collateral, &[]));
m.insert("entryPrice".to_string(), self.parse_number(entryPrice.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("markPrice".to_string(), self.parse_number(markPrice, &[]));
m.insert("lastPrice".to_string(), Value::Null);
m.insert("percentage".to_string(), self.parse_number(percentage, &[]));
m.insert("resolved".to_string(), Value::Bool(resolved));
m.insert("won".to_string(), won);
m.insert("settleFraction".to_string(), self.parse_number(settleFraction, &[]));
m.insert("payout".to_string(), self.parse_number(payout, &[]));
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[tokenId.map(Value::from).unwrap_or(Value::Null)]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[self.safe_string_upper(rawOutcome, Value::Str("name".into()), &[])]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(outcomeObj, "event", &[]));
m.insert("info".to_string(), position);
m
}));
Value::Null
}
/*
* @method
* @name predictfun#cancelOrder
* @description removes one of your own orders from the order book
* @see https://dev.predict.fun/remove-orders-by-hash-38139973e0
* @param {string} id the order hash, as returned by createOrder
* @param {string} [outcome] unified outcome handle the order belongs to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut orders: Value = self.cancel_orders(Value::from(vec![id.clone()]), &[outcome, params]).await;
let mut order: Value = self.safe_dict(orders, Value::Int(0), &[]);
if (order == Value::Null) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrder() could not remove ".into())).into()), id)));
}
return order;
Value::Null
}
/*
* @method
* @name predictfun#cancelOrders
* @description removes several of your own orders from the order book, up to a hundred at a time
* @see https://dev.predict.fun/remove-orders-by-hash-38139973e0
* @param {string[]} ids the order hashes, as returned by createOrder
* @param {string} [outcome] unified outcome handle the orders belong to
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
let mut idsLength: f64 = ((ids.len() as i64) as f64);
if (idsLength == 0.0) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() requires at least one order hash".into()))));
}
if idsLength > ((100i64) as f64) {
panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() takes at most 100 order hashes per call".into()))));
}
// the JWT identifies the signer whose orders may be pulled
self.authenticate(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("data".to_string(), Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("hashes".to_string(), ids);
m
}));
m
});
// this only pulls the orders off the book, it does not cancel them on chain
let __ws_arg_12 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_post_v1_orders_remove_by_hash(&[__ws_arg_12]).await;
//
// {
// "removed": [ "0xebf11bdff189b8609c9ae66bebb20b94742865a2d94970856f3fb6b0896f9ec0" ],
// "rejected": [],
// "noop": [ "0x00de1b3b4d8647c371022c3b952c82d89298ed3746d4677e582ef9808bbdc6cf" ],
// "success": true
// }
//
let mut rejected: Value = self.safe_list_k(response.clone(), "rejected", &[Value::from(vec![])]);
let mut rejectedLength: f64 = ((rejected.len() as i64) as f64);
if rejectedLength > ((0i64) as f64) {
panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() was refused for ".into())).into()), json_stringify(&rejected))));
}
// the venue reports hashes only, so each one becomes a row the shared order parser can
// read: it takes the hash off orderHash and the status through parseOrderStatus
let mut removed: Vec<Value> = self.safe_list_k(response.clone(), "removed", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut noop: Vec<Value> = self.safe_list_k(response.clone(), "noop", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
let mut rows: Vec<Value> = Vec::new();
let mut removedLength: f64 = ((removed.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1478: bool = true;
while { if !__for_first_1478 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1478 = false; i.as_f64().unwrap_or(f64::NAN) < removedLength } {
rows.push(self.extend(response.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderHash".to_string(), removed.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m.insert("status".to_string(), Value::Str("CANCELLED".into()));
m
})]));
}
}
let mut noopLength: f64 = ((noop.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1479: bool = true;
while { if !__for_first_1479 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1479 = false; i.as_f64().unwrap_or(f64::NAN) < noopLength } {
// accepted, but nothing was resting to pull: the order had already filled, expired,
// was never booked, or had been removed before - so the status is left unknown
rows.push(self.extend(response.clone(), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("orderHash".to_string(), noop.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
m
})]));
}
}
return self.parse_prediction_orders(Value::from(rows), &[outcomeObj]);
Value::Null
}
/*
* @method
* @name predictfun#fetchOrder
* @description fetches one of your own orders by its hash
* @see https://dev.predict.fun/get-order-by-hash-25326901e0
* @param {string} id the order hash
* @param {string} [outcome] unified outcome handle the order belongs to, resolved from the order when omitted
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} an [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.authenticate(&[]).await;
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
// the JWT identifies the wallet whose orders can be read
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("hash".to_string(), id);
m
});
let __ws_arg_13 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_get_v1_orders_hash(&[__ws_arg_13]).await;
//
// {
// "data": {
// "amount": "10000000000000000000",
// "amountFilled": "0",
// "currency": "USDT",
// "id": "415537",
// "isNegRisk": false,
// "isYieldBearing": true,
// "marketId": 2004048,
// "order": {
// "expiration": 1788717567,
// "feeRateBps": "200",
// "hash": "0xd0933a7528d1f4d8f82861a097a8e44298806f072a76bc9ec9c423707c94dfe7",
// "maker": "0x78C7b44105eB616B48d4A4328D4Ded1c3B53AF31",
// "makerAmount": "5000000000000000000",
// "nonce": "0",
// "salt": "1788713967425",
// "side": 0,
// "signature": "0x019cfd569d6d678a5ba900d43d93dfd55b3ef98c38d5b9bd243ac356a1fbffaa351e417d534195aa43bf20f07c6b82c25e7c49591f7c74565c3b9fa75b298bbb1c",
// "signatureType": 0,
// "signer": "0x78C7b44105eB616B48d4A4328D4Ded1c3B53AF31",
// "taker": "0x0000000000000000000000000000000000000000",
// "takerAmount": "10000000000000000000",
// "tokenId": "21794117812663370870023674333212505719146120894214542748572818978538793884650"},
// "rewardEarningRate": 0,
// "status": "CANCELLED",
// "strategy": "LIMIT"
// },
// "success": true
// }
//
let mut data: Value = self.safe_dict_k(response, "data", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
return self.parse_prediction_order(data, &[outcomeObj]);
Value::Null
}
/*
* @method
* @name predictfun#fetchOpenOrders
* @description fetches your own orders that are still resting on the book (only limit orders can be fetched)
* @see https://dev.predict.fun/get-orders-25326902e0
* @param {string} [outcome] unified outcome handle to filter by, all outcomes when omitted
* @param {int} [since] not used by predictfun fetchOpenOrders, the venue returns no order timestamps
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.after] cursor from a previous response, the venue pages back from the newest order
* @returns {object[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("OPEN".into()));
m
});
let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
return self.fetch_orders_helper(&[outcome, since, limit, __ws_arg_14]).await;
Value::Null
}
/*
* @method
* @name predictfun#fetchClosedOrders
* @description fetches your own orders that filled (only limit orders can be fetched)
* @see https://dev.predict.fun/get-orders-25326902e0
* @param {string} [outcome] unified outcome handle to filter by, all outcomes when omitted
* @param {int} [since] not used by predictfun fetchClosedOrders, the venue returns no order timestamps
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.after] cursor from a previous response, the venue pages back from the newest order
* @returns {object[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_closed_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = 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
}));
// the venue's status filter is an enum of OPEN and FILLED only - expired and cancelled
// orders cannot be asked for, so a closed order here means one that filled
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("status".to_string(), Value::Str("FILLED".into()));
m
});
let __ws_arg_15 = self.extend(Value::Map(request), &[params]);
return self.fetch_orders_helper(&[outcome, since, limit, __ws_arg_15]).await;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#fetchOrdersHelper
* @description fetches your own orders - the venue answers with the open ones unless a status is named, so each public method passes its own
* @see https://dev.predict.fun/get-orders-25326902e0
* @param {string} [outcome] unified outcome handle to filter by, all outcomes when omitted
* @param {int} [since] not used by predictfun, the venue returns no order timestamps
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @param {string} [params.status] 'OPEN' | 'FILLED' | 'EXPIRED' | 'CANCELLED'
* @param {string} [params.after] cursor from a previous response, the venue pages back from the newest order
* @returns {object[]} a list of [order structures](https://docs.ccxt.com/#/?id=order-structure)
*/
pub async fn fetch_orders_helper(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut outcomeObj: Value = Value::Null;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
outcomeObj = self.outcome(outcome.clone());
}
// the JWT identifies the wallet whose orders are returned
self.authenticate(&[]).await;
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
let __ws_arg_16 = self.extend(Value::Map(request), &[params]);
let mut response: Value = self.predictfun_get_v1_orders(&[__ws_arg_16]).await;
//
// {
// "cursor": null,
// "data": [
// {
// "amount": "10000000000000000000",
// "amountFilled": "0",
// "currency": "USDT",
// "id": "3295357412",
// "isNegRisk": false,
// "isYieldBearing": true,
// "marketId": 2107,
// "order": {
// "expiration": 1788888638,
// "feeRateBps": "200",
// "hash": "0x620e0237aaf75a86facfaa6840cba9d3bff4bb7a9c5606ad404c2a65ffadf14d",
// "maker": "0x9050dfA063D1bE7cA711c750b18D51fDD13e90Ee",
// "makerAmount": "1000000000000000000",
// "nonce": "0",
// "salt": "1788885038954",
// "side": 0,
// "signature": "0x564ea556c53aa58d66497639e82723402fe40fe8214f35ce5963aa5e09fd72e752a35b6bdc616017a55cefd4d34a32005497a0ae324a7d6f30a4998d130b04e81b",
// "signatureType": 0,
// "signer": "0x9050dfA063D1bE7cA711c750b18D51fDD13e90Ee",
// "taker": "0x0000000000000000000000000000000000000000",
// "takerAmount": "10000000000000000000",
// "tokenId": "11755619521560507246941857733124673401539364429068333264940202564484253415073"
// },
// "rewardEarningRate": 0,
// "status": "OPEN",
// "strategy": "LIMIT"
// }
// ],
// "success": true
// }
//
let mut data: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
return self.parse_prediction_orders(data, &[outcomeObj, since, limit]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parsePredictionOrder
* @description parses a raw order, as returned by the create and the fetch endpoints, into a unified order
* @param {object} order the raw order, with the signed contract order nested under 'order'
* @param {object} [market] the outcome the order belongs to, resolved from the token id when omitted
* @returns {object} an [order structure](https://docs.ccxt.com/#/?id=order-structure)
*/
pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
//
// fetchOrder
// {
// "amount": "10000000000000000000",
// "amountFilled": "0",
// "currency": "USDT",
// "id": "415537",
// "isNegRisk": false,
// "isYieldBearing": true,
// "marketId": 2004048,
// "order": {
// "expiration": 1788717567,
// "feeRateBps": "200",
// "hash": "0xd0933a7528d1f4d8f82861a097a8e44298806f072a76bc9ec9c423707c94dfe7",
// "maker": "0x78C7b44105eB616B48d4A4328D4Ded1c3B53AF31",
// "makerAmount": "5000000000000000000",
// "nonce": "0",
// "salt": "1788713967425",
// "side": 0,
// "signature": "0x019cfd569d6d678a5ba900d43d93dfd55b3ef98c38d5b9bd243ac356a1fbffaa351e417d534195aa43bf20f07c6b82c25e7c49591f7c74565c3b9fa75b298bbb1c",
// "signatureType": 0,
// "signer": "0x78C7b44105eB616B48d4A4328D4Ded1c3B53AF31",
// "taker": "0x0000000000000000000000000000000000000000",
// "takerAmount": "10000000000000000000",
// "tokenId": "21794117812663370870023674333212505719146120894214542748572818978538793884650"
// },
// "rewardEarningRate": 0,
// "status": "CANCELLED",
// "strategy": "LIMIT"
// }
//
let mut data: Value = self.safe_dict2(order.clone(), Value::Str("order".into()), Value::Str("data".into()), &[]);
// the fetch endpoints nest the hash inside the contract order, the create endpoint
// returns it at the top level as orderHash - accept either
let mut topLevelHash: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("hash".into()), Value::Str("orderHash".into()), &[]);
let mut orderHash: Value = self.safe_string_k(data.clone(), "hash", &[topLevelHash.map(Value::from).unwrap_or(Value::Null)]);
let mut tokenId: Option<String> = self.safe_string_k_opt(data.clone(), "tokenId", &[]);
let mut outcomeObj: Value = self.outcome_for_token(tokenId.clone().map(Value::from).unwrap_or(Value::Null), &[market]);
// the contract order carries the economics: a buy offers collateral for shares while a
// sell offers shares for collateral, so which leg is the size depends on the side
let mut rawSide: Option<String> = self.safe_string_k(data.clone(), "side", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (rawSide.as_deref() == Some("0")) || (rawSide.as_deref() == Some("Bid")) {
side = Value::Str("buy".into());
} else if (rawSide.as_deref() == Some("1")) || (rawSide.as_deref() == Some("Ask")) {
side = Value::Str("sell".into());
}
let mut makerAmount: Option<String> = self.safe_string_k_opt(data.clone(), "makerAmount", &[]);
let mut takerAmount: Option<String> = self.safe_string_k_opt(data, "takerAmount", &[]);
let mut amountWei: Value = makerAmount.clone().map(Value::from).unwrap_or(Value::Null);
let mut costWei: Value = takerAmount.clone().map(Value::from).unwrap_or(Value::Null);
if (side.as_str() == Some("buy")) {
amountWei = takerAmount.map(Value::from).unwrap_or(Value::Null);
costWei = makerAmount.map(Value::from).unwrap_or(Value::Null);
}
let mut amount: Value = crate::precise::Precise::stringDiv(&amountWei, &Value::Str("1000000000000000000".into()));
let mut cost: Value = crate::precise::Precise::stringDiv(&costWei, &Value::Str("1000000000000000000".into()));
let mut type_var: Option<String> = self.safe_string_lower_k(order.clone(), "strategy", &[]).as_str().map(str::to_owned);
let mut price: Value = Value::Null;
// orders show same takerAmount and makerAmount as it was when they were placed
// the price of market orders will be calculated incorrectly
// we can calculate price for limit orders only
if (type_var.as_deref() == Some("limit")) {
price = crate::precise::Precise::stringDiv(&cost, &amount);
}
let mut amountFilled: Option<String> = self.safe_string_k_opt(order.clone(), "amountFilled", &[]);
let mut filled: Value = crate::precise::Precise::stringDiv(&amountFilled.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1000000000000000000".into()));
let mut filledCost: Value = crate::precise::Precise::stringMul(&filled, &price);
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), orderHash);
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::Null);
m.insert("datetime".to_string(), Value::Null);
m.insert("status".to_string(), self.parse_order_status(self.safe_string_k(order.clone(), "status", &[])).map(Value::from).unwrap_or(Value::Null));
m.insert("type".to_string(), self.safe_string_lower_k(order.clone(), "strategy", &[]));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), price);
m.insert("amount".to_string(), amount);
m.insert("filled".to_string(), filled);
m.insert("remaining".to_string(), Value::Null);
m.insert("cost".to_string(), filledCost);
m.insert("fee".to_string(), Value::Null);
m.insert("postOnly".to_string(), self.safe_bool_k(order.clone(), "isPostOnly", &[]));
m.insert("trades".to_string(), Value::Null);
m.insert("outcome".to_string(), self.safe_outcome_symbol(tokenId.clone().map(Value::from).unwrap_or(Value::Null), &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[tokenId.map(Value::from).unwrap_or(Value::Null)]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(outcomeObj, "event", &[]));
m.insert("info".to_string(), order);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parseOrderStatus
* @description maps a venue order status onto the unified vocabulary
* @param {string} [status] the raw status
* @returns {string} the unified status
*/
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("OPEN".to_string(), Value::Str("open".into()));
m.insert("PENDING".to_string(), Value::Str("open".into()));
m.insert("MATCHED".to_string(), Value::Str("closed".into()));
m.insert("FILLED".to_string(), Value::Str("closed".into()));
m.insert("CANCELLED".to_string(), Value::Str("canceled".into()));
m.insert("CANCELED".to_string(), Value::Str("canceled".into()));
m.insert("EXPIRED".to_string(), Value::Str("expired".into()));
m.insert("REJECTED".to_string(), Value::Str("rejected".into()));
m
});
return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#handleErrors
* @description maps the venue's error slugs and messages onto the unified exceptions
* @param {int} code the http status code
* @param {string} reason the http status text
* @param {string} url the request url
* @param {string} method the http method
* @param {object} headers the response headers
* @param {string} body the raw response body
* @param {object} response the parsed response
* @param {object} requestHeaders the request headers
* @param {object} requestBody the request body
* @returns {undefined} nothing, it throws when the venue reported a failure
*/
pub fn handle_errors(&mut 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) {
return Value::Null;
}
let mut success: bool = self.safe_bool_k_opt(response.clone(), "success", &[Value::Bool(true)]).unwrap_or(true);
if success {
return Value::Null;
}
let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
// the message is matched first because it is the more specific of the two: several
// distinct failures share a generic slug, notably 'unauthorized', which the venue also
// returns for a hash belonging to another wallet, and 'not_found' for an unknown market
let mut message: Option<String> = self.safe_string_k_opt(response.clone(), "message", &[]);
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());
// the venue also answers 401 when the request was authorised but acted on someone else's
// order - that case is matched above and has already thrown, so reaching here with a 401
// means the credential itself was refused. drop the cached JWT, otherwise a token revoked
// or aged out before its window closes is replayed for the life of the process
if (code.as_f64() == Some(401.0)) {
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtToken".into(), Value::Null); }
if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("jwtTokenExpiresAt".into(), Value::Int(0)); }
}
let mut error: Option<String> = self.safe_string_k_opt(response, "error", &[]);
self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), error.map(Value::from).unwrap_or(Value::Null), feedback.clone());
// a 400 is a rejected request or a business rule, not a transport outage - the base would
// otherwise map the bare status onto a retryable network error
if (code.as_f64() == Some(400.0)) {
panic!("{}", crate::exchange_errors::bad_request(feedback));
}
panic!("{}", crate::exchange_errors::exchange_error(feedback));
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#exchangeAddress
* @description the exchange contract a market settles through, which is what its orders are signed against and what its collateral has to be approved to
* @param {bool} isNegRisk whether the market settles through the negative risk exchange
* @param {bool} isYieldBearing whether the market settles through the yield bearing exchange
* @returns {string} the contract address on the active chain
*/
pub fn exchange_address(&self, isNegRisk: bool, isYieldBearing: bool) -> Option<String> {
let mut chainIdValue: Value = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(56)]);
let mut exchanges: Value = self.safe_dict_k(self.options.clone(), "exchanges", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut byChain: Value = self.safe_dict(exchanges, self.number_to_string(chainIdValue), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut identifier: String = "CTF_EXCHANGE".to_string();
if isNegRisk && isYieldBearing {
identifier = "YIELD_BEARING_NEG_RISK_CTF_EXCHANGE".to_string();
} else if isNegRisk {
identifier = "NEG_RISK_CTF_EXCHANGE".to_string();
} else if isYieldBearing {
identifier = "YIELD_BEARING_CTF_EXCHANGE".to_string();
}
return self.safe_string(byChain, Value::from(identifier), &[]).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#conditionalTokensAddress
* @description the ERC-1155 contract a market's outcome shares live in, which is the contract a seller grants the approval on
* @param {bool} isNegRisk whether the market settles through the negative risk exchange
* @param {bool} isYieldBearing whether the market settles through the yield bearing exchange
* @returns {string} the contract address on the active chain
*/
pub fn conditional_tokens_address(&self, isNegRisk: bool, isYieldBearing: bool) -> Option<String> {
let mut chainIdValue: Value = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(56)]);
let mut tokens: Value = self.safe_dict_k(self.options.clone(), "conditionalTokens", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut byChain: Value = self.safe_dict(tokens, self.number_to_string(chainIdValue), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut identifier: String = "CONDITIONAL_TOKENS".to_string();
if isNegRisk && isYieldBearing {
identifier = "YIELD_BEARING_NEG_RISK_CONDITIONAL_TOKENS".to_string();
} else if isNegRisk {
identifier = "NEG_RISK_CONDITIONAL_TOKENS".to_string();
} else if isYieldBearing {
identifier = "YIELD_BEARING_CONDITIONAL_TOKENS".to_string();
}
return self.safe_string(byChain, Value::from(identifier), &[]).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#adapterAddress
* @description the negative risk adapter, which moves a seller's shares itself when a neg risk match mints or merges
* @param {bool} isYieldBearing whether the market settles through the yield bearing exchange
* @returns {string} the contract address on the active chain
*/
pub fn adapter_address(&self, isYieldBearing: bool) -> Option<String> {
let mut chainIdValue: Value = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(56)]);
let mut adapters: Value = self.safe_dict_k(self.options.clone(), "adapters", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut byChain: Value = self.safe_dict(adapters, self.number_to_string(chainIdValue), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut identifier: String = "NEG_RISK_ADAPTER".to_string();
if isYieldBearing {
identifier = "YIELD_BEARING_NEG_RISK_ADAPTER".to_string();
}
return self.safe_string(byChain, Value::from(identifier), &[]).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#signEvmTransaction
* @description builds and signs an EIP-1559 transaction, returning the raw signed hex
* @param {object} tx the transaction fields
* @param {string} privateKey the wallet private key
* @returns {string} the signed raw transaction
*/
pub fn sign_evm_transaction(&self, mut tx: Value, mut privateKey: Value) -> Value {
let mut accessList: Value = self.rlp_encode_list(Value::from(vec![]));
let mut fields: Value = Value::from(vec![self.rlp_encode_bytes(self.int_to_rlp_hex(self.safe_integer_k(tx.clone(), "chainId", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "nonce", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxPriorityFeePerGas", &[]))),
self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "maxFeePerGas", &[]))), self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "gasLimit", &[]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx.clone(), "to", &[]))),
self.rlp_encode_bytes(self.hex_to_rlp_bytes(self.safe_string_k(tx.clone(), "value", &[Value::Str("0x0".into())]))), self.rlp_encode_bytes(self.remove0x_prefix(self.safe_string_k(tx, "data", &[Value::Str("0x".into())]))), accessList]);
let mut payload: Value = Value::Str(format!("{}{}", Value::Str("02".into()), self.rlp_encode_list(fields.clone())).into());
let mut hashHex: Value = self.hash(self.base16_to_binary(payload, &[]), Value::Str("keccak".into()), &[Value::Str("hex".into())]);
let mut signature: Value = ecdsa(hashHex, self.remove0x_prefix(privateKey), Value::Str("secp256k1".into()), Value::Null);
let mut rHex: Value = self.safe_string_k(signature.clone(), "r", &[]);
let mut sHex: Value = self.safe_string_k(signature.clone(), "s", &[]);
rHex = self.pad_hex_to_even(rHex.clone());
sHex = self.pad_hex_to_even(sHex.clone());
let mut yParity: Value = self.safe_integer_k(signature, "v", &[]);
let mut signedFields: Value = self.array_concat(fields, Value::from(vec![self.rlp_encode_bytes(self.int_to_rlp_hex(yParity)), self.rlp_encode_bytes(rHex), self.rlp_encode_bytes(sHex)]));
return Value::Str(format!("{}{}", Value::Str("0x02".into()), self.rlp_encode_list(signedFields)).into());
Value::Null
}
/*
* @method
* @name predictfun#approve
* @description grants the on-chain approvals a wallet needs before it can trade. The buy side is the USDT allowance the exchange spends, without which every order is refused with create_order_insufficient_collateral_allowance; the sell side is the ERC-1155 approval over the outcome shares themselves. WITHOUT params.amount THE BUY SIDE GRANTS AN UNLIMITED (max uint256) ALLOWANCE, pass params.amount to bound it. sends real transactions signed with the privateKey and waits for each receipt, so the wallet needs BNB for gas
* @see https://dev.predict.fun/how-to-create-or-cancel-orders-679306m0
* @param {string} [outcome] unified outcome handle, used to pick the contracts its market settles through
* @param {object} [params] extra parameters
* @param {string} [params.side] 'buy' for the collateral allowance (the default), 'sell' for the outcome share approval
* @param {string} [params.spender] approve this contract instead of resolving it from the outcome
* @param {string} [params.token] the contract to grant on, defaults to USDT when buying and to the market's conditional tokens when selling
* @param {float} [params.amount] the allowance in USDT, unlimited when omitted, buy side only
* @param {bool} [params.approved] pass false to revoke instead of grant, sell side only
* @param {string} [params.owner] the token holder, defaults to walletAddress or the address of the privateKey
* @param {string} [params.rpcUrl] the rpc to broadcast through, defaults to the public endpoint for the chain
* @param {string} [params.gasLimit] gas limit as hex, defaults to 0x186a0
* @returns {object} the transaction receipt when buying, and the list of receipts when selling - a neg risk market needs two
*/
pub async fn approve(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = 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.privateKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" approve() requires a privateKey to sign the on-chain transaction".into()))));
}
let mut side: Option<String> = self.safe_string_lower_k(params.clone(), "side", &[Value::Str("buy".into())]).as_str().map(str::to_owned);
let mut chainId: Value = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(56)]);
let mut chainKey: Value = self.number_to_string(chainId.clone());
let mut rpcUrls: Value = self.safe_dict_k(self.options.clone(), "rpcUrls", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut rpcUrl: Value = self.safe_string_k(params.clone(), "rpcUrl", &[self.safe_string(rpcUrls, chainKey.clone(), &[])]);
let mut owner: Value = self.safe_string_k(params.clone(), "owner", &[self.walletAddress.clone()]);
if (owner == Value::Null) {
owner = self.eth_get_address_from_private_key(self.privateKey.clone(), &[]);
}
let mut gasLimit: Value = self.safe_string_k(params.clone(), "gasLimit", &[Value::Str("0x186a0".into())]);
// which of the four exchanges settles a market is a property of the market, so an
// approval granted for one of them is worth nothing on the others
let mut isNegRisk: bool = false;
let mut isYieldBearing: bool = false;
if (outcome != Value::Null) {
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut marketSymbol: Option<String> = self.safe_string_k_opt(outcomeObj, "market", &[]);
let mut marketObj: Value = self.safe_dict(self.markets.clone(), marketSymbol.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketRow: Value = self.safe_dict_k(marketObj, "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
isNegRisk = self.safe_bool_k(marketRow.clone(), "isNegRisk", &[Value::Bool(false)]).as_bool() == Some(true);
isYieldBearing = self.safe_bool_k(marketRow, "isYieldBearing", &[Value::Bool(false)]).as_bool() == Some(true);
}
if (side.as_deref() == Some("sell")) {
let mut ctfToken: Value = self.safe_string_k(params.clone(), "token", &[self.conditional_tokens_address(isNegRisk, isYieldBearing).map(Value::from).unwrap_or(Value::Null)]);
let mut operators: Value = Value::from(vec![]);
let mut explicitOperator: Option<String> = self.safe_string_k_opt(params.clone(), "spender", &[]);
if (explicitOperator.is_some()) {
if let Value::Arr(__a) = &mut operators { std::sync::Arc::make_mut(__a).push(explicitOperator.clone().map(Value::from).unwrap_or(Value::Null)); }
} else if (outcome == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" approve() requires an \"outcome\" to resolve the contracts to approve for selling, or an explicit \"spender\" parameter".into()))));
} else {
if let Value::Arr(__a) = &mut operators { std::sync::Arc::make_mut(__a).push(self.exchange_address(isNegRisk, isYieldBearing).map(Value::from).unwrap_or(Value::Null)); }
// a neg risk match mints and merges through the adapter, which moves the seller's
// shares itself, so approving the exchange alone leaves the sell side half open
if isNegRisk {
if let Value::Arr(__a) = &mut operators { std::sync::Arc::make_mut(__a).push(self.adapter_address(isYieldBearing).map(Value::from).unwrap_or(Value::Null)); }
}
}
if (rpcUrl == Value::Null) || (ctfToken == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" approve() could not resolve the \"rpcUrl\" or the conditional tokens for chain ".into())).into()), chainKey)));
}
let mut approved: bool = self.safe_bool_k_opt(params.clone(), "approved", &[Value::Bool(true)]).unwrap_or(true);
let mut approvedHex: String = "0000000000000000000000000000000000000000000000000000000000000000".to_string();
if approved {
approvedHex = "0000000000000000000000000000000000000000000000000000000000000001".to_string();
}
let mut receipts: Vec<Value> = Vec::new();
let mut operatorsLength: f64 = ((operators.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1480: bool = true;
while { if !__for_first_1480 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1480 = false; i.as_f64().unwrap_or(f64::NAN) < operatorsLength } {
let mut operatorAddress: Option<String> = self.safe_string_opt(operators.clone(), i.clone(), &[]);
if (operatorAddress.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" approve() could not resolve the operator to approve for chain ".into())).into()), chainKey)));
}
// setApprovalForAll(operator, approved) -> selector 0xa22cb465
let mut approvalData: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0xa22cb465".into()), self.pad_hex_address(operatorAddress.map(Value::from).unwrap_or(Value::Null))).into()), approvedHex).into());
// each receipt is awaited before the next transaction goes out, so the nonce the
// second one looks up already counts the first
let mut approvalHash: Value = self.send_evm_transaction(rpcUrl.clone(), chainId.clone(), owner.clone(), ctfToken.clone(), Value::Str("0x0".into()), approvalData, gasLimit.clone()).await;
let mut receipt: Value = self.wait_for_transaction_receipt(rpcUrl.clone(), approvalHash, &[]).await;
receipts.push(receipt);
}
}
return Value::from(receipts);
}
let mut collaterals: Value = self.safe_dict_k(self.options.clone(), "collateral", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut token: Value = self.safe_string_k(params.clone(), "token", &[self.safe_string(collaterals, chainKey.clone(), &[])]);
let mut spender: Value = self.safe_string_k(params.clone(), "spender", &[]);
if (spender == Value::Null) {
if (outcome == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" approve() requires an \"outcome\" to resolve the exchange to approve, or an explicit \"spender\" parameter".into()))));
}
spender = self.exchange_address(isNegRisk, isYieldBearing).map(Value::from).unwrap_or(Value::Null);
}
if (rpcUrl == Value::Null) || (token == Value::Null) || (spender == Value::Null) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" approve() could not resolve the \"rpcUrl\", the \"token\" or the \"spender\" for chain ".into())).into()), chainKey)));
}
let mut amountHex: Value = Value::Str("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".into());
let mut amount: Option<String> = self.safe_string_k_opt(params, "amount", &[]);
if (amount.is_some()) {
// the collateral has eighteen decimals, so the scaled amount runs past what a float
// can hold - it has to stay a string all the way into the bigint
let mut scaled: Value = crate::precise::Precise::stringMul(&amount.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1000000000000000000".into()));
let mut amountInt: Value = self.decimal_to_precision(scaled, Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
let mut amountBase16: Value = self.int_to_base16(self.convert_to_big_int(amountInt), &[]);
amountHex = amountBase16.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
}
// approve(spender, amount) -> selector 0x095ea7b3
let mut approveData: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x095ea7b3".into()), self.pad_hex_address(spender)).into()), amountHex).into());
let mut txHash: Value = self.send_evm_transaction(rpcUrl.clone(), chainId, owner, token, Value::Str("0x0".into()), approveData, gasLimit).await;
return self.wait_for_transaction_receipt(rpcUrl, txHash, &[]).await;
Value::Null
}
/*
* @method
* @name predictfun#watchOrderBook
* @description subscribes to the live order book of an outcome and returns it as it updates
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} outcome unified outcome handle
* @param {int} [limit] the maximum number of price levels to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
*/
pub async fn watch_order_book(&mut self, mut outcome: 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
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Option<String> = self.safe_string_k_opt(info, "marketId", &[]);
if (marketId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" watchOrderBook() could not resolve the market id of ".into())).into()), outcome)));
}
let mut outcomeHandle: Value = self.safe_outcome_symbol(Value::Null, &[outcomeObj]);
// the venue publishes one book per market, quoted on the yes side, and the no side is its
// complement - so a single subscription serves both outcomes and each waits on its own hash
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("predictOrderbook/".into()), marketId.clone().map(Value::from).unwrap_or(Value::Null)).into());
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcomeHandle).into());
let mut requestId: Value = self.request_id();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("subscribe".into()));
m.insert("requestId".to_string(), requestId.clone());
m.insert("params".to_string(), Value::from(vec![topic.clone()]));
m
});
// the subscription travels as a dict rather than the default boolean: a reply carries only
// the request id, so every registered subscription is indexed on it - and indexBy cannot
// look inside a boolean. both outcomes wait on this one topic, so a rejected request has to
// be able to release both of them
let mut subscription: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.number_to_string(requestId));
m.insert("topic".to_string(), topic.clone());
m.insert("subscribeHash".to_string(), topic.clone());
m.insert("messageHashes".to_string(), self.order_book_message_hashes(marketId.map(Value::from).unwrap_or(Value::Null)));
m
});
let mut url: Value = self.socket_url().map(Value::from).unwrap_or(Value::Null);
let __ws_arg_17 = self.extend(Value::Map(request), &[params]);
let mut orderbook: Value = self.watch(url, messageHash, &[__ws_arg_17, topic, Value::Map(subscription)]).await;
return orderbook.limit();
Value::Null
}
/*
* @method
* @name predictfun#unWatchOrderBook
* @description stops watching the order book of an outcome. the venue publishes one book per market and both of its outcomes read it, so the sibling outcome is released with it
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} outcome unified outcome handle
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} the venue's acknowledgement
*/
pub async fn un_watch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
self.load_outcome(outcome.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcome.clone());
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut marketId: Option<String> = self.safe_string_k_opt(info, "marketId", &[]);
if (marketId.is_none()) {
panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" unWatchOrderBook() could not resolve the market id of ".into())).into()), outcome)));
}
let mut topic: Value = Value::Str(format!("{}{}", Value::Str("predictOrderbook/".into()), marketId.clone().map(Value::from).unwrap_or(Value::Null)).into());
let mut outcomes: Vec<Value> = self.outcomes_by_market_id(marketId.clone().map(Value::from).unwrap_or(Value::Null)).as_array().cloned().unwrap_or_default();
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
let mut handles: Vec<Value> = Vec::new();
let mut subMessageHashes: Vec<Value> = Vec::new();
let mut messageHashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1481: bool = true;
while { if !__for_first_1481 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1481 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut handle: Option<String> = self.safe_string_opt(outcomes.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("outcome".into()), &[]);
if (handle.is_some()) {
handles.push(handle.clone().map(Value::from).unwrap_or(Value::Null));
subMessageHashes.push(Value::Str(format!("{}{}", Value::Str("orderbook::".into()), handle.clone().map(Value::from).unwrap_or(Value::Null)).into()));
messageHashes.push(Value::Str(format!("{}{}", Value::Str("unsubscribe::orderbook::".into()), handle.map(Value::from).unwrap_or(Value::Null)).into()));
}
}
}
let mut requestId: Value = self.request_id();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("unsubscribe".into()));
m.insert("requestId".to_string(), requestId.clone());
m.insert("params".to_string(), Value::from(vec![topic.clone()]));
m
});
// the acknowledgement carries the request id and nothing else - no topic - so the id is
// what ties the reply back to this subscription, which travels with it as the last argument
let mut subscription: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("id".to_string(), self.number_to_string(requestId));
m.insert("topic".to_string(), Value::Str("orderbook".into()));
m.insert("symbols".to_string(), Value::from(handles));
m.insert("subMessageHashes".to_string(), Value::from(subMessageHashes));
m.insert("messageHashes".to_string(), Value::from(messageHashes));
m.insert("subscribeHash".to_string(), topic);
m
});
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::orderbook::".into()), self.safe_outcome_symbol(Value::Null, &[outcomeObj])).into());
let mut url: Value = self.socket_url().map(Value::from).unwrap_or(Value::Null);
let __ws_arg_18 = self.extend(Value::Map(request), &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_18, messageHash.clone(), Value::Map(subscription)]).await;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#orderBookMessageHashes
* @description the hashes every waiter on a market's book is parked on, one per outcome
* @param {string} [marketId] the venue market id
* @returns {string[]} the message hashes
*/
pub fn order_book_message_hashes(&self, mut marketId: Value) -> Value {
let mut outcomes: Vec<Value> = self.outcomes_by_market_id(marketId).as_array().cloned().unwrap_or_default();
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
let mut hashes: Vec<Value> = Vec::new();
{
let mut i: Value = Value::Int(0);
let mut __for_first_1482: bool = true;
while { if !__for_first_1482 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1482 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut handle: Option<String> = self.safe_string_opt(outcomes.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("outcome".into()), &[]);
if (handle.is_some()) {
hashes.push(Value::Str(format!("{}{}", Value::Str("orderbook::".into()), handle.map(Value::from).unwrap_or(Value::Null)).into()));
}
}
}
return Value::from(hashes);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#handleSubscriptionError
* @description releases the one request the venue turned down and leaves the rest of the connection alone
* @param {Client} client the websocket client
* @param {object} message the raw rejection
* @param {object} subscription the subscription that request registered, empty when it cannot be attributed
*/
pub fn handle_subscription_error(&self, mut client: Value, mut message: Value, mut subscription: Value) {
let mut __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
let __subscription_empty = indexmap::IndexMap::new();
let subscription = subscription.as_map().unwrap_or(&__subscription_empty);
let mut rawError: Value = (match message.get("error") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut error = Value::from(crate::exchange_errors::exchange_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" subscribe request rejected ".into())).into()), json_stringify(&rawError))));
// watch () registers a subscription before it sends and only sends while the hash is still
// unregistered, so a rejected request has to take its own entry down - otherwise a retry
// would skip the send and wait forever on a topic the venue never accepted
let mut subscribeHash: Value = (match subscription.get("subscribeHash") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null });
if (subscribeHash != Value::Null) && (__ch.has_subscription(&subscribeHash)) {
__ch.remove_subscription(&subscribeHash);
}
let mut messageHashes: Value = (match subscription.get("messageHashes") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) });
if ((match subscription.get("topic") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str() == Some("walletEvents")) {
// watch () registers the wallet subscription once, for whichever watcher came first, so
// its list is a snapshot of that moment - a narrowed watcher that joined later is known
// only to the client. read the live waiters now, or those later callers would never be
// rejected and, with the subscription gone below, never retried or torn down either
messageHashes = self.wallet_event_message_hashes(client.clone(), &[]);
}
let mut messageHashesLength: f64 = ((messageHashes.len() as i64) as f64);
if (messageHashesLength == 0.0) {
panic!("{}", error);
}
{
let mut i: Value = Value::Int(0);
let mut __for_first_1483: bool = true;
while { if !__for_first_1483 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1483 = false; i.as_f64().unwrap_or(f64::NAN) < messageHashesLength } {
client.reject(&[Value::from(error.clone()), self.safe_string(messageHashes.clone(), i.clone(), &[Value::Str("".into())])]);
}
}
}
/*
* @ignore
* @method
* @name predictfun#handleUnSubscription
* @description tears down what an acknowledged unsubscribe leaves behind
* @param {Client} client the websocket client
* @param {object} subscription the subscription the acknowledged request id belongs to
*/
pub fn handle_un_subscription(&mut self, mut client: Value, mut subscription: Value) {
let mut __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &subscription { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut messageHashes: Vec<Value> = (match __pro_message.get("messageHashes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) }).as_array().cloned().unwrap_or_default();
let mut subMessageHashes: Value = (match __pro_message.get("subMessageHashes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
let mut messageHashesLength: f64 = ((messageHashes.len() as i64) as f64);
// one wallet hash stands for a family: 'orders' is what an unnarrowed caller waits on and
// 'orders::<outcome>' what a narrowed one waits on, so the base matches it as a prefix and
// releases both. the book path needs no such thing - it registers the full narrowed hash of
// every outcome of the market, and an exact match is what keeps a sibling market out of it
let mut isWalletTopic: Value = (Value::Bool((match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str() == Some("walletEvents")));
{
let mut i: Value = Value::Int(0);
let mut __for_first_1484: bool = true;
while { if !__for_first_1484 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1484 = false; i.as_f64().unwrap_or(f64::NAN) < messageHashesLength } {
self.clean_unsubscription(client.clone(), subMessageHashes.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), messageHashes.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[isWalletTopic.clone()]);
}
}
self.clean_cache(subscription);
// the subscription itself is keyed by the topic, which is what watchOrderBook registered -
// leaving it behind would make a later watch believe it is still subscribed
let mut subscribeHash: Option<String> = match __pro_message.get("subscribeHash").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
if (subscribeHash.is_some()) && (__ch.has_subscription(&subscribeHash.clone().map(Value::from).unwrap_or(Value::Null))) {
__ch.remove_subscription(&subscribeHash.clone().map(Value::from).unwrap_or(Value::Null));
}
// cleanCache drops a cache only when the subscription names that one topic, and the wallet
// topic backs two of them - so the caches it cannot reach are dropped here by the hashes
// the subscription does list. a stale cache left behind would be served to the next watcher
// as if it had just arrived
// the reset is delegated to the base rather than written here: assigning undefined to an
// inherited cache from a derived class is dropped outright by the go and c# transpilers,
// silently leaving those two languages with a stale cache
let mut subMessageHashesLength: f64 = ((subMessageHashes.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1485: bool = true;
while { if !__for_first_1485 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1485 = false; i.as_f64().unwrap_or(f64::NAN) < subMessageHashesLength } {
let mut subHash: Option<String> = self.safe_string_opt(subMessageHashes.clone(), i.clone(), &[]);
if (subHash.as_deref() == Some("orders")) || (subHash.as_deref() == Some("myTrades")) {
self.clean_cache(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("topic".to_string(), subHash.map(Value::from).unwrap_or(Value::Null));
m
}));
}
}
}
}
/*
* @method
* @name predictfun#watchOrders
* @description watches the wallet's own orders as the venue accepts, fills, expires or cancels them
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} [outcome] unified outcome handle to narrow the stream to
* @param {int} [since] timestamp in ms of the earliest order to return
* @param {int} [limit] the maximum number of orders to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut messageHash: Value = Value::Str("orders".into());
let mut outcomeResolved: Value = outcome.clone();
if (outcome != Value::Null) {
self.load_outcome(outcomeResolved.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcomeResolved.clone());
outcomeResolved = self.safe_outcome_symbol(Value::Null, &[outcomeObj]);
messageHash = Value::Str(format!("{}{}", Value::Str("orders::".into()), outcomeResolved).into());
} else {
// events arrive for whatever market the wallet traded, and the handler that resolves
// them is synchronous - so the universe is warmed here, while there is still a place to
// await. without it the first events land on a cold cache and every one of them buckets
// into the cache under the same undefined outcome. the call is idempotent and returns
// without a request once the cache is warm
self.load_outcomes(&[]).await;
}
let mut orders: Value = self.watch_wallet_events(messageHash, &[params]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = orders.get_limit(outcomeResolved.clone(), limitResolved.clone());
}
return self.filter_by_outcome_since_limit(orders, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name predictfun#watchMyTrades
* @description watches the wallet's own fills as they settle on chain
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} [outcome] unified outcome handle to narrow the stream to
* @param {int} [since] timestamp in ms of the earliest trade to return
* @param {int} [limit] the maximum number of trades to return
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut since = get_arg(optional_args, 1, Value::Null);
let mut limit = get_arg(optional_args, 2, Value::Null);
let mut params = get_arg(optional_args, 3, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut messageHash: Value = Value::Str("myTrades".into());
let mut outcomeResolved: Value = outcome.clone();
if (outcome != Value::Null) {
self.load_outcome(outcomeResolved.clone(), &[]).await;
let mut outcomeObj: Value = self.outcome(outcomeResolved.clone());
outcomeResolved = self.safe_outcome_symbol(Value::Null, &[outcomeObj]);
messageHash = Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcomeResolved).into());
} else {
// same as watchOrders (): the fills come from the one wallet topic and are resolved by
// a synchronous handler, so the cache is warmed here rather than on the first event
self.load_outcomes(&[]).await;
}
let mut trades: Value = self.watch_wallet_events(messageHash, &[params]).await;
let mut limitResolved: Value = limit;
if self.newUpdates.as_bool() == Some(true) {
limitResolved = trades.get_limit(outcomeResolved.clone(), limitResolved.clone());
}
return self.filter_by_outcome_since_limit(trades, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);
Value::Null
}
/*
* @method
* @name predictfun#unWatchOrders
* @description stops watching the wallet's orders. one wallet topic carries orders and fills alike, so both streams are released together
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} [outcome] not used by predictfun.unWatchOrders
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} the venue's acknowledgement
*/
pub async fn un_watch_orders(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_watch_wallet_events(Value::Str("orders".into()), &[params]).await;
Value::Null
}
/*
* @method
* @name predictfun#unWatchMyTrades
* @description stops watching the wallet's fills. one wallet topic carries orders and fills alike, so both streams are released together
* @see https://dev.predict.fun/subscription-topics-1915507m0
* @param {string} [outcome] not used by predictfun.unWatchMyTrades
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} the venue's acknowledgement
*/
pub async fn un_watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
let mut outcome = get_arg(optional_args, 0, Value::Null);
let mut params = get_arg(optional_args, 1, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
return self.un_watch_wallet_events(Value::Str("myTrades".into()), &[params]).await;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#walletEventsTopic
* @description the wallet topic, which carries the jwt inside the topic string itself
* @returns {string} the topic to subscribe to
*/
pub async fn wallet_events_topic(&mut self) -> Value {
// authenticate () serves the cached token until it expires, so subscribe and unsubscribe
// name the same topic. a re-minted token is a different topic, which is why the socket
// subscription is keyed by a stable hash instead of by this string - the token is a secret
// and has no business sitting in a subscription key
// the local is not called jwt: that is the name of a base method, and the regex transpiler
// rewrites such identifiers into self.jwt.clone(), which lands as a broken assignment in python
let mut walletToken: Value = self.authenticate(&[]).await;
return Value::Str(format!("{}{}", Value::Str("predictWalletEvents/".into()), walletToken).into());
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#watchWalletEvents
* @description subscribes to the wallet topic and waits on the hash the caller's method reads
* @param {string} messageHash the hash the caller waits on
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} whatever the channel resolves with
*/
pub async fn watch_wallet_events(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut topic: Value = self.wallet_events_topic().await;
let mut requestId: Value = self.request_id();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("subscribe".into()));
m.insert("requestId".to_string(), requestId.clone());
m.insert("params".to_string(), Value::from(vec![topic]));
m
});
let mut url: Value = self.socket_url().map(Value::from).unwrap_or(Value::Null);
let mut client: Value = self.client(&[url.clone()]);
let mut subscription: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.number_to_string(requestId));
m.insert("topic".to_string(), Value::Str("walletEvents".into()));
m.insert("subscribeHash".to_string(), Value::Str("walletEvents".into()));
m.insert("messageHashes".to_string(), self.wallet_event_message_hashes(client, &[messageHash.clone()]));
m
});
let __ws_arg_19 = self.extend(Value::Map(request), &[params]);
return self.watch(url, messageHash, &[__ws_arg_19, Value::Str("walletEvents".into()), Value::Map(subscription)]).await;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#walletEventMessageHashes
* @description the hashes every waiter on the wallet topic is parked on, the narrowed ones included
* @param {Client} client the websocket client
* @param {string} [messageHash] the hash this call is about to park on, not registered yet
* @returns {string[]} the message hashes
*/
pub fn wallet_event_message_hashes(&self, mut client: Value, optional_args: &[Value]) -> Value {
let __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let mut messageHash = get_arg(optional_args, 0, Value::Null);
// handleSubscriptionError rejects exactly this list, so a hash missing from it belongs to a
// caller the venue's refusal never reaches - watchOrders (outcome) would sit forever on a
// topic that was turned down. the unnarrowed pair is always listed, the narrowed ones are
// whatever is already live on this connection plus the hash watch () is about to register
let mut hashes: Vec<Value> = vec![Value::Str("orders".into()), Value::Str("myTrades".into())];
let mut futures: Vec<Value> = Value::Array(__ch.futures.clone().as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
let mut futuresLength: f64 = ((futures.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1486: bool = true;
while { if !__for_first_1486 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1486 = false; i.as_f64().unwrap_or(f64::NAN) < futuresLength } {
let mut future: Value = futures.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
if (Value::Int(future.as_str().and_then(|__s| __s.find("orders::")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) || (Value::Int(future.as_str().and_then(|__s| __s.find("myTrades::")).map(|__i| __i as i64).unwrap_or(-1)).as_f64() == Some(0.0)) {
hashes.push(future);
}
}
}
if (messageHash != Value::Null) && !(self.in_array(messageHash.clone(), Value::from(hashes.clone())).as_bool() == Some(true)) {
hashes.push(messageHash);
}
return Value::from(hashes);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#unWatchWalletEvents
* @description drops the wallet topic, releasing both the order and the fill stream
* @param {string} channel 'orders' or 'myTrades'
* @param {object} [params] extra parameters specific to the exchange API endpoint
* @returns {any} the venue's acknowledgement
*/
pub async fn un_watch_wallet_events(&mut self, mut channel: Value, optional_args: &[Value]) -> Value {
let mut params = get_arg(optional_args, 0, Value::Map({
let mut m = indexmap::IndexMap::new();
m
}));
let mut topic: Value = self.wallet_events_topic().await;
let mut requestId: Value = self.request_id();
let mut request: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("unsubscribe".into()));
m.insert("requestId".to_string(), requestId.clone());
m.insert("params".to_string(), Value::from(vec![topic]));
m
});
let mut subscription: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("unsubscribe".to_string(), Value::Bool(true));
m.insert("id".to_string(), self.number_to_string(requestId));
m.insert("topic".to_string(), Value::Str("walletEvents".into()));
m.insert("symbols".to_string(), Value::from(vec![]));
m.insert("subMessageHashes".to_string(), Value::from(vec![Value::Str("orders".into()), Value::Str("myTrades".into())]));
m.insert("messageHashes".to_string(), Value::from(vec![Value::Str("unsubscribe::orders".into()), Value::Str("unsubscribe::myTrades".into())]));
m.insert("subscribeHash".to_string(), Value::Str("walletEvents".into()));
m
});
let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("unsubscribe::".into()), channel).into());
let mut url: Value = self.socket_url().map(Value::from).unwrap_or(Value::Null);
let __ws_arg_20 = self.extend(Value::Map(request), &[params]);
return self.watch(url, messageHash.clone(), &[__ws_arg_20, messageHash.clone(), Value::Map(subscription)]).await;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#socketUrl
* @description the socket endpoint carrying the api key the venue demands on the handshake
* @returns {string} the url to connect to
*/
pub fn socket_url(&self) -> Option<String> {
let mut urls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut base: Option<String> = self.safe_string_k_opt(urls, "ws", &[]);
if (base.is_none()) {
panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", self.id.clone(), Value::Str(" does not have a sandbox websocket endpoint".into()))));
}
if (self.apiKey.clone() == Value::Null) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" requires an apiKey for all methods - the venue answers the socket handshake with a 401 without one".into()))));
}
return Value::Str(format!("{}{}", Value::Str(format!("{}{}", base.map(Value::from).unwrap_or(Value::Null), Value::Str("?apiKey=".into())).into()), self.apiKey.clone()).into()).as_str().map(str::to_owned);
}
/*
* @ignore
* @method
* @name predictfun#requestId
* @description a monotonic id the venue echoes back so a subscription reply can be matched to its request
* @returns {int} the next request id
*/
pub fn request_id(&self) -> Value {
self.lock_id(&[]);
let mut previous: Value = self.safe_integer_k(self.options.clone(), "requestId", &[Value::Int(0)]);
let mut next: Value = self.sum(&[previous, Value::Int(1)]);
if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("requestId".into(), next.clone()); }
self.unlock_id(&[]);
return next;
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#outcomeForToken
* @description resolves the outcome a row belongs to from its own token id, taking the caller's outcome only when it names that same token
* @param {string} [tokenId] the on chain token id the row carries
* @param {object} [market] the outcome the caller asked about
* @returns {object} the outcome object, or a stub keyed by the token id when it is not cached
*/
pub fn outcome_for_token(&self, mut tokenId: Value, optional_args: &[Value]) -> Value {
let mut market = get_arg(optional_args, 0, Value::Null);
// the list endpoints (orders, matches, positions) answer for the whole wallet rather than
// for the outcome asked about, so the caller's outcome is only a hint. safeOutcome falls
// back to it on any cache miss, which stamped the requested outcome onto rows from other
// markets - and the outcome filter afterwards then kept them, as they now matched
let mut hintId: Option<String> = self.safe_string_k_opt(market.clone(), "outcomeId", &[]);
if (tokenId == Value::Null) || (hintId.as_deref() == tokenId.as_str()) {
return self.safe_outcome(tokenId.clone(), &[market]);
}
return self.safe_outcome(tokenId, &[]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#outcomesByMarketId
* @description the cached outcomes that belong to one venue market id
* @param {string} [marketId] the venue market id
* @returns {object[]} the outcome objects
*/
pub fn outcomes_by_market_id(&self, mut marketId: Value) -> Value {
let mut result: Vec<Value> = Vec::new();
if (marketId == Value::Null) || (self.exchange.outcomes.clone() == Value::Null) {
return Value::from(result);
}
let mut cached: Value = self.exchange.outcomes.clone();
let mut handles: Vec<Value> = object_keys(&cached).as_array().cloned().unwrap_or_default();
let mut handlesLength: f64 = ((handles.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1487: bool = true;
while { if !__for_first_1487 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1487 = false; i.as_f64().unwrap_or(f64::NAN) < handlesLength } {
let mut outcomeObj: Value = get_value(&cached, &handles.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
if (self.safe_string_k(info, "marketId", &[]).as_str() == marketId.as_str()) {
result.push(outcomeObj);
}
}
}
return Value::from(result);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#handleOrderBook
* @description turns a book message into the two complementary outcome books of its market
* @param {Client} client the websocket client
* @param {object} message the raw message
*/
pub fn handle_order_book(&self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "type": "M",
// "topic": "predictOrderbook/2107",
// "data": {
// "asks": [
// [ 0.029, 1478.08 ],
// [ 0.03, 870.93 ]
// ],
// "bids": [
// [ 0.02, 1386.724081632653 ],
// [ 0.017, 2640.3371187742646 ]
// ],
// "lastOrderSettled": {
// "id": "3172327577",
// "kind": "LIMIT",
// "marketId": 2107,
// "outcome": "Yes",
// "price": "0.02",
// "side": "Bid"
// },
// "marketId": 2107,
// "orderCount": 62,
// "settlementsPending": {
// "asks": [
// [ 0.029, 0.14906 ]
// ],
// "bids": []
// },
// "updateTimestampMs": 1788953990223,
// "version": 1
// }
// }
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut marketId: Option<String> = self.safe_string_k_opt(data.clone(), "marketId", &[]);
let mut timestamp: Option<i64> = self.safe_integer_k(data.clone(), "updateTimestampMs", &[]).as_i64();
let mut rawAsks: Value = self.safe_list_k(data.clone(), "asks", &[Value::from(vec![])]);
let mut rawBids: Value = self.safe_list_k(data.clone(), "bids", &[Value::from(vec![])]);
// every message carries the whole book - the venue publishes no deltas - and the levels
// arrive already sorted, best first
let mut yesBids: Value = Value::from(vec![]);
let mut yesAsks: Value = Value::from(vec![]);
let mut noBids: Value = Value::from(vec![]);
let mut noAsks: Value = Value::from(vec![]);
let mut bidsLength: f64 = ((rawBids.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1488: bool = true;
while { if !__for_first_1488 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1488 = false; i.as_f64().unwrap_or(f64::NAN) < bidsLength } {
let mut bid: Value = self.safe_list(rawBids.clone(), i.clone(), &[]);
let mut bidPrice: Option<String> = self.safe_string_opt(bid.clone(), Value::Int(0), &[]);
let mut bidSize: Value = self.parse_number(self.safe_string(bid, Value::Int(1), &[]), &[]);
if let Value::Arr(__a) = &mut yesBids { std::sync::Arc::make_mut(__a).push(Value::from(vec![self.parse_number(bidPrice.clone().map(Value::from).unwrap_or(Value::Null), &[]), bidSize.clone()])); }
// a bid for yes at p is an offer of no at 1 - p
if let Value::Arr(__a) = &mut noAsks { std::sync::Arc::make_mut(__a).push(Value::from(vec![self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &bidPrice.clone().map(Value::from).unwrap_or(Value::Null)), &[]), bidSize])); }
}
}
let mut asksLength: f64 = ((rawAsks.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1489: bool = true;
while { if !__for_first_1489 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1489 = false; i.as_f64().unwrap_or(f64::NAN) < asksLength } {
let mut ask: Value = self.safe_list(rawAsks.clone(), i.clone(), &[]);
let mut askPrice: Option<String> = self.safe_string_opt(ask.clone(), Value::Int(0), &[]);
let mut askSize: Value = self.parse_number(self.safe_string(ask, Value::Int(1), &[]), &[]);
if let Value::Arr(__a) = &mut yesAsks { std::sync::Arc::make_mut(__a).push(Value::from(vec![self.parse_number(askPrice.clone().map(Value::from).unwrap_or(Value::Null), &[]), askSize.clone()])); }
if let Value::Arr(__a) = &mut noBids { std::sync::Arc::make_mut(__a).push(Value::from(vec![self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &askPrice.clone().map(Value::from).unwrap_or(Value::Null)), &[]), askSize])); }
}
}
let mut outcomes: Value = self.outcomes_by_market_id(marketId.clone().map(Value::from).unwrap_or(Value::Null));
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1490: bool = true;
while { if !__for_first_1490 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1490 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut outcomeObj: Value = self.safe_dict(outcomes.clone(), i.clone(), &[]);
let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut isYesOutcome: bool = self.safe_integer_k(outcomeInfo, "indexSet", &[]).as_f64() == Some(1.0);
let mut outcomeHandle: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcome", &[]);
if (outcomeHandle.is_some()) {
if !(matches!((&self.orderbooks, &outcomeHandle.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
{ let __be_tmp = self.order_book(&[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]); if let Value::Dict(__d) = &mut self.orderbooks.clone() { std::sync::Arc::make_mut(__d).insert(outcomeHandle.as_deref().unwrap_or("null").to_string(), __be_tmp); } }
}
let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcomeHandle.as_deref()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
let mut bids: Value = yesBids.clone();
let mut asks: Value = yesAsks.clone();
if !isYesOutcome {
bids = self.sort_by(noBids.clone(), Value::Int(0), &[Value::Bool(true)]);
asks = self.sort_by(noAsks.clone(), Value::Int(0), &[]);
}
orderbook.reset(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("bids".to_string(), bids);
m.insert("asks".to_string(), asks);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("outcome".to_string(), outcomeHandle.clone().map(Value::from).unwrap_or(Value::Null));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
m.insert("nonce".to_string(), self.safe_integer_k(data.clone(), "version", &[]));
m
}));
client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcomeHandle.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
}
}
/*
* @ignore
* @method
* @name predictfun#handleWalletEvent
* @description turns one wallet event into the order it describes, and into a trade when it settled
* @param {Client} client the websocket client
* @param {object} message the raw message
*/
pub fn handle_wallet_event(&mut self, mut client: Value, mut message: Value) {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
//
// {
// "type": "M",
// "topic": "predictWalletEvents/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
// "data": {
// "type": "orderTransactionSuccess",
// "orderId": "3420472350",
// "orderHash": "0x7d097327cc15754411b7ec3e3e074ff3e974394a75aa5c81fdf90b4e67e59c15",
// "settlementId": "01a08f55-d6f7-77e3-895e-81cf62d8aa09",
// "timestamp": 1789111162000,
// "walletAddress": "0xabababababababababababababababababababab",
// "isMaker": false,
// "fee": { "amountWei": "400000000000000", "type": "COLLATERAL" },
// "fill": {
// "executedPriceWei": "20000000000000000",
// "executedSizeWei": "1000000000000000000",
// "executedValueWei": "20000000000000000"
// },
// "details": {
// "categorySlug": "will-trump-acquire-greenland-before-2027",
// "marketId": 2107,
// "marketQuestion": "Will Trump acquire Greenland before 2027?",
// "outcome": "YES",
// "outcomeIndex": 1,
// "outcomeName": "Yes",
// "price": "0.010",
// "quantity": "1.000",
// "quantityFilled": "1.000",
// "quoteType": "ASK",
// "strategyType": "MARKET",
// "value": "0.01",
// "valueFilled": "0.01"
// }
// }
// }
//
// the details block is the same on every variant and is quoted in units, while fill and fee
// are quoted in wei. observed live: orderAccepted, orderMarketMatchPlan (which the venue
// sends but does not document), orderTransactionSubmitted, orderTransactionSuccess and
// orderCancelled - the latter arrives with the same envelope and no fill
//
let mut data: Value = (match message.get("data") { Some(__v) if matches!(__v, Value::Dict(_)) => __v.clone(), _ => Value::Map({
let mut m = indexmap::IndexMap::new();
m
}) });
let mut order: Value = self.parse_wallet_event_order(data.clone());
self.handle_wallet_event_order(client.clone(), order.clone());
// only a confirmed on-chain settlement is a trade: a submitted transaction has not landed
// yet and a failed one never did, so neither belongs in myTrades
let mut eventType: Option<String> = self.safe_string_k(data.clone(), "type", &[]).as_str().map(str::to_owned);
if (eventType.as_deref() == Some("orderTransactionSuccess")) {
self.handle_wallet_event_trade(client, data, order);
}
}
/*
* @ignore
* @method
* @name predictfun#handleWalletEventOrder
* @description stores the order a wallet event describes and wakes whoever waits on it
* @param {Client} client the websocket client
* @param {object} order the parsed order
*/
pub fn handle_wallet_event_order(&mut self, mut client: Value, mut order: Value) {
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &order { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
if (self.orders.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
self.orders = ArrayCacheByOutcomeById::new(limit);
}
let mut stored: Value = self.orders.clone();
stored.append(order);
client.resolve(&[stored.clone(), Value::Str("orders".into())]);
let mut outcomeHandle: Option<String> = match __pro_message.get("outcome").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
if (outcomeHandle.is_some()) {
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("orders::".into()), outcomeHandle.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
/*
* @ignore
* @method
* @name predictfun#handleWalletEventTrade
* @description stores the settled fill a wallet event carries and wakes whoever waits on it
* @param {Client} client the websocket client
* @param {object} event the raw event
* @param {object} order the order the same event was parsed into
*/
pub fn handle_wallet_event_trade(&mut self, mut client: Value, mut event: Value, mut order: Value) {
let mut trade: Value = self.parse_wallet_event_trade(event, order);
if (self.myTrades.clone() == Value::Null) {
let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
self.myTrades = ArrayCacheByOutcomeById::new(limit);
}
let mut stored: Value = self.myTrades.clone();
stored.append(trade.clone());
client.resolve(&[stored.clone(), Value::Str("myTrades".into())]);
let mut outcomeHandle: Option<String> = self.safe_string_k_opt(trade, "outcome", &[]);
if (outcomeHandle.is_some()) {
client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcomeHandle.map(Value::from).unwrap_or(Value::Null)).into())]);
}
}
/*
* @ignore
* @method
* @name predictfun#walletEventOutcome
* @description resolves the cached outcome a wallet event refers to, by market and outcome index
* @param {object} details the event's details block
* @returns {object} the outcome object, or a stub when the market is not cached
*/
pub fn wallet_event_outcome(&self, mut details: Value) -> Value {
let mut marketId: Option<String> = self.safe_string_k_opt(details.clone(), "marketId", &[]);
let mut outcomeIndex: Value = self.safe_integer_k(details.clone(), "outcomeIndex", &[]);
let mut outcomes: Vec<Value> = self.outcomes_by_market_id(marketId.clone().map(Value::from).unwrap_or(Value::Null)).as_array().cloned().unwrap_or_default();
let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
{
let mut i: Value = Value::Int(0);
let mut __for_first_1491: bool = true;
while { if !__for_first_1491 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1491 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
let mut candidate: Value = outcomes.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
let mut info: Value = self.safe_dict_k(candidate.clone(), "info", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut candidateIndexSet: Value = self.safe_integer_k(info, "indexSet", &[]);
if (candidateIndexSet.as_f64() == outcomeIndex.as_f64()) {
return candidate;
}
}
}
// the wallet stream reports every market the wallet ever touched, including ones outside
// the capped listing watchOrders () warms the cache from, so a miss survives that warm-up.
// the event does name its topic and its outcome, and the unified event handle and label are
// derived from exactly those two strings - so both are rebuilt here the way parseTopicMarket
// builds them. the market symbol and the token id are not: the first needs the topic's
// market count and the second the on-chain id, neither of which the event carries. they stay
// undefined rather than guessed - a handle that does not match the one the rest of the api
// reports is worse than none at all
let mut topicSlug: Option<String> = self.safe_string_k_opt(details.clone(), "categorySlug", &[]);
let mut eventHandle: Value = Value::Null;
if (topicSlug.is_some()) {
eventHandle = self.shorten_slug(topicSlug.map(Value::from).unwrap_or(Value::Null));
}
let mut label: Value = self.strip_price_formatting(self.safe_string_upper_k(details.clone(), "outcomeName", &[])).map(Value::from).unwrap_or(Value::Null);
return Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("outcome".to_string(), Value::Null);
m.insert("outcomeId".to_string(), Value::Null);
m.insert("market".to_string(), Value::Null);
m.insert("label".to_string(), label);
m.insert("event".to_string(), eventHandle);
m.insert("info".to_string(), details);
m
});
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parseWalletEventOrder
* @description parses a wallet event into the unified order it describes
* @param {object} event the raw event
* @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
*/
pub fn parse_wallet_event_order(&self, mut event: Value) -> Value {
//
// {
// "type": "orderTransactionSuccess",
// "orderId": "3420472350",
// "orderHash": "0x7d097327cc15754411b7ec3e3e074ff3e974394a75aa5c81fdf90b4e67e59c15",
// "settlementId": "01a08f55-d6f7-77e3-895e-81cf62d8aa09",
// "timestamp": 1789111162000,
// "walletAddress": "0xabababababababababababababababababababab",
// "isMaker": false,
// "fee": { "amountWei": "400000000000000", "type": "COLLATERAL" },
// "fill": {
// "executedPriceWei": "20000000000000000",
// "executedSizeWei": "1000000000000000000",
// "executedValueWei": "20000000000000000"
// },
// "details": {
// "categorySlug": "will-trump-acquire-greenland-before-2027",
// "marketId": 2107,
// "marketQuestion": "Will Trump acquire Greenland before 2027?",
// "outcome": "YES",
// "outcomeIndex": 1,
// "outcomeName": "Yes",
// "price": "0.010",
// "quantity": "1.000",
// "quantityFilled": "1.000",
// "quoteType": "ASK",
// "strategyType": "MARKET",
// "value": "0.01",
// "valueFilled": "0.01"
// }
// }
//
let mut details: Value = self.safe_dict_k(event.clone(), "details", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut outcomeObj: Value = self.wallet_event_outcome(details.clone());
let mut eventType: Option<String> = self.safe_string_k(event.clone(), "type", &[]).as_str().map(str::to_owned);
let mut amount: Option<String> = self.safe_string_k_opt(details.clone(), "quantity", &[]);
let mut filled: Option<String> = self.safe_string_k_opt(details.clone(), "quantityFilled", &[]);
// every variant names a state of one order, so the event type is the status
let mut status: Value = Value::Null;
if (eventType.as_deref() == Some("orderAccepted")) || (eventType.as_deref() == Some("orderMarketMatchPlan")) || (eventType.as_deref() == Some("orderTransactionSubmitted")) || (eventType.as_deref() == Some("orderTransactionFailed")) {
// orderMarketMatchPlan is not in the documented union but the venue does send it: the
// order is accepted and being matched, which is the same state the caller sees as open
status = Value::Str("open".into());
} else if (eventType.as_deref() == Some("orderNotAccepted")) {
status = Value::Str("rejected".into());
} else if (eventType.as_deref() == Some("orderExpired")) {
status = Value::Str("expired".into());
} else if (eventType.as_deref() == Some("orderCancelled")) {
status = Value::Str("canceled".into());
} else if (eventType.as_deref() == Some("orderTransactionSuccess")) {
// a settled fill closes the order only once nothing is left of it
status = Value::Str("open".into());
if (amount.is_some()) && (filled.is_some()) && !(crate::precise::Precise::stringLt(&filled.clone().map(Value::from).unwrap_or(Value::Null), &amount.clone().map(Value::from).unwrap_or(Value::Null)).as_bool() == Some(true)) {
status = Value::Str("closed".into());
}
}
let mut quoteType: Option<String> = self.safe_string_lower_k(details.clone(), "quoteType", &[]).as_str().map(str::to_owned);
let mut side: Value = Value::Null;
if (quoteType.as_deref() == Some("bid")) {
side = Value::Str("buy".into());
} else if (quoteType.as_deref() == Some("ask")) {
side = Value::Str("sell".into());
}
let mut remaining: Value = Value::Null;
if (amount.is_some()) && (filled.is_some()) {
remaining = crate::precise::Precise::stringSub(&amount.clone().map(Value::from).unwrap_or(Value::Null), &filled.clone().map(Value::from).unwrap_or(Value::Null));
}
let mut timestamp: Option<i64> = self.safe_integer_k(event.clone(), "timestamp", &[]).as_i64();
return self.safe_prediction_order(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string2(event.clone(), Value::Str("orderHash".into()), Value::Str("orderId".into()), &[]));
m.insert("clientOrderId".to_string(), Value::Null);
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("lastTradeTimestamp".to_string(), Value::Null);
m.insert("lastUpdateTimestamp".to_string(), Value::from(timestamp));
m.insert("status".to_string(), status);
m.insert("type".to_string(), self.safe_string_lower_k(details.clone(), "strategyType", &[]));
m.insert("timeInForce".to_string(), Value::Null);
m.insert("side".to_string(), side);
m.insert("price".to_string(), self.safe_number_k(details.clone(), "price", &[]));
m.insert("average".to_string(), Value::Null);
m.insert("amount".to_string(), self.parse_number(amount.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("filled".to_string(), self.parse_number(filled.map(Value::from).unwrap_or(Value::Null), &[]));
m.insert("remaining".to_string(), self.parse_number(remaining, &[]));
m.insert("cost".to_string(), self.safe_number_k(details, "valueFilled", &[]));
m.insert("fee".to_string(), Value::Null);
m.insert("reduceOnly".to_string(), Value::Null);
m.insert("postOnly".to_string(), Value::Null);
m.insert("trades".to_string(), Value::from(vec![]));
m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
m.insert("event".to_string(), self.safe_string_k(outcomeObj, "event", &[]));
m.insert("info".to_string(), event);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#parseWalletEventTrade
* @description parses the settled fill a wallet event carries
* @param {object} event the raw event
* @param {object} order the order the same event was parsed into
* @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
*/
pub fn parse_wallet_event_trade(&self, mut event: Value, mut order: Value) -> Value {
let __order_empty = indexmap::IndexMap::new();
let order = order.as_map().unwrap_or(&__order_empty);
let mut fill: Value = self.safe_dict_k(event.clone(), "fill", &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
// the fill is quoted in wei while the details block is quoted in units, so only these three
// fields are scaled down
let mut price: Value = crate::precise::Precise::stringDiv(&self.safe_string_k(fill.clone(), "executedPriceWei", &[]), &Value::Str("1000000000000000000".into()));
let mut amount: Value = crate::precise::Precise::stringDiv(&self.safe_string_k(fill.clone(), "executedSizeWei", &[]), &Value::Str("1000000000000000000".into()));
let mut cost: Value = crate::precise::Precise::stringDiv(&self.safe_string_k(fill, "executedValueWei", &[]), &Value::Str("1000000000000000000".into()));
let mut isMaker: Option<bool> = self.safe_bool_k_opt(event.clone(), "isMaker", &[]);
let mut takerOrMaker: Value = Value::Null;
if (isMaker.is_some()) {
takerOrMaker = (if isMaker == Some(true) { Value::Str("maker".into()) } else { Value::Str("taker".into()) });
}
let mut rawFee: Value = self.safe_dict_k(event.clone(), "fee", &[]);
let mut fee: Value = Value::Null;
if (rawFee != Value::Null) {
let mut feeType: Option<String> = self.safe_string_k(rawFee.clone(), "type", &[]).as_str().map(str::to_owned);
fee = Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("currency".to_string(), (if (feeType.as_deref() == Some("COLLATERAL")) { Value::Str("USDT".into()) } else { Value::Null }));
m.insert("cost".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&self.safe_string_k(rawFee, "amountWei", &[]), &Value::Str("1000000000000000000".into())), &[]));
m
});
}
let mut timestamp: Option<i64> = self.safe_integer_k(event.clone(), "timestamp", &[]).as_i64();
return self.safe_prediction_trade(Value::Map({
let mut m = indexmap::IndexMap::new();
m.insert("id".to_string(), self.safe_string_k(event.clone(), "settlementId", &[]));
m.insert("order".to_string(), self.safe_string_k(event.clone(), "orderHash", &[]));
m.insert("timestamp".to_string(), Value::from(timestamp));
m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
m.insert("outcome".to_string(), (match order.get("outcome") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("outcomeId".to_string(), (match order.get("outcomeId") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("label".to_string(), (match order.get("label") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("market".to_string(), (match order.get("market") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("type".to_string(), (match order.get("type") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("side".to_string(), (match order.get("side") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
m.insert("takerOrMaker".to_string(), takerOrMaker);
m.insert("price".to_string(), self.parse_number(price, &[]));
m.insert("amount".to_string(), self.parse_number(amount, &[]));
m.insert("cost".to_string(), self.parse_number(cost, &[]));
m.insert("fee".to_string(), fee);
m.insert("info".to_string(), event);
m
}), &[]);
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#handleHeartbeat
* @description echoes the probe timestamp back, which is what keeps the connection open
* @param {Client} client the websocket client
* @param {object} message the raw message
*/
pub fn handle_heartbeat(&mut self, mut client: Value, mut message: Value) {
// client.send () is a coroutine in the python port, so firing it from this synchronous
// handler would drop it unsent and the venue would close the socket on its next probe
self.spawn(&[Value::Null.clone(), client, message]);
}
/*
* @ignore
* @method
* @name predictfun#pong
* @description echoes the probe timestamp back, which is what keeps the connection open
* @param {Client} client the websocket client
* @param {object} message the raw probe
*/
pub async fn pong(&mut self, mut client: Value, mut message: Value) -> Value {
let __message_empty = indexmap::IndexMap::new();
let message = message.as_map().unwrap_or(&__message_empty);
// the server probes every fifteen seconds and drops the connection on the next probe unless
// the exact timestamp it sent comes back, so the reply echoes it verbatim
let mut reply: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m.insert("method".to_string(), Value::Str("heartbeat".into()));
m.insert("data".to_string(), (match message.get("data") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null }));
m
});
let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
client.send(&[Value::Map(reply)]);
#[allow(unreachable_code)] { Value::Null }})).await;
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
let mut error = Value::from(crate::exchange_errors::network_error(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" pong failed - ".into())).into()), self.exception_message(e, &[]))));
client.reset(error);
}
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#handleMessage
* @description routes a socket message to the handler of its topic
* @param {Client} client the websocket client
* @param {object} message the raw message
*/
pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
let __ch = crate::pro::ws_client::ClientHandle::from_value(client.clone());
let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &message { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
let mut messageType: Option<String> = (match __pro_message.get("type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
if (messageType.as_deref() == Some("R")) {
// a subscription reply - the venue reports a rejected topic here instead of closing.
// it carries only the request id, so the subscription that request registered is found
// by it - see handleSubscriptionStatus in pro/binance.ts
let mut id: Option<String> = match __pro_message.get("requestId").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
let mut subscriptionsById: Value = self.index_by(__ch.subscriptions.clone(), Value::Str("id".into()));
let mut subscription: Value = self.safe_dict(subscriptionsById, id.map(Value::from).unwrap_or(Value::Null), &[Value::Map({
let mut m = indexmap::IndexMap::new();
m
})]);
let mut success: Value = (match __pro_message.get("success").cloned() { Some(__v) if matches!(__v, Value::Bool(_)) => __v, _ => Value::Bool(false) });
if !(success.as_bool() == Some(true)) {
self.handle_subscription_error(client.clone(), message.clone(), subscription.clone());
return;
}
if matches!(self.safe_bool_k(subscription.clone(), "unsubscribe", &[Value::Bool(false)]), Value::Bool(true)) {
self.handle_un_subscription(client.clone(), subscription);
}
return;
}
let mut topic: Option<String> = match __pro_message.get("topic").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
if (topic.as_deref() == Some("heartbeat")) {
self.handle_heartbeat(client.clone(), message.clone());
return;
}
if (topic.is_none()) {
return;
}
let mut parts: Value = Value::Array(if let Some(__s) = topic.as_deref() { __s.split("/").map(Value::from).collect() } else { Vec::new() });
let mut channel: Option<String> = self.safe_string(parts, Value::Int(0), &[]).as_str().map(str::to_owned);
if (channel.as_deref() == Some("predictOrderbook")) {
self.handle_order_book(client.clone(), message.clone());
} else if (channel.as_deref() == Some("predictWalletEvents")) {
self.handle_wallet_event(client, message);
}
}
pub fn nonce(&self) -> Value {
return self.milliseconds();
Value::Null
}
/*
* @ignore
* @method
* @name predictfun#sign
* @description builds the request URL and attaches the API key header required by every endpoint
* @param {string} path the endpoint path
* @param {string[]} [api] the API group and access level
* @param {string} [method] HTTP method
* @param {object} [params] request parameters
* @returns {object} a dictionary with url, method, body and headers
*/
pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("predictfun".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);
// the venue authenticates every endpoint, so the key is required up front rather than
// per access level - a key-less request is answered with a 401 by the API gateway.
// the testnet is the exception, it is served without an API key at all
let mut sandboxMode: bool = self.safe_bool_k_opt(self.options.clone(), "sandboxMode", &[Value::Bool(false)]).unwrap_or(false);
let mut apiKey: Value = self.apiKey.clone();
if (apiKey == Value::Null) && !(sandboxMode) {
panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" sign() requires the \"apiKey\" credential for all endpoints".into()))));
}
let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[baseUrls.as_map().and_then(|__m| __m.get("predictfun")).cloned().unwrap_or(Value::Null)]);
let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
let mut query: Value = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
if (method.as_str() == Some("GET")) {
if ((object_keys(&query).len() as i64) as f64) > ((0i64) as f64) {
url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), self.urlencode(query.clone(), &[])).into())).into());
}
}
let mut existingHeaders: Value = Value::Map({
let mut m = indexmap::IndexMap::new();
m
});
let mut headersValue: Value = existingHeaders;
let mut authHeaders: indexmap::IndexMap<String, Value> = ({
let mut m = indexmap::IndexMap::new();
m
});
if (apiKey != Value::Null) && (!(sandboxMode)) {
// the php transpiler prefixes every standalone 'api' with a $, string literals included,
// since sign () has a parameter of that name - ending the literal right after it avoids that
let mut apiKeyHeader: Value = Value::Str(format!("{}{}", Value::Str("x-api".into()), Value::Str("-key".into())).into());
authHeaders.insert(crate::runtime::stringify_param(&apiKeyHeader), apiKey);
}
// the API key authorises the request, the JWT authorises acting for a wallet - authenticate ()
// caches it, so it is attached to every call once an order action has asked for one
// the JWT is scoped to one wallet, so it only goes to the endpoints that act for a wallet.
// attaching it to public reads would hand the venue a wallet credential they do not need.
// note v1/positions/{address} reads someone else's positions and is deliberately absent,
// as is v1/orders/matches, which is the public trade feed
let mut walletPaths: Value = Value::from(vec![Value::Str("v1/orders".into()), Value::Str("v1/orders/{hash}".into()), Value::Str("v1/orders/remove".into()), Value::Str("v1/orders/remove-by-hash".into()), Value::Str("v1/account".into()), Value::Str("v1/account/activity".into()), Value::Str("v1/account/referral".into()),
Value::Str("v1/positions".into()), Value::Str("v1/oauth/finalize".into()), Value::Str("v1/oauth/orders".into()), Value::Str("v1/oauth/orders/create".into()), Value::Str("v1/oauth/orders/cancel".into()), Value::Str("v1/oauth/positions".into())]);
let mut jwtToken: Option<String> = self.safe_string_k_opt(self.options.clone(), "jwtToken", &[]);
// unlike the API key, the JWT IS required on the testnet - wallet endpoints there answer
// 401 without it, so it is attached on both hosts
if (jwtToken.is_some()) && self.in_array(path, walletPaths).as_bool() == Some(true) {
authHeaders.insert("Authorization".into(), Value::Str(format!("{}{}", Value::Str("Bearer ".into()), jwtToken.map(Value::from).unwrap_or(Value::Null)).into()));
}
let mut bodyValue: Value = Value::Null;
if (method.as_str() != Some("GET")) {
if !(sandboxMode) {
self.check_required_credentials(&[]);
}
authHeaders.insert("Content-Type".into(), Value::Str("application/json".into()));
bodyValue = json_stringify(¶ms);
}
let mut headersExtended: Value = self.extend(headersValue, &[Value::Map(authHeaders)]);
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(), bodyValue);
m.insert("headers".to_string(), headersExtended);
m
});
Value::Null
}
}