Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 35 additions & 40 deletions examples/decode_market_example/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,52 +25,47 @@ def main():
# 1. Initialize the TNClient
client = TNClient(endpoint, private_key)

# 2. List the most recently created markets
# We'll look at the top 3 active markets.
limit = 3
print(f"[*] Fetching the {limit} latest markets...")
markets = client.list_markets(limit=limit)
# 2. List Markets (Both Active and Settled)
states = [
{"label": "ACTIVE", "filter": False},
{"label": "SETTLED", "filter": True}
]
limit = 2

if not markets:
print("[!] No markets found on the network.")
return
for state in states:
print(f"\n--- Fetching Latest {state['label']} Markets ---")
markets = client.list_markets(limit=limit, settled_filter=state['filter'])

print(f"[+] Found {len(markets)} markets.\n")
if not markets:
print(f"[!] No {state['label']} markets found.")
continue

# 3. Process each market
for m in markets:
market_id = m['id']
print(f"{'-' * 40}")
print(f" MARKET ID: {market_id}")
print(f"{'-' * 40}")

try:
# Fetch the FULL market info, which includes the 'query_components'
# list_markets only returns a summary for performance.
market_info = client.get_market_info(market_id)
print(f"[+] Found {len(markets)} markets.\n")

# Use the SDK's built-in decoder to parse the binary components
# This handles ABI-decoding the (address, bytes32, string, bytes) tuple
# and further parsing the 'args' based on the action type.
details = TNClient.decode_market_data(market_info['query_components'])

# Display the decoded information
print(f" [Action] {details['action_id']}")
print(f" [Market Type] {details['type'].upper()}")

# Format thresholds for readability
thresholds_str = ", ".join(details['thresholds'])
print(f" [Thresholds] {thresholds_str}")

print(f" [Provider] {details['data_provider']}")
print(f" [Stream ID] {details['stream_id']}")
# 3. Process each market
for m in markets:
market_id = m['id']
print(f" MARKET ID: {market_id}")

# Print the raw decoded dictionary for reference
# print(f"\n [Raw Data] {json.dumps(details, indent=4)}")
print()
try:
# Fetch the FULL market info
market_info = client.get_market_info(market_id)

# Use the SDK's built-in decoder
details = TNClient.decode_market_data(market_info['query_components'])

# Display the decoded information
print(f" [Action] {details['action_id']}")
print(f" [Market Type] {details['type'].upper()}")

# Format thresholds for readability
thresholds_str = ", ".join(details['thresholds'])
print(f" [Thresholds] {thresholds_str}")
print(f" [Stream ID] {details['stream_id']}")
print()

except Exception as e:
print(f" [!] Error processing market {market_id}: {e}")
except Exception as e:
print(f" [!] Error processing market {market_id}: {e}")
Comment on lines +67 to +68
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Locate SDK exception types and what get_market_info/decode_market_data raise
rg -n --type=py "def get_market_info" -C5
rg -n --type=py "def decode_market_data" -C5
rg -n --type=py "class .*Error|Exception" -C3
rg -n --type=py "raise " -C2

Repository: trufnetwork/sdk-py

Length of output: 50376


🏁 Script executed:

#!/bin/bash
# Get the full decode_market_data implementation
sed -n '2736,2780p' src/trufnetwork_sdk_py/client.py

# Check if there are any custom exception classes defined
rg -n "^class.*Exception|^class.*Error" src/trufnetwork_sdk_py/ --type=py

# Get the complete context around lines 67-68 in the example file
sed -n '50,75p' examples/decode_market_example/main.py

# Search for what decode_market_data might raise
rg -n "def decode_market_data" -A 20 src/trufnetwork_sdk_py/ --type=py

Repository: trufnetwork/sdk-py

Length of output: 4509


🏁 Script executed:

#!/bin/bash
# Search for custom exception/error class definitions
rg -n "^class.*Exception|^class.*Error" src/trufnetwork_sdk_py/ --type=py

# Check for any documented exceptions in docstrings
rg -n "Raises:" src/trufnetwork_sdk_py/client.py -A 3 | head -50

Repository: trufnetwork/sdk-py

Length of output: 1285


Narrow broad Exception to specific SDK exception types.

The code should catch (RuntimeError, ValueError, KeyError) instead of bare Exception. get_market_info raises RuntimeError when a market isn't found, decode_market_data can raise ValueError (via json.loads), and accessing market_info['query_components'] can raise KeyError. Catching only these known exceptions prevents accidental masking of unexpected bugs.

🧰 Tools
🪛 Ruff (0.15.2)

[warning] 67-67: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/decode_market_example/main.py` around lines 67 - 68, Replace the
broad except Exception handler that prints errors for each market with a
narrowed exception tuple: catch RuntimeError, ValueError, and KeyError only
(these come from get_market_info raising RuntimeError,
decode_market_data/json.loads raising ValueError, and accessing
market_info['query_components'] raising KeyError) and keep the existing error
logging/print for the caught exceptions so unexpected errors still surface.


except Exception as e:
print(f"[!] Critical error: {e}")
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ require (
github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9
github.com/pkg/errors v0.9.1
github.com/trufnetwork/kwil-db/core v0.4.3-0.20260216231327-01b863886682
github.com/trufnetwork/sdk-go v0.6.4-0.20260220161451-2f87974cef9c
github.com/trufnetwork/sdk-go v0.6.4-0.20260224122406-a741343e2f37
google.golang.org/genproto v0.0.0-20251111163417-95abcf5c77ba
)

Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ github.com/trufnetwork/sdk-go v0.6.3 h1:GHEm94C2yTdo6RjY/a/5i2d9uyvtqACjpzTNE/Vc
github.com/trufnetwork/sdk-go v0.6.3/go.mod h1:f7IjKRZi4VufWM01b3rODFot1LqopiKw5YR23TL/3dg=
github.com/trufnetwork/sdk-go v0.6.4-0.20260220161451-2f87974cef9c h1:h6qaPvGjhLTJN7cM1gpKVRsY+GolXkb8m5lvUADkuTU=
github.com/trufnetwork/sdk-go v0.6.4-0.20260220161451-2f87974cef9c/go.mod h1:f7IjKRZi4VufWM01b3rODFot1LqopiKw5YR23TL/3dg=
github.com/trufnetwork/sdk-go v0.6.4-0.20260224100843-2b7b7e735e86 h1:2qBAQJXOjNHX8hyBv1c8/eJwr70Nifg8Q3tqb0e5wCE=
github.com/trufnetwork/sdk-go v0.6.4-0.20260224100843-2b7b7e735e86/go.mod h1:f7IjKRZi4VufWM01b3rODFot1LqopiKw5YR23TL/3dg=
github.com/trufnetwork/sdk-go v0.6.4-0.20260224122406-a741343e2f37 h1:VD/GWxLTshaXpLukEc1SXbG7QA9HrFzF8JvxJAJ/x7Q=
github.com/trufnetwork/sdk-go v0.6.4-0.20260224122406-a741343e2f37/go.mod h1:f7IjKRZi4VufWM01b3rODFot1LqopiKw5YR23TL/3dg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
Expand Down