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 call = self.prepare_ctf_redemption(condition_id).await?;
320 self.submit_call(call, "Redeem positions").await
321 }
322
323 pub async fn redeem_positions_batch(
334 &self,
335 condition_ids: &[&str],
336 ) -> Result<PolymarketPositionTransaction> {
337 if condition_ids.is_empty() {
338 return Err(Error::bad_request(
339 "redeem_positions_batch requires at least one condition",
340 ));
341 }
342
343 let mut calls = Vec::with_capacity(condition_ids.len());
344 for (index, condition_id) in condition_ids.iter().enumerate() {
345 calls.push(self.prepare_ctf_redemption(condition_id).await.inspect_err(|e| {
346 log::warn!(
347 "Polymarket batch redemption preparation failed: wallet={:#x}, condition_index={index}, condition_id={condition_id}, error={e}",
348 self.deposit_wallet,
349 );
350 })?);
351 }
352
353 self.submit_calls(&calls, "Redeem positions batch").await
354 }
355
356 pub async fn redeem_position(
367 &self,
368 condition_id: &str,
369 outcome_index: u8,
370 amount: Decimal,
371 ) -> Result<PolymarketPositionTransaction> {
372 let call = encode_redeem_position_v2(condition_id, outcome_index, amount)?;
373 let base_amount = pusd_to_base_units(amount)?;
374
375 let PositionMarket::V2 { position_ids, .. } = self.market(condition_id).await? else {
376 return Err(Error::bad_request(
377 "redeem_position requires a V2 market; use redeem_positions for CTF",
378 ));
379 };
380
381 let position_id = position_ids[usize::from(outcome_index)];
382 self.wallet
383 .verify_v2_positions(self.deposit_wallet, &[position_id], base_amount)
384 .await?;
385 self.wallet.payout(position_id, base_amount).await?;
386 self.submit_call(call, "Redeem V2 position").await
387 }
388
389 pub async fn approve_v2_trading(
401 &self,
402 collateral_limit: Decimal,
403 ) -> Result<PolymarketPositionTransaction> {
404 let amount = pusd_to_base_units(collateral_limit)?;
405 let calls = approval_plan_v2(amount)
406 .into_iter()
407 .map(encode_approval)
408 .collect::<Vec<_>>();
409 self.submit_calls(&calls, "Approve V2 trading").await
410 }
411
412 async fn prepare_ctf_redemption(&self, condition_id: &str) -> Result<PositionCall> {
413 let PositionMarket::Ctf { neg_risk } = self.market(condition_id).await? else {
414 return Err(Error::bad_request(
415 "redeem_positions supports only v1 CTF markets; use redeem_position for V2",
416 ));
417 };
418
419 encode_redeem_positions(condition_id, neg_risk)
420 }
421
422 async fn market(&self, condition_id: &str) -> Result<PositionMarket> {
423 let query = if condition_id.len() == 64 {
424 let native = parse_condition_id_v2(condition_id)?;
425 format!("{native:#x}00")
426 } else {
427 condition_id.to_string()
428 };
429
430 let market = self.clob.get_market(&query).await?;
431 let version = validate_data_market_version(market.version.as_deref())
432 .map_err(|e| Error::bad_request(e.to_string()))?;
433
434 let neg_risk = market.neg_risk.ok_or_else(|| {
435 Error::bad_request(format!(
436 "market metadata for {condition_id} is missing neg_risk"
437 ))
438 })?;
439
440 if version != MARKET_VERSION_V2 {
441 if parse_bytes32(&market.condition_id, "market condition_id")?
442 != parse_bytes32(&query, "condition_id")?
443 {
444 return Err(Error::bad_request(
445 "Market condition ID does not match the requested condition",
446 ));
447 }
448
449 return Ok(PositionMarket::Ctf { neg_risk });
450 }
451
452 let requested = parse_condition_id_v2(condition_id)?;
453 if parse_condition_id_v2(&market.condition_id)? != requested {
454 return Err(Error::bad_request(
455 "Market condition ID does not match the requested V2 condition",
456 ));
457 }
458
459 if (requested[0] == 2) != neg_risk {
460 return Err(Error::bad_request(
461 "V2 module and neg_risk metadata disagree",
462 ));
463 }
464
465 let ids: Vec<_> = market
466 .tokens
467 .iter()
468 .map(|token| token.token_id.clone())
469 .collect();
470 let outcomes: Vec<_> = market
471 .tokens
472 .iter()
473 .map(|token| token.outcome.clone())
474 .collect();
475 validate_outcome_ids(&ids)
476 .and_then(|()| validate_outcomes(&outcomes))
477 .map_err(|e| Error::bad_request(e.to_string()))?;
478 let yes_id = U256::from_be_slice(requested.as_slice()) << 8;
479 let position_ids = [yes_id, yes_id + U256::from(1u8)];
480
481 for id in ids {
482 let id =
483 U256::from_str_radix(&id, 10).map_err(|e| Error::bad_request(e.to_string()))?;
484 if !position_ids.contains(&id) {
485 return Err(Error::bad_request(
486 "V2 position IDs do not match the requested condition and outcomes",
487 ));
488 }
489 }
490
491 Ok(PositionMarket::V2 { position_ids })
492 }
493
494 async fn submit_call(
495 &self,
496 call: PositionCall,
497 metadata: &str,
498 ) -> Result<PolymarketPositionTransaction> {
499 self.submit_calls(std::slice::from_ref(&call), metadata)
500 .await
501 }
502
503 async fn submit_calls(
504 &self,
505 calls: &[PositionCall],
506 metadata: &str,
507 ) -> Result<PolymarketPositionTransaction> {
508 let mut submission = self.submission.lock().await;
509 if let Some(previous) = submission.as_ref() {
510 let Some(transaction_id) = previous.transaction_id.as_deref() else {
511 return Err(Error::exchange(
512 "Previous Deposit Wallet submit outcome is unknown; reconcile it before further operations",
513 ));
514 };
515
516 let transaction = self.relayer.get_transaction(transaction_id).await?;
517 if !transaction.state.is_terminal() {
518 return Err(Error::exchange(format!(
519 "Deposit Wallet transaction {transaction_id} is still pending"
520 )));
521 }
522 }
523
524 let nonce = self
525 .wallet
526 .verify(self.signer.address(), self.deposit_wallet)
527 .await?;
528 let now = U256::from(self.clock.get_time_ns().as_u64() / 1_000_000_000);
529
530 if let Some(previous) = submission.as_ref()
531 && nonce <= previous.nonce
532 {
533 return Err(Error::exchange(
534 "Deposit Wallet nonce has not advanced; reconcile the previous submission before further operations",
535 ));
536 }
537
538 let deadline = now.saturating_add(U256::from(self.deadline_secs));
539
540 let wallet_calls: Vec<_> = calls
541 .iter()
542 .map(|call| DepositWalletCall {
543 target: call.target,
544 value: U256::ZERO,
545 data: call.data.clone(),
546 })
547 .collect();
548
549 let signature = self.signer.sign_deposit_wallet_batch(
550 self.deposit_wallet,
551 nonce,
552 deadline,
553 &wallet_calls,
554 )?;
555 *submission = Some(WalletSubmission {
556 nonce,
557 transaction_id: None,
558 });
559
560 for wallet_call in &wallet_calls {
561 log::info!(
562 "Deposit Wallet submission: wallet={:#x}, nonce={nonce}, deadline={deadline}, operation={metadata}, target={:#x}, value={}, data={}",
563 self.deposit_wallet,
564 wallet_call.target,
565 wallet_call.value,
566 wallet_call.data,
567 );
568 }
569
570 let submitted = self
571 .relayer
572 .submit_wallet_batch(RelayerWalletSubmit {
573 signer: self.signer.address(),
574 deposit_wallet: self.deposit_wallet,
575 nonce,
576 deadline,
577 signature: &signature,
578 metadata,
579 calls: &wallet_calls,
580 })
581 .await?;
582
583 let Some(transaction_id) = submitted.transaction_id else {
584 return Err(Error::decode(
585 "Relayer submit response omitted transaction_id; transaction outcome is unknown",
586 ));
587 };
588
589 *submission = Some(WalletSubmission {
590 nonce,
591 transaction_id: Some(transaction_id.clone()),
592 });
593
594 Ok(PolymarketPositionTransaction {
595 relayer: self.relayer.clone(),
596 transaction_id,
597 wait_timeout: self.wait_timeout,
598 poll_interval: self.poll_interval,
599 })
600 }
601}
602
603enum PositionMarket {
604 Ctf { neg_risk: bool },
605 V2 { position_ids: [U256; 2] },
606}
607
608#[derive(Debug)]
609struct WalletSubmission {
610 nonce: U256,
611 transaction_id: Option<String>,
612}
613
614type WalletSubmissionState = tokio::sync::Mutex<Option<WalletSubmission>>;
615
616fn wallet_submission(wallet: Address) -> Arc<WalletSubmissionState> {
617 let mut submissions = WALLET_SUBMISSIONS.lock();
618 submissions.retain(|_, state| {
619 Arc::strong_count(state) > 1 || state.try_lock().map_or(true, |state| state.is_some())
620 });
621
622 submissions.entry(wallet).or_default().clone()
623}
624
625fn outcome_from_transaction(tx: RelayerTransaction) -> Result<PolymarketPositionOutcome> {
626 let transaction_id = tx.transaction_id.clone().ok_or_else(|| {
627 Error::decode(
628 "Relayer terminal response omitted transaction_id; transaction outcome is unknown",
629 )
630 })?;
631
632 match tx.state {
633 RelayerTransactionState::Confirmed => Ok(PolymarketPositionOutcome::Confirmed {
634 transaction_id,
635 transaction_hash: tx.transaction_hash,
636 }),
637 RelayerTransactionState::Failed => Ok(PolymarketPositionOutcome::Failed {
638 transaction_id,
639 transaction_hash: tx.transaction_hash,
640 error_msg: tx.error_msg,
641 }),
642 RelayerTransactionState::Invalid => Ok(PolymarketPositionOutcome::Invalid {
643 transaction_id,
644 error_msg: tx.error_msg,
645 }),
646 RelayerTransactionState::New | RelayerTransactionState::Other(_) => {
647 Err(Error::decode(format!(
648 "Relayer transaction {transaction_id} is not terminal, state was {}",
649 tx.state.as_str()
650 )))
651 }
652 }
653}
654
655#[cfg(test)]
656mod tests {
657 use nautilus_network::retry::RetryConfig;
658 use rstest::rstest;
659
660 use super::*;
661
662 #[tokio::test]
663 #[ignore = "requires read-only access to live Polymarket Gamma and CLOB APIs"]
664 async fn test_live_market_protocol_selection() {
665 let key = EvmPrivateKey::new(
666 "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80",
667 )
668 .unwrap();
669 let relayer_key = RelayerApiKey::new(
670 "unused".into(),
671 "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
672 )
673 .unwrap();
674 let client = PolymarketPositionClient::new(
675 &key,
676 "0x1111111111111111111111111111111111111111",
677 relayer_key,
678 Some("http://127.0.0.1:1".into()),
679 None,
680 Some(20),
681 None,
682 )
683 .unwrap();
684 let gamma =
685 crate::http::gamma::PolymarketGammaHttpClient::new(None, 20, RetryConfig::default())
686 .unwrap();
687
688 for (market_id, protocol) in [("1557558", "v1"), ("5931597", "v2")] {
689 let markets = vec![gamma.inner().get_gamma_market(market_id).await.unwrap()];
690 let market = &markets[0];
691 assert_eq!(market.version.as_deref(), Some(protocol));
692 let (instruments, transient) =
693 crate::http::gamma::parse_markets_with_transient(&markets, 1.into());
694 assert_eq!(instruments.len(), 2);
695 assert_eq!(transient, Vec::<String>::new());
696 let result = client.market(&market.condition_id).await.unwrap();
697
698 if protocol == "v1" {
699 assert!(
700 matches!(result, PositionMarket::Ctf { neg_risk } if neg_risk == market.neg_risk.unwrap())
701 );
702 } else {
703 assert!(matches!(result, PositionMarket::V2 { .. }));
704 }
705 }
706 }
707
708 #[rstest]
709 fn test_outcome_from_confirmed_transaction() {
710 let outcome = outcome_from_transaction(RelayerTransaction {
711 transaction_id: Some("tx-1".into()),
712 transaction_hash: Some("0xabc".into()),
713 state: RelayerTransactionState::Confirmed,
714 error_msg: None,
715 })
716 .unwrap();
717
718 assert_eq!(
719 outcome,
720 PolymarketPositionOutcome::Confirmed {
721 transaction_id: "tx-1".into(),
722 transaction_hash: Some("0xabc".into()),
723 }
724 );
725 }
726
727 #[rstest]
728 fn test_outcome_from_failed_and_invalid_transactions() {
729 let failed = outcome_from_transaction(RelayerTransaction {
730 transaction_id: Some("tx-2".into()),
731 transaction_hash: None,
732 state: RelayerTransactionState::Failed,
733 error_msg: Some("reverted".into()),
734 })
735 .unwrap();
736
737 assert_eq!(
738 failed,
739 PolymarketPositionOutcome::Failed {
740 transaction_id: "tx-2".into(),
741 transaction_hash: None,
742 error_msg: Some("reverted".into()),
743 }
744 );
745
746 let invalid = outcome_from_transaction(RelayerTransaction {
747 transaction_id: Some("tx-3".into()),
748 transaction_hash: None,
749 state: RelayerTransactionState::Invalid,
750 error_msg: Some("bad nonce".into()),
751 })
752 .unwrap();
753
754 assert_eq!(
755 invalid,
756 PolymarketPositionOutcome::Invalid {
757 transaction_id: "tx-3".into(),
758 error_msg: Some("bad nonce".into()),
759 }
760 );
761 }
762
763 #[rstest]
764 fn test_outcome_from_non_terminal_is_error() {
765 let err = outcome_from_transaction(RelayerTransaction {
766 transaction_id: Some("tx-4".into()),
767 transaction_hash: None,
768 state: RelayerTransactionState::New,
769 error_msg: None,
770 })
771 .unwrap_err();
772
773 assert!(err.to_string().contains("is not terminal"));
774 assert!(err.to_string().contains("state was STATE_NEW"));
775 }
776}