-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_probe.py
More file actions
313 lines (276 loc) · 9.18 KB
/
api_probe.py
File metadata and controls
313 lines (276 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import json
import os
import sys
import requests
from dotenv import load_dotenv
load_dotenv()
API_URL = os.getenv('CATAPULT_API_URL', 'https://public-api.catapult.trade/graphql').strip()
API_KEY = os.getenv('CATAPULT_API_KEY', '').strip()
TOKEN_ID = os.getenv('PROBE_TOKEN_ID', '15836020').strip()
if not API_KEY:
print('CATAPULT_API_KEY is missing in .env')
print('Create a new read-only API key with only Read Tokens / Stream Price scopes.')
sys.exit(1)
HEADER_CANDIDATES = [
('Authorization', f'Bearer {API_KEY}'),
('x-api-key', API_KEY),
('X-API-Key', API_KEY),
]
INTROSPECTION_QUERY = '''
query ApiProbeQueryFields {
__schema {
queryType {
fields {
name
description
args {
name
type {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
'''
TYPE_QUERY = '''
query ApiProbeTypes {
__schema {
types {
name
kind
fields {
name
}
inputFields {
name
type {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
enumValues {
name
}
}
}
}
'''
TOKENS_QUERY = '''
query ApiProbeTokens($input: PublicTokenListInput!) {
tokens(input: $input) {
items {
id
name
symbol
speedMode
initialPrice
price
startDate
endDate
buysCount
sellsCount
uniqueTradersCount
volumeUsdtDrops
rank
}
meta {
firstCursor
lastCursor
hasNextItems
hasPreviousItems
}
}
}
'''
def post_graphql(headers, query, variables=None, operation_name=None):
payload = {'query': query}
if variables is not None:
payload['variables'] = variables
if operation_name is not None:
payload['operationName'] = operation_name
return requests.post(API_URL, headers=headers, json=payload, timeout=30)
def compact_type(type_obj):
if not type_obj:
return 'unknown'
kind = type_obj.get('kind')
name = type_obj.get('name')
inner = type_obj.get('ofType')
if kind == 'NON_NULL':
return compact_type(inner) + '!'
if kind == 'LIST':
return '[' + compact_type(inner) + ']'
return name or kind or 'unknown'
def print_query_fields(data):
fields = data.get('data', {}).get('__schema', {}).get('queryType', {}).get('fields') or []
print('\nAvailable Query fields:')
for field in fields:
args = field.get('args') or []
arg_text = ', '.join(f"{a.get('name')}: {compact_type(a.get('type'))}" for a in args)
if arg_text:
print(f"- {field.get('name')}({arg_text})")
else:
print(f"- {field.get('name')}")
return fields
def schema_maps(type_data):
types = type_data.get('data', {}).get('__schema', {}).get('types') or []
by_name = {}
for item in types:
name = item.get('name')
if name:
by_name[name] = item
return by_name
def print_named_type(by_name, name):
item = by_name.get(name)
if not item:
print(f'- {name}: not found')
return
print(f'\n{name} [{item.get("kind")}]')
for field in item.get('inputFields') or []:
print(f"- {field.get('name')}: {compact_type(field.get('type'))}")
for value in item.get('enumValues') or []:
print(f"- {value.get('name')}")
for field in item.get('fields') or []:
print(f"- {field.get('name')}")
def print_token_related_types(by_name):
print('\nToken/turbo/price related schema types:')
matches = []
for name, item in by_name.items():
if any(word in name.lower() for word in ('token', 'turbo', 'price', 'stream', 'cursor', 'pagination', 'sort')):
field_names = [f.get('name') for f in (item.get('fields') or []) if f.get('name')]
input_names = [f.get('name') for f in (item.get('inputFields') or []) if f.get('name')]
enum_names = [v.get('name') for v in (item.get('enumValues') or []) if v.get('name')]
shown = field_names or input_names or enum_names
matches.append((name, item.get('kind'), shown[:20]))
for name, kind, shown in matches[:120]:
suffix = ''
if shown:
suffix = ' fields=' + ', '.join(shown)
print(f'- {name} [{kind}]{suffix}')
def try_tokens_examples(headers, by_name):
input_type = by_name.get('PublicTokenListInput') or {}
input_fields = [f.get('name') for f in (input_type.get('inputFields') or [])]
pagination_type = by_name.get('CursorPaginationInput') or {}
pagination_fields = [f.get('name') for f in (pagination_type.get('inputFields') or [])]
print('\nTrying read-only tokens(input: ...) examples')
print(f'PublicTokenListInput fields: {input_fields}')
print(f'CursorPaginationInput fields: {pagination_fields}')
pagination_candidates = []
if 'limit' in pagination_fields:
pagination_candidates.append({'limit': 5})
if 'first' in pagination_fields:
pagination_candidates.append({'first': 5})
if 'take' in pagination_fields:
pagination_candidates.append({'take': 5})
if 'size' in pagination_fields:
pagination_candidates.append({'size': 5})
if not pagination_candidates:
pagination_candidates.append({'limit': 5})
candidates = []
for pagination in pagination_candidates:
candidates.append({'pagination': pagination})
candidates.append({
'pagination': pagination,
'sort': {'field': 'StartTime', 'direction': 'Desc'},
})
candidates.append({
'pagination': pagination,
'filter': {'rank': 'Public'},
'sort': {'field': 'StartTime', 'direction': 'Desc'},
})
seen = set()
unique_candidates = []
for candidate in candidates:
key = json.dumps(candidate, sort_keys=True)
if key not in seen:
seen.add(key)
unique_candidates.append(candidate)
for candidate in unique_candidates:
print('\ninput candidate:')
print(json.dumps(candidate, ensure_ascii=False, indent=2))
try:
response = post_graphql(
headers,
TOKENS_QUERY,
variables={'input': candidate},
operation_name='ApiProbeTokens',
)
print(f'status={response.status_code}')
print(response.text[:3000])
data = response.json()
if response.status_code == 200 and not data.get('errors'):
print('\nSUCCESS: tokens query works with this input')
return candidate
except Exception as exc:
print(f'tokens candidate failed: {exc}')
return None
print(f'API_URL={API_URL}')
print(f'TOKEN_ID={TOKEN_ID}')
print('This probe is read-only. It uses GraphQL introspection and tokens query only.')
for i, (header_name, header_value) in enumerate(HEADER_CANDIDATES, start=1):
headers = {
'accept': 'application/json',
'content-type': 'application/json',
header_name: header_value,
}
print('\n' + '=' * 80)
print(f'Test #{i}: {header_name}')
try:
response = post_graphql(headers, INTROSPECTION_QUERY, operation_name='ApiProbeQueryFields')
except Exception as exc:
print(f'request error: {exc}')
continue
print(f'status={response.status_code}')
print(response.text[:1200])
try:
data = response.json()
except Exception:
print('Response is not JSON.')
continue
if response.status_code == 200 and data and not data.get('errors'):
print('\nSUCCESS: this auth header can access schema introspection')
print_query_fields(data)
type_response = post_graphql(headers, TYPE_QUERY, operation_name='ApiProbeTypes')
type_data = type_response.json()
if type_response.status_code == 200 and not type_data.get('errors'):
by_name = schema_maps(type_data)
print_named_type(by_name, 'PublicTokenListInput')
print_named_type(by_name, 'CursorPaginationInput')
print_named_type(by_name, 'CursorPaginationMetaOutput')
print_named_type(by_name, 'TurboTokenListFilterInput')
print_named_type(by_name, 'TurboTokenListSortInput')
print_named_type(by_name, 'TurboTokenListSorting')
print_named_type(by_name, 'SortDirection')
print_named_type(by_name, 'TurboTokenMode')
print_named_type(by_name, 'SpeedMode')
print_named_type(by_name, 'PublicTokenListOutput')
print_token_related_types(by_name)
try_tokens_examples(headers, by_name)
else:
print('Type introspection failed:')
print(type_response.text[:2000])
break
errors = data.get('errors') if isinstance(data, dict) else None
if errors:
print('\nerrors preview:')
print(json.dumps(errors, ensure_ascii=False, indent=2)[:1600])
else:
print('\nNo header candidate succeeded. Check API key scopes and endpoint.')