1pub mod amounts;
19pub mod calldata;
20
21mod wallet;
22
23use std::{
24 collections::HashMap,
25 sync::{Arc, LazyLock},
26 time::{Duration, Instant},
27};
28
29use alloy_primitives::{Address, U256};
30use nautilus_core::time::{AtomicTime, get_atomic_clock_realtime};
31use nautilus_network::websocket::proxy::ProxyUrl;
32use parking_lot::Mutex;
33use rust_decimal::Decimal;
34
35use self::{
36 amounts::pusd_to_base_units,
37 calldata::{
38 PositionCall, encode_approval, encode_merge_positions, encode_merge_positions_v2,
39 encode_redeem_position_v2, encode_redeem_positions, encode_split_position,
40 encode_split_position_v2, parse_condition_id_v2,
41 },
42};
43use crate::{
44 common::{
45 consts::MARKET_VERSION_V2,
46 credential::{EvmPrivateKey, RelayerApiKey},
47 parse::{validate_data_market_version, validate_outcome_ids, validate_outcomes},
48 },
49 http::{
50 clob::PolymarketClobPublicClient,
51 error::{Error, Result},
52 relayer::{
53 PolymarketRelayerHttpClient, RelayerTransaction, RelayerTransactionState,
54 RelayerWalletSubmit,
55 },
56 },
57 signing::eip712::{
58 DepositWalletCall, OrderSigner, approval_plan_v2, parse_address, parse_bytes32,
59 },
60};
61
62const DEFAULT_HTTP_TIMEOUT_SECS: u64 = 60;
63const DEFAULT_DEADLINE_SECS: u64 = 1_800;
64const DEFAULT_WAIT_TIMEOUT_SECS: u64 = 120;
65const DEFAULT_POLL_INTERVAL_MS: u64 = 1_000;
66
67static WALLET_SUBMISSIONS: LazyLock<Mutex<HashMap<Address, Arc<WalletSubmissionState>>>> =
68 LazyLock::new(|| Mutex::new(HashMap::new()));
69
70#[derive(Clone, Debug, PartialEq, Eq)]
72pub enum PolymarketPositionOutcome {
73 Confirmed {
75 transaction_id: String,
77 transaction_hash: Option<String>,
79 },
80 Failed {
82 transaction_id: String,
84 transaction_hash: Option<String>,
86 error_msg: Option<String>,
88 },
89 Invalid {
91 transaction_id: String,
93 error_msg: Option<String>,
95 },
96}
97
98#[derive(Debug)]
100pub struct PolymarketPositionTransaction {
101 relayer: PolymarketRelayerHttpClient,
102 transaction_id: String,
103 wait_timeout: Duration,
104 poll_interval: Duration,
105}
106
107impl PolymarketPositionTransaction {
108 #[must_use]
110 pub fn transaction_id(&self) -> &str {
111 &self.transaction_id
112 }
113
114 pub async fn wait(self) -> Result<PolymarketPositionOutcome> {
122 let deadline = Instant::now() + self.wait_timeout;
123
124 loop {
125 match self.relayer.get_transaction(&self.transaction_id).await {
126 Ok(tx) => {
127 if tx.state.is_terminal() {
128 return outcome_from_transaction(tx);
129 }
130 }
131 Err(e) if e.is_retryable() => {
132 log::warn!(
133 "Relayer transaction {} poll failed: {e}; retrying",
134 self.transaction_id
135 );
136 }
137 Err(e) => return Err(e),
138 }
139
140 if Instant::now() >= deadline {
141 return Err(Error::exchange(format!(
142 "Relayer transaction {} wait timed out; terminal state is unknown",
143 self.transaction_id
144 )));
145 }
146
147 tokio::time::sleep(self.poll_interval).await;
148 }
149 }
150}
151
152#[derive(Debug)]
154pub struct PolymarketPositionClient {
155 signer: OrderSigner,
156 deposit_wallet: Address,
157 relayer: PolymarketRelayerHttpClient,
158 clob: PolymarketClobPublicClient,
159 clock: &'static AtomicTime,
160 deadline_secs: u64,
161 wait_timeout: Duration,
162 poll_interval: Duration,
163 wallet: wallet::WalletVerifier,
164 submission: Arc<WalletSubmissionState>,
165}
166
167impl PolymarketPositionClient {
168 pub fn new(
175 private_key: &EvmPrivateKey,
176 deposit_wallet: &str,
177 relayer_api_key: RelayerApiKey,
178 base_url_relayer: Option<String>,
179 base_url_clob: Option<String>,
180 timeout_secs: Option<u64>,
181 proxy_url: Option<ProxyUrl>,
182 ) -> Result<Self> {
183 let timeout_secs = timeout_secs.unwrap_or(DEFAULT_HTTP_TIMEOUT_SECS);
184 let signer = OrderSigner::new(private_key)?;
185 let deposit_wallet = parse_address(deposit_wallet, "deposit_wallet")?;
186 if deposit_wallet == signer.address() {
187 return Err(Error::bad_request(
188 "Deposit Wallet operations require a funder distinct from the signing address",
189 ));
190 }
191
192 let relayer = PolymarketRelayerHttpClient::new_with_proxy(
193 relayer_api_key,
194 base_url_relayer,
195 timeout_secs,
196 proxy_url.clone(),
197 )
198 .map_err(Error::from_http_client)?;
199 let wallet = wallet::WalletVerifier::new(timeout_secs, proxy_url.clone())?;
200 let clob =
201 PolymarketClobPublicClient::new_with_proxy(base_url_clob, timeout_secs, proxy_url)
202 .map_err(Error::from_http_client)?;
203
204 Ok(Self {
205 signer,
206 deposit_wallet,
207 relayer,
208 clob,
209 clock: get_atomic_clock_realtime(),
210 deadline_secs: DEFAULT_DEADLINE_SECS,
211 wait_timeout: Duration::from_secs(DEFAULT_WAIT_TIMEOUT_SECS),
212 poll_interval: Duration::from_millis(DEFAULT_POLL_INTERVAL_MS),
213 wallet,
214 submission: wallet_submission(deposit_wallet),
215 })
216 }
217
218 #[must_use]
220 pub fn with_rpc_url(mut self, rpc_url: String) -> Self {
221 self.wallet.set_rpc_url(rpc_url);
222 self
223 }
224
225 #[must_use]
232 pub fn with_deadline_secs(mut self, deadline_secs: u64) -> Self {
233 self.deadline_secs = deadline_secs.max(1);
234 self
235 }
236
237 #[must_use]
239 pub fn with_wait_timeout(mut self, wait_timeout: Duration) -> Self {
240 self.wait_timeout = wait_timeout;
241 self
242 }
243
244 #[must_use]
246 pub fn with_poll_interval(mut self, poll_interval: Duration) -> Self {
247 self.poll_interval = poll_interval;
248 self
249 }
250
251 pub async fn split_position(
258 &self,
259 condition_id: &str,
260 amount: Decimal,
261 ) -> Result<PolymarketPositionTransaction> {
262 let base_amount = pusd_to_base_units(amount)?;
263
264 let call = match self.market(condition_id).await? {
265 PositionMarket::Ctf { neg_risk } => {
266 encode_split_position(condition_id, amount, neg_risk)?
267 }
268 PositionMarket::V2 { .. } => {
269 let call = encode_split_position_v2(condition_id, amount)?;
270 self.wallet
271 .verify_v2_split(self.deposit_wallet, base_amount)
272 .await?;
273 call
274 }
275 };
276
277 self.submit_call(call, "Split position").await
278 }
279
280 pub async fn merge_positions(
287 &self,
288 condition_id: &str,
289 amount: Decimal,
290 ) -> Result<PolymarketPositionTransaction> {
291 let base_amount = pusd_to_base_units(amount)?;
292
293 let call = match self.market(condition_id).await? {
294 PositionMarket::Ctf { neg_risk } => {
295 encode_merge_positions(condition_id, amount, neg_risk)?
296 }
297 PositionMarket::V2 { position_ids } => {
298 let call = encode_merge_positions_v2(condition_id, amount)?;
299 self.wallet
300 .verify_v2_positions(self.deposit_wallet, &position_ids, base_amount)
301 .await?;
302 call
303 }
304 };
305
306 self.submit_call(call, "Merge positions").await
307 }
308
309 pub async fn redeem_positions(
316 &self,
317 condition_id: &str,
318 ) -> Result<PolymarketPositionTransaction> {
319 let PositionMarket::Ctf { neg_risk } = self.market(condition_id).await? else {
320 return Err(Error::bad_request(
321 "redeem_positions supports only v1 CTF markets; use redeem_position for V2",
322 ));
323 };
324
325 let call = encode_redeem_positions(condition_id, neg_risk)?;
326 self.submit_call(call, "Redeem positions").await
327 }
328
329 pub async fn redeem_position(
340 &self,
341 condition_id: &str,
342 outcome_index: u8,
343 amount: Decimal,
344 ) -> Result<PolymarketPositionTransaction> {
345 let call = encode_redeem_position_v2(condition_id, outcome_index, amount)?;
346 let base_amount = pusd_to_base_units(amount)?;
347
348 let PositionMarket::V2 { position_ids, .. } = self.market(condition_id).await? else {
349 return Err(Error::bad_request(
350 "redeem_position requires a V2 market; use redeem_positions for CTF",
351 ));
352 };
353
354 let position_id = position_ids[usize::from(outcome_index)];
355 self.wallet
356 .verify_v2_positions(self.deposit_wallet, &[position_id], base_amount)
357 .await?;
358 self.wallet.payout(position_id, base_amount).await?;
359 self.submit_call(call, "Redeem V2 position").await
360 }
361
362 pub async fn approve_v2_trading(
374 &self,
375 collateral_limit: Decimal,
376 ) -> Result<PolymarketPositionTransaction> {
377 let amount = pusd_to_base_units(collateral_limit)?;
378 let calls = approval_plan_v2(amount)
379 .into_iter()
380 .map(encode_approval)
381 .collect::<Vec<_>>();
382 self.submit_calls(&calls, "Approve V2 trading").await
383 }
384
385 async fn market(&self, condition_id: &str) -> Result<PositionMarket> {
386 let query = if condition_id.len() == 64 {
387 let native = parse_condition_id_v2(condition_id)?;
388 format!("{native:#x}00")
389 } else {
390 condition_id.to_string()
391 };
392
393 let market = self.clob.get_market(&query).await?;
394 let version = validate_data_market_version(market.version.as_deref())
395 .map_err(|e| Error::bad_request(e.to_string()))?;
396
397 let neg_risk = market.neg_risk.ok_or_else(|| {
398 Error::bad_request(format!(
399 "market metadata for {condition_id} is missing neg_risk"
400 ))
401 })?;
402
403 if version != MARKET_VERSION_V2 {
404 if parse_bytes32(&market.condition_id, "market condition_id")?
405 != parse_bytes32(&query, "condition_id")?
406 {
407 return Err(Error::bad_request(
408 "Market condition ID does not match the requested condition",
409 ));
410 }
411
412 return Ok(PositionMarket::Ctf { neg_risk });
413 }
414
415 let requested = parse_condition_id_v2(condition_id)?;
416 if parse_condition_id_v2(&market.condition_id)? != requested {
417 return Err(Error::bad_request(
418 "Market condition ID does not match the requested V2 condition",
419 ));
420 }
421
422 if (requested[0] == 2) != neg_risk {
423 return Err(Error::bad_request(
424 "V2 module and neg_risk metadata disagree",
425 ));
426 }
427
428 let ids: Vec<_> = market
429 .tokens
430 .iter()
431 .map(|token| token.token_id.clone())
432 .collect();
433 let outcomes: Vec<_> = market
434 .tokens
435 .iter()
436 .map(|token| token.outcome.clone())
437 .collect();
438 validate_outcome_ids(&ids)
439 .and_then(|()| validate_outcomes(&outcomes))
440 .map_err(|e| Error::bad_request(e.to_string()))?;
441 let yes_id = U256::from_be_slice(requested.as_slice()) << 8;
442 let position_ids = [yes_id, yes_id + U256::from(1u8)];
443
444 for id in ids {
445 let id =
446 U256::from_str_radix(&id, 10).map_err(|e| Error::bad_request(e.to_string()))?;
447 if !position_ids.contains(&id) {
448 return Err(Error::bad_request(
449 "V2 position IDs do not match the requested condition and outcomes",
450 ));
451 }
452 }
453
454 Ok(PositionMarket::V2 { position_ids })
455 }
456
457 async fn submit_call(
458 &self,
459 call: PositionCall,
460 metadata: &str,
461 ) -> Result<PolymarketPositionTransaction> {
462 self.submit_calls(std::slice::from_ref(&call), metadata)
463 .await
464 }
465
466 async fn submit_calls(
467 &self,
468 calls: &[PositionCall],
469 metadata: &str,
470 ) -> Result<PolymarketPositionTransaction> {
471 let mut submission = self.submission.lock().await;
472 if let Some(previous) = submission.as_ref() {
473 let Some(transaction_id) = previous.transaction_id.as_deref() else {
474 return Err(Error::exchange(
475 "Previous Deposit Wallet submit outcome is unknown; reconcile it before further operations",
476 ));
477 };
478
479 let transaction = self.relayer.get_transaction(transaction_id).await?;
480 if !transaction.state.is_terminal() {
481 return Err(Error::exchange(format!(
482 "Deposit Wallet transaction {transaction_id} is still pending"
483 )));
484 }
485 }
486
487 let nonce = self
488 .wallet
489 .verify(self.signer.address(), self.deposit_wallet)
490 .await?;
491 let now = U256::from(self.clock.get_time_ns().as_u64() / 1_000_000_000);
492
493 if let Some(previous) = submission.as_ref()
494 && nonce <= previous.nonce
495 {
496 return Err(Error::exchange(
497 "Deposit Wallet nonce has not advanced; reconcile the previous submission before further operations",
498 ));
499 }
500
501 let deadline = now.saturating_add(U256::from(self.deadline_secs));
502
503 let wallet_calls: Vec<_> = calls
504 .iter()
505 .map(|call| DepositWalletCall {
506 target: call.target,
507 value: U256::ZERO,
508 data: call.data.clone(),
509 })
510 .collect();
511
512 let signature = self.signer.sign_deposit_wallet_batch(
513 self.deposit_wallet,
514 nonce,
515 deadline,
516 &wallet_calls,
517 )?;
518 *submission = Some(WalletSubmission {
519 nonce,
520 transaction_id: None,
521 });
522
523 for wallet_call in &wallet_calls {
524 log::info!(
525 "Deposit Wallet submission: wallet={:#x}, nonce={nonce}, deadline={deadline}, operation={metadata}, target={:#x}, value={}, data={}",
526 self.deposit_wallet,
527 wallet_call.target,
528 wallet_call.value,
529 wallet_call.data,
530 );
531 }
532
533 let submitted = self
534 .relayer
535 .submit_wallet_batch(RelayerWalletSubmit {
536 signer: self.signer.address(),
537 deposit_wallet: self.deposit_wallet,
538 nonce,
539 deadline,
540 signature: &signature,
541 metadata,
542 calls: &wallet_calls,
543 })
544 .await?;
545
546 let Some(transaction_id) = submitted.transaction_id else {
547 return Err(Error::decode(
548 "Relayer submit response omitted transaction_id; transaction outcome is unknown",
549 ));
550 };
551
552 *submission = Some(WalletSubmission {
553 nonce,
554 transaction_id: Some(transaction_id.clone()),
555 });
556
557 Ok(PolymarketPositionTransaction {
558 relayer: self.relayer.clone(),
559 transaction_id,
560 wait_timeout: self.wait_timeout,
561 poll_interval: self.poll_interval,
562 })
563 }
564}
565
566enum PositionMarket {
567 Ctf { neg_risk: bool },
568 V2 { position_ids: [U256; 2] },
569}
570
571#[derive(Debug)]
572struct WalletSubmission {
573 nonce: U256,
574 transaction_id: Option<String>,
575}
576
577type WalletSubmissionState = tokio::sync::Mutex<Option<WalletSubmission>>;
578
579fn wallet_submission(wallet: Address) -> Arc<WalletSubmissionState> {
580 let mut submissions = WALLET_SUBMISSIONS.lock();
581 submissions.retain(|_, state| {
582 Arc::strong_count(state) > 1 || state.try_lock().map_or(true, |state| state.is_some())
583 });
584
585 submissions.entry(wallet).or_default().clone()
586}
587
588fn outcome_from_transaction(tx: RelayerTransaction) -> Result<PolymarketPositionOutcome> {
589 let transaction_id = tx.transaction_id.clone().ok_or_else(|| {
590 Error::decode(
591 "Relayer terminal response omitted transaction_id; transaction outcome is unknown",
592 )
593 })?;
594
595 match tx.state {
596 RelayerTransactionState::Confirmed => Ok(PolymarketPositionOutcome::Confirmed {
597 transaction_id,
598 transaction_hash: tx.transaction_hash,
599 }),
600 RelayerTransactionState::Failed => Ok(PolymarketPositionOutcome::Failed {
601 transaction_id,
602 transaction_hash: tx.transaction_hash,
603 error_msg: tx.error_msg,
604 }),
605 RelayerTransactionState::Invalid => Ok(PolymarketPositionOutcome::Invalid {
606 transaction_id,
607 error_msg: tx.error_msg,
608 }),
609 RelayerTransactionState::New | RelayerTransactionState::Other(_) => {
610 Err(Error::decode(format!(
611 "Relayer transaction {transaction_id} is not terminal, state was {}",
612 tx.state.as_str()
613 )))
614 }
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use nautilus_network::retry::RetryConfig;
621 use rstest::rstest;
622
623 use super::*;
624
625 #[tokio::test]
626 #[ignore = "requires read-only access to live Polymarket Gamma and CLOB APIs"]
627 async fn test_live_market_protocol_selection() {
628 let key = EvmPrivateKey::new(
629 "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
630 )
631 .unwrap();
632 let relayer_key = RelayerApiKey::new(
633 "unused".into(),
634 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
635 )
636 .unwrap();
637 let client = PolymarketPositionClient::new(
638 &key,
639 "0x1111111111111111111111111111111111111111",
640 relayer_key,
641 Some("http://127.0.0.1:1".into()),
642 None,
643 Some(20),
644 None,
645 )
646 .unwrap();
647 let gamma =
648 crate::http::gamma::PolymarketGammaHttpClient::new(None, 20, RetryConfig::default())
649 .unwrap();
650
651 for (market_id, protocol) in [("1557558", "v1"), ("5931597", "v2")] {
652 let markets = vec![gamma.inner().get_gamma_market(market_id).await.unwrap()];
653 let market = &markets[0];
654 assert_eq!(market.version.as_deref(), Some(protocol));
655 let (instruments, transient) =
656 crate::http::gamma::parse_markets_with_transient(&markets, 1.into());
657 assert_eq!(instruments.len(), 2);
658 assert_eq!(transient, Vec::<String>::new());
659 let result = client.market(&market.condition_id).await.unwrap();
660
661 if protocol == "v1" {
662 assert!(
663 matches!(result, PositionMarket::Ctf { neg_risk } if neg_risk == market.neg_risk.unwrap())
664 );
665 } else {
666 assert!(matches!(result, PositionMarket::V2 { .. }));
667 }
668 }
669 }
670
671 #[rstest]
672 fn test_outcome_from_confirmed_transaction() {
673 let outcome = outcome_from_transaction(RelayerTransaction {
674 transaction_id: Some("tx-1".into()),
675 transaction_hash: Some("0xabc".into()),
676 state: RelayerTransactionState::Confirmed,
677 error_msg: None,
678 })
679 .unwrap();
680
681 assert_eq!(
682 outcome,
683 PolymarketPositionOutcome::Confirmed {
684 transaction_id: "tx-1".into(),
685 transaction_hash: Some("0xabc".into()),
686 }
687 );
688 }
689
690 #[rstest]
691 fn test_outcome_from_failed_and_invalid_transactions() {
692 let failed = outcome_from_transaction(RelayerTransaction {
693 transaction_id: Some("tx-2".into()),
694 transaction_hash: None,
695 state: RelayerTransactionState::Failed,
696 error_msg: Some("reverted".into()),
697 })
698 .unwrap();
699
700 assert_eq!(
701 failed,
702 PolymarketPositionOutcome::Failed {
703 transaction_id: "tx-2".into(),
704 transaction_hash: None,
705 error_msg: Some("reverted".into()),
706 }
707 );
708
709 let invalid = outcome_from_transaction(RelayerTransaction {
710 transaction_id: Some("tx-3".into()),
711 transaction_hash: None,
712 state: RelayerTransactionState::Invalid,
713 error_msg: Some("bad nonce".into()),
714 })
715 .unwrap();
716
717 assert_eq!(
718 invalid,
719 PolymarketPositionOutcome::Invalid {
720 transaction_id: "tx-3".into(),
721 error_msg: Some("bad nonce".into()),
722 }
723 );
724 }
725
726 #[rstest]
727 fn test_outcome_from_non_terminal_is_error() {
728 let err = outcome_from_transaction(RelayerTransaction {
729 transaction_id: Some("tx-4".into()),
730 transaction_hash: None,
731 state: RelayerTransactionState::New,
732 error_msg: None,
733 })
734 .unwrap_err();
735
736 assert!(err.to_string().contains("is not terminal"));
737 assert!(err.to_string().contains("state was STATE_NEW"));
738 }
739}