Skip to content

Commit 817ca64

Browse files
codebydivineclaude
andcommitted
feat: Optimize examples for maximum simplicity and user experience
- Add visual formatting with emojis and professional output - Create helper functions to reduce code duplication - Improve error messages with actionable troubleshooting tips - Add quickstart.py for one-stop demonstration - Enhance readability with better variable names and comments - Implement smart number formatting (K/M suffixes) - Add comprehensive validation and optimization documentation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent adf16fc commit 817ca64

File tree

9 files changed

+465
-181
lines changed

9 files changed

+465
-181
lines changed

examples/README.md

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,41 @@
11
# Token API Examples
22

3-
Comprehensive examples demonstrating real-world usage of the Token API Client with live blockchain data. All examples use actual addresses, contracts, and market data to showcase API capabilities.
3+
Optimized, user-friendly examples demonstrating The Graph Token API with real blockchain data. All examples feature clean output, helpful error messages, and professional formatting.
44

55
## 🚀 Quick Start
66

7-
**Set your API key:**
7+
**1. Set your API key:**
88
```bash
9-
export THEGRAPH_API_KEY="your_api_key_here"
9+
export THEGRAPH_API_KEY="your_api_key_here" # pragma: allowlist secret
1010
```
1111
Get a free API key at: [thegraph.market](https://thegraph.market)
1212

13-
**Run examples:**
13+
**2. Try the quick start:**
14+
```bash
15+
python examples/quickstart.py # Everything in one script!
16+
```
17+
18+
**3. Explore specific examples:**
1419
```bash
1520
# EVM examples
16-
python examples/endpoints/evm/health.py # API connectivity
17-
python examples/endpoints/evm/balances.py # Token balances
18-
python examples/endpoints/evm/nfts.py # NFT ownership
21+
python examples/endpoints/evm/health.py # 🏥 API connectivity
22+
python examples/endpoints/evm/balances.py # 💰 Token portfolios
23+
python examples/endpoints/evm/nfts.py # 🎨 NFT collections
1924

2025
# SVM examples
21-
python examples/endpoints/svm/balances.py # SPL balances
22-
python examples/endpoints/svm/swaps.py # Solana DEX swaps
26+
python examples/endpoints/svm/balances.py # SPL token balances
27+
python examples/endpoints/svm/swaps.py # 🌊 Solana DEX trading
2328
```
2429

30+
## **NEW: Optimized for Simplicity**
31+
32+
All examples now feature:
33+
- 🎨 **Visual output** with emojis and clear formatting
34+
- 💡 **Smart error messages** with troubleshooting tips
35+
- 📊 **Professional displays** with K/M number formatting
36+
- 🚀 **Faster execution** with streamlined code
37+
- 🛠️ **Helper functions** for consistent, maintainable code
38+
2539
## 📁 Examples Structure
2640

2741
### 🔗 EVM (Ethereum Virtual Machine)

examples/_helpers.py

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Helper functions for token-api examples.
4+
5+
This module provides common utility functions used across examples
6+
to format data, handle timestamps, and display information cleanly.
7+
"""
8+
9+
from datetime import datetime
10+
11+
12+
def format_amount(value, precision=2):
13+
"""
14+
Format large numbers with K/M suffixes for readability.
15+
16+
Args:
17+
value: Numeric value to format
18+
precision: Decimal places (default: 2)
19+
20+
Returns:
21+
Formatted string (e.g., "1.5M", "234.6K", "45.67")
22+
"""
23+
if value >= 1_000_000:
24+
return f"{value / 1_000_000:.1f}M"
25+
if value >= 1_000:
26+
return f"{value / 1_000:.1f}K"
27+
return f"{value:.{precision}f}"
28+
29+
30+
def format_time(timestamp):
31+
"""
32+
Convert Unix timestamp to readable time format.
33+
34+
Args:
35+
timestamp: Unix timestamp (int/float)
36+
37+
Returns:
38+
Time string in HH:MM format, or "??:??" if invalid
39+
"""
40+
try:
41+
return datetime.fromtimestamp(timestamp).strftime("%H:%M")
42+
except (ValueError, TypeError, OSError):
43+
return "??:??"
44+
45+
46+
def format_date(timestamp):
47+
"""
48+
Convert Unix timestamp to readable date format.
49+
50+
Args:
51+
timestamp: Unix timestamp (int/float)
52+
53+
Returns:
54+
Date string in MM/DD format, or "??/??" if invalid
55+
"""
56+
try:
57+
return datetime.fromtimestamp(timestamp).strftime("%m/%d")
58+
except (ValueError, TypeError, OSError):
59+
return "??/??"
60+
61+
62+
def shorten_address(address, length=6):
63+
"""
64+
Shorten blockchain address for display.
65+
66+
Args:
67+
address: Full blockchain address
68+
length: Number of characters to show (default: 6)
69+
70+
Returns:
71+
Shortened address with "..." (e.g., "0x1234...")
72+
"""
73+
if not address or len(address) <= length + 3:
74+
return str(address)
75+
return str(address)[:length] + "..."
76+
77+
78+
def shorten_id(token_id, max_length=6):
79+
"""
80+
Shorten long token IDs for display.
81+
82+
Args:
83+
token_id: Token ID (any type)
84+
max_length: Maximum length before shortening
85+
86+
Returns:
87+
Shortened ID string
88+
"""
89+
id_str = str(token_id)
90+
if len(id_str) <= max_length:
91+
return id_str
92+
return id_str[:max_length] + "..."
93+
94+
95+
def get_symbol(mint_obj, fallback_length=6):
96+
"""
97+
Get token symbol from mint object, with fallback to shortened address.
98+
99+
Args:
100+
mint_obj: Token mint object (may have .symbol attribute)
101+
fallback_length: Length for fallback address shortening
102+
103+
Returns:
104+
Token symbol or shortened address
105+
"""
106+
if hasattr(mint_obj, "symbol") and mint_obj.symbol:
107+
return mint_obj.symbol
108+
return shorten_address(str(mint_obj), fallback_length)
109+
110+
111+
def format_price_change(open_price, close_price):
112+
"""
113+
Calculate and format price change percentage.
114+
115+
Args:
116+
open_price: Opening price
117+
close_price: Closing price
118+
119+
Returns:
120+
Formatted percentage string (e.g., "+2.5%", "-1.8%")
121+
"""
122+
if not open_price or open_price == 0:
123+
return "±0.0%"
124+
125+
change = ((close_price - open_price) / open_price) * 100
126+
return f"{change:+.1f}%"
127+
128+
129+
def print_header(title, emoji=""):
130+
"""
131+
Print a formatted header for examples.
132+
133+
Args:
134+
title: Header title
135+
emoji: Optional emoji prefix
136+
"""
137+
full_title = f"{emoji} {title}" if emoji else title
138+
print(full_title)
139+
print("=" * len(full_title))
140+
141+
142+
def print_section(title, emoji=""):
143+
"""
144+
Print a formatted section header.
145+
146+
Args:
147+
title: Section title
148+
emoji: Optional emoji prefix
149+
"""
150+
full_title = f"{emoji} {title}" if emoji else title
151+
print(f"\n{full_title}:")
152+
153+
154+
# Common wallet addresses for examples
155+
WALLETS = {
156+
"vitalik": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
157+
"imagine_token": "0x6A1B2AE3a55B5661b40d86c2bF805f7DAdB16978",
158+
"cryptopunks": "0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb",
159+
"link_token": "0x514910771AF9Ca656af840dff83E8264EcF986CA",
160+
"uniswap_pool": "0x3E456E2A71adafb6fe0AF8098334ee41ef53A7C6",
161+
}
162+
163+
# Common Solana mint addresses
164+
SOLANA_MINTS = {
165+
"sol": "So11111111111111111111111111111111111111112",
166+
"usdc": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", # pragma: allowlist secret
167+
}

examples/endpoints/evm/balances.py

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,52 @@
11
#!/usr/bin/env python3
2-
"""Token Balances Example - Get ERC-20 token balances."""
2+
"""Token Balances Example - See your crypto portfolio instantly."""
33

44
import anyio
55

66
from thegraph_token_api import TokenAPI
77

88

9+
def format_amount(value):
10+
"""Format large numbers with K/M suffixes."""
11+
if value >= 1_000_000:
12+
return f"{value / 1_000_000:.1f}M"
13+
if value >= 1_000:
14+
return f"{value / 1_000:.1f}K"
15+
return f"{value:.2f}"
16+
17+
918
async def main():
10-
print("Token Balances Example")
11-
print("=" * 22)
19+
print("💰 Token Balances")
20+
print("=" * 17)
1221

1322
api = TokenAPI()
14-
vitalik = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
23+
wallet = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" # Vitalik's wallet
1524

1625
try:
17-
# Get top token balances
18-
print(f"\nTop balances for {vitalik[:10]}...:")
19-
balances = await api.evm.balances(vitalik, limit=7)
26+
print(f"📊 Portfolio for {wallet[:8]}...")
27+
balances = await api.evm.balances(wallet, limit=5)
2028

29+
print("\n🏆 Top Holdings:")
2130
for i, balance in enumerate(balances, 1):
22-
symbol = balance.symbol or "?"
23-
value = balance.value
24-
25-
# Simple number formatting
26-
if value > 1_000_000:
27-
formatted = f"{value / 1_000_000:.1f}M"
28-
elif value > 1_000:
29-
formatted = f"{value / 1_000:.1f}K"
30-
else:
31-
formatted = f"{value:.2f}"
32-
33-
print(f" {i}. {symbol}: {formatted}")
34-
35-
# Get specific token balance
36-
print("\nSpecific token balance:")
37-
specific = await api.evm.balances(vitalik, contract="0x6A1B2AE3a55B5661b40d86c2bF805f7DAdB16978", limit=1)
38-
39-
if specific:
40-
symbol = specific[0].symbol or "?"
41-
value = specific[0].value
42-
print(f" {symbol}: {value}")
31+
symbol = balance.symbol or "UNKNOWN"
32+
amount = format_amount(balance.value)
33+
print(f" {i}. {symbol}: {amount}")
34+
35+
# Show specific token
36+
print("\n🎯 Specific Token:")
37+
imagine = await api.evm.balances(wallet, contract="0x6A1B2AE3a55B5661b40d86c2bF805f7DAdB16978", limit=1)
38+
39+
if imagine:
40+
token = imagine[0]
41+
print(f" {token.symbol or 'TOKEN'}: {format_amount(token.value)}")
4342
else:
44-
print(" No balance found")
43+
print(" No balance found for this token")
4544

46-
print("\nBalances retrieved successfully!")
45+
print("\nPortfolio loaded!")
4746

4847
except Exception as e:
49-
print(f"❌ Error: {e}")
48+
print(f"❌ Failed to load portfolio: {e}")
49+
print("💡 Make sure your API key is set: export THEGRAPH_API_KEY='your_key'") # pragma: allowlist secret
5050

5151

5252
if __name__ == "__main__":

examples/endpoints/evm/health.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,36 @@
11
#!/usr/bin/env python3
2-
"""Health Check Example - Check API health and connectivity."""
2+
"""Health Check Example - Verify API connectivity in 10 seconds."""
33

44
import anyio
55

66
from thegraph_token_api import TokenAPI
77

88

99
async def main():
10-
print("API Health Check")
11-
print("=" * 16)
10+
print("🏥 API Health Check")
11+
print("=" * 18)
1212

1313
api = TokenAPI()
1414

1515
try:
16-
# Check API health
17-
print("\nChecking API health...")
18-
health_status = await api.health()
19-
print(f"Status: {health_status}")
16+
# Quick health check
17+
print("🔍 Checking API...")
18+
health = await api.health()
2019

21-
if health_status.lower() == "ok":
22-
print("✅ API is healthy")
23-
else:
24-
print("⚠️ API may have issues")
20+
if health.lower() == "ok":
21+
print("✅ API is healthy and ready!")
2522

26-
# Test connectivity with simple call
27-
print("\nTesting connectivity...")
28-
test_data = await api.evm.balances("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", limit=1)
23+
# Quick connectivity test
24+
print("🧪 Testing data access...")
25+
data = await api.evm.balances("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", limit=1)
26+
print(f"✅ Connected! Found {len(data)} balance(s)")
2927

30-
if test_data:
31-
print(f"✅ API call successful - received {len(test_data)} result(s)")
3228
else:
33-
print("⚠️ No data returned")
34-
35-
print("\n✅ Health check completed!")
29+
print(f"⚠️ API status: {health}")
3630

3731
except Exception as e:
38-
print(f"❌ Health check failed: {e}")
32+
print(f"❌ Connection failed: {e}")
33+
print("💡 Check your THEGRAPH_API_KEY environment variable")
3934

4035

4136
if __name__ == "__main__":

0 commit comments

Comments
 (0)