Skip to main content

Check for Pending Settlements

from polyhush import PolyhushClient

client = PolyhushClient(api_key="your-api-key")

# Get all markets awaiting settlement
pending = client.get_pending_settlements()

if not pending:
    print("No pending settlements")
else:
    print(f"📋 {len(pending)} positions to review\n")
    
    ready = []
    awaiting = []
    
    for market in pending:
        if market['can_settle']:
            ready.append(market)
        else:
            awaiting.append(market)
    
    if ready:
        print(f"🟢 READY TO SETTLE ({len(ready)})")
        print("-" * 40)
        for m in ready:
            result_icon = "🎉" if m['you_won'] else "📉"
            print(f"{result_icon} {m['market_question'][:45]}...")
            print(f"   Your bet: {m['your_outcome']} ({m['your_position_size']} shares)")
            print(f"   Winner: {m['winning_outcome']}")
            print(f"   Payout: ${m['potential_payout']:.2f}")
            print()
    
    if awaiting:
        print(f"\n⏳ AWAITING RESOLUTION ({len(awaiting)})")
        print("-" * 40)
        for m in awaiting:
            print(f"   {m['market_question'][:45]}...")
            print(f"   Your bet: {m['your_outcome']}")
            print()

Settle All Positions at Once

# Simple one-liner to settle everything
results = client.settle_all_positions()

# Process results
total_payout = 0
wins = 0
losses = 0

for result in results:
    if result.get('settled'):
        total_payout += result['payout']
        if result['was_winner']:
            wins += 1
            print(f"🎉 Won ${result['payout']:.2f}")
        else:
            losses += 1
            print(f"📉 Lost (position cleared)")
    else:
        print(f"❌ Error: {result.get('error')}")

print(f"\n{'='*40}")
print(f"Summary: {wins} wins, {losses} losses")
print(f"Total claimed: ${total_payout:.2f}")

Settle a Specific Market

# Check status first
status = client.get_settlement_status(market_id="0x1234...abcd")

print(f"Market: {status['market_question']}")
print(f"Status: {status['status']}")

if status['settled']:
    print(f"Already settled! Payout was: ${status['user_payout']:.2f}")
    
elif status['status'] == 'NOT_SETTLED':
    # Check if we can settle
    pending = client.get_pending_settlements()
    market = next((m for m in pending if m['market_id'] == "0x1234...abcd"), None)
    
    if market and market['can_settle']:
        # Settle it
        result = client.settle_position(
            market_id=market['market_id'],
            token_id=market['token_id']
        )
        
        if result['settled']:
            print(f"✅ Settled! Payout: ${result['payout']:.2f}")
    else:
        print("Market not ready for settlement yet")
        
elif status['status'] == 'REDEEMING':
    print("Settlement in progress... please wait")

Settlement Dashboard

def settlement_dashboard(client):
    """Display a complete settlement dashboard"""
    
    # Get all settlement data
    summary = client.get_settlement_summary()
    pending = client.get_pending_settlements()
    history = client.get_settlements(limit=10)
    
    print("╔════════════════════════════════════════════╗")
    print("║          SETTLEMENT DASHBOARD              ║")
    print("╠════════════════════════════════════════════╣")
    print(f"║ Total Winnings:      ${summary['total_winnings']:>15,.2f} ║")
    print(f"║ Markets Settled:     {summary['settled_markets']:>15} ║")
    print(f"║ Pending Settlements: {summary['pending_markets']:>15} ║")
    print("╚════════════════════════════════════════════╝")
    
    # Pending settlements
    if pending:
        ready = [m for m in pending if m['can_settle']]
        if ready:
            total_pending = sum(m['potential_payout'] for m in ready)
            print(f"\n🟢 READY TO CLAIM: ${total_pending:.2f}")
            for m in ready[:5]:
                print(f"   • {m['market_question'][:40]}... ${m['potential_payout']:.2f}")
    
    # Recent history
    if history:
        print(f"\n📜 RECENT SETTLEMENTS")
        for h in history[:5]:
            icon = "✅" if h['winnings'] > 0 else "❌"
            print(f"   {icon} {h['market_question'][:35]}... ${h['winnings']:.2f}")

# Run dashboard
settlement_dashboard(client)

Automated Settlement Bot

import time
import schedule

def auto_settle():
    """Automatically settle all pending positions"""
    client = PolyhushClient()
    
    pending = client.get_pending_settlements()
    ready = [m for m in pending if m['can_settle']]
    
    if not ready:
        print(f"[{time.strftime('%H:%M')}] No settlements pending")
        return
    
    print(f"[{time.strftime('%H:%M')}] Settling {len(ready)} positions...")
    
    results = client.settle_all_positions()
    total = sum(r['payout'] for r in results if r.get('settled'))
    
    if total > 0:
        print(f"💰 Claimed ${total:.2f}!")
        # Could add notification here (email, Telegram, etc.)

# Run every hour
schedule.every().hour.do(auto_settle)

print("Settlement bot started...")
while True:
    schedule.run_pending()
    time.sleep(60)

Force Settlement Check

Use when automatic settlement hasn’t triggered.
def force_settle_market(client, market_id):
    """Force a settlement check for a specific market"""
    
    # First check current status
    status = client.get_settlement_status(market_id)
    
    if status['settled']:
        print(f"Market already settled")
        print(f"Your payout: ${status['user_payout']:.2f}")
        return status
    
    if status['status'] in ['REDEEMING', 'DISTRIBUTING']:
        print(f"Settlement in progress: {status['status']}")
        return status
    
    # Force the check
    print("Forcing settlement check...")
    result = client.force_settlement_check(market_id)
    
    if result.get('success'):
        print("✅ Settlement triggered!")
        print("Waiting for completion...")
        
        # Poll for completion
        for _ in range(12):  # Wait up to 2 minutes
            time.sleep(10)
            status = client.get_settlement_status(market_id)
            
            if status['settled']:
                print(f"Settlement complete!")
                print(f"Payout: ${status['user_payout']:.2f}")
                return status
            
            print(f"Status: {status['status']}...")
        
        print("Settlement still in progress")
        
    elif result.get('already_settled'):
        print("Market was already settled")
        
    else:
        print(f"Could not trigger settlement: {result.get('error')}")
    
    return result

# Usage
force_settle_market(client, "0x1234...abcd")

Track Settlement Transactions

def track_settlement_tx(client, market_id):
    """Get the on-chain transaction for a settlement"""
    
    status = client.get_settlement_status(market_id)
    
    if not status['settled']:
        print("Market not yet settled")
        return
    
    print(f"Market: {status['market_question']}")
    print(f"Winner: {status['winning_outcome']}")
    print(f"Your payout: ${status['user_payout']:.2f}")
    
    if status.get('redemption_tx_hash'):
        tx_hash = status['redemption_tx_hash']
        print(f"\n🔗 On-chain Transaction:")
        print(f"   Hash: {tx_hash}")
        print(f"   View: https://polygonscan.com/tx/{tx_hash}")
        print(f"\n   Total redeemed: ${status.get('redeemed_amount', 0):.2f}")
        print(f"   Users credited: {status.get('users_credited', 0)}")
    else:
        print("\nNo on-chain transaction (internal settlement)")

track_settlement_tx(client, "0x1234...abcd")