-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
256 lines (206 loc) · 8.67 KB
/
main.py
File metadata and controls
256 lines (206 loc) · 8.67 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
import os
import sys
import time
import subprocess
import requests
from dotenv import load_dotenv
from utils.args import args
from utils.logger import logger
# Load environment variables
load_dotenv()
# CoinMarketCap API key
CMC_API_KEY = os.getenv("CMC_API_KEY")
if not CMC_API_KEY:
logger.error("CMC_API_KEY is not set in the .env file")
sys.exit(1)
# Global configuration
CMC_API_URL = (
f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest"
f"?CMC_PRO_API_KEY={CMC_API_KEY}&symbol=SUI"
)
SUI_RPC_URL = args.sui_rpc
SUI_BIN_PATH = args.sui_bin_path
SUI_GAS_BUDGET = args.sui_gas_budget
SUI_REF_TOKEN_PRICE = args.sui_ref_token_price
SUI_REF_GAS_PRICE = args.sui_ref_gas_price
SUI_VAL_CAP_OBJECT_ID = args.sui_val_cap_object_id
LAST_UPDATED_EPOCH = None
def get_current_sui_price():
"""Fetch the current SUI price from CoinMarketCap."""
try:
response = requests.get(CMC_API_URL, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("status", {}).get("error_code") != 0:
raise ValueError(f"CMC API Error: {data['status']['error_message']}")
price = data["data"]["SUI"]["quote"]["USD"]["price"]
return round(price, 4)
except Exception as e:
logger.error(f"Failed to fetch SUI price: {e}")
raise
def get_epoch_info():
"""Get the latest epoch information from the SUI RPC endpoint."""
try:
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "suix_getLatestSuiSystemState",
"params": [],
}
headers = {"Content-Type": "application/json"}
response = requests.post(SUI_RPC_URL, json=payload, headers=headers, timeout=10)
response.raise_for_status()
data = response.json()
if "result" not in data:
raise ValueError("No system state data received from RPC")
system_state = data["result"]
current_epoch = int(system_state["epoch"])
epoch_start_timestamp_ms = int(system_state["epochStartTimestampMs"])
epoch_duration_ms = int(system_state["epochDurationMs"])
now = int(time.time() * 1000)
epoch_end_timestamp = epoch_start_timestamp_ms + epoch_duration_ms
remaining_ms = epoch_end_timestamp - now
return {
"current_epoch": current_epoch,
"remaining_ms": remaining_ms,
"epoch_end_timestamp": epoch_end_timestamp,
"epoch_start_timestamp_ms": epoch_start_timestamp_ms,
"epoch_duration_ms": epoch_duration_ms,
}
except Exception as e:
logger.error(f"Failed to fetch epoch information: {e}")
raise
def calculate_new_mist(current_price, reference_price, reference_mist):
"""Calculate the new mist value based on the price change."""
price_ratio = reference_price / current_price
calculated_mist = round(reference_mist * price_ratio)
return min(calculated_mist, 1000)
def update_validator_gas_price(mist_value: int, dry_run: bool = False) -> bool:
try:
command = [
str(SUI_BIN_PATH),
"client",
"--client.config", str(args.sui_client_config_path),
"call",
"--package", "0x3",
"--module", "sui_system",
"--function", "request_set_gas_price",
"--args", "0x5", str(SUI_VAL_CAP_OBJECT_ID), str(mist_value),
"--gas-budget", str(SUI_GAS_BUDGET),
]
if dry_run:
command.append("--dry-run")
logger.info("Executing: %s", " ".join(command))
result = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
)
if result.stdout:
logger.info("Command stdout:\n%s", result.stdout.strip())
if result.stderr:
logger.warning("Command stderr:\n%s", result.stderr.strip())
return result.returncode == 0
except Exception as e:
logger.error(f"Failed to run sui command: {e}")
return False
def process_updates():
"""Check epoch information and update gas price if needed."""
global LAST_UPDATED_EPOCH
try:
epoch_info = get_epoch_info()
remaining_ms = epoch_info["remaining_ms"]
current_epoch = epoch_info["current_epoch"]
# Format remaining time
remaining_hours = remaining_ms // (1000 * 60 * 60)
remaining_minutes = (remaining_ms % (1000 * 60 * 60)) // (1000 * 60)
remaining_seconds = (remaining_ms % (1000 * 60)) // 1000
logger.info(
f"Epoch {current_epoch} | "
f"Time remaining: {remaining_hours}h {remaining_minutes}m {remaining_seconds}s"
)
# Skip if already updated this epoch
if LAST_UPDATED_EPOCH == current_epoch:
logger.info(f"Gas price already updated for epoch {current_epoch}, skipping.")
return
# Update gas price if less than 1 hour remains
if remaining_ms < 60 * 60 * 1000:
current_price = get_current_sui_price()
logger.info(f"Fetched current $SUI price: ${current_price}")
new_mist = calculate_new_mist(
current_price, SUI_REF_TOKEN_PRICE, SUI_REF_GAS_PRICE
)
price_change_percent = (
(current_price - SUI_REF_TOKEN_PRICE) / SUI_REF_TOKEN_PRICE * 100
)
mist_change_percent = (
(new_mist - SUI_REF_GAS_PRICE) / SUI_REF_GAS_PRICE * 100
)
logger.info(
f"SUI Price: ${current_price} ({price_change_percent:.2f}% vs ref ${SUI_REF_TOKEN_PRICE})"
)
logger.info(
f"Mist Value: {new_mist} ({mist_change_percent:.2f}% vs ref {SUI_REF_GAS_PRICE})"
)
pass
if update_validator_gas_price(new_mist):
logger.info(f"Validator gas price updated successfully for epoch {current_epoch}")
LAST_UPDATED_EPOCH = current_epoch
else:
logger.error(f"Validator gas price update failed for epoch {current_epoch}")
except Exception as e:
logger.error(f"Process update failed: {e}")
def main():
logger.info("==============================================================")
logger.info("Starting SUI Gas Price Monitor")
logger.info(
f"Reference values: SUI price=${SUI_REF_TOKEN_PRICE}, "
f"GAS price={SUI_REF_GAS_PRICE} $MIST"
)
# ---- DRY RUN MODE: compute once, run --dry-run, exit ----
if getattr(args, "dry_run", False):
try:
current_price = get_current_sui_price()
logger.info(f"[DRY-RUN] Fetched current $SUI price: ${current_price}")
new_mist = calculate_new_mist(
current_price, SUI_REF_TOKEN_PRICE, SUI_REF_GAS_PRICE
)
price_change_percent = (
(current_price - SUI_REF_TOKEN_PRICE) / SUI_REF_TOKEN_PRICE * 100
)
mist_change_percent = (
(new_mist - SUI_REF_GAS_PRICE) / SUI_REF_GAS_PRICE * 100
)
logger.info(
f"[DRY-RUN] SUI Price: ${current_price} ({price_change_percent:.2f}% vs ref ${SUI_REF_TOKEN_PRICE})"
)
logger.info(
f"[DRY-RUN] Mist Value: {new_mist} ({mist_change_percent:.2f}% vs ref {SUI_REF_GAS_PRICE})"
)
ok = update_validator_gas_price(new_mist, dry_run=True)
if ok:
logger.info("[DRY-RUN] Dry run completed successfully. Exiting.")
logger.info("==============================================================")
sys.exit(0)
else:
logger.error("[DRY-RUN] Dry run failed. Exiting with code 1.")
sys.exit(1)
except Exception as e:
logger.error(f"[DRY-RUN] Failed: {e}")
sys.exit(1)
# ---- NORMAL MODE LOOP ----
try:
while True:
try:
process_updates()
except Exception as e:
logger.error(f"Unexpected error in main loop: {e}")
logger.info("Sleeping for 10 minutes before next check...")
time.sleep(10 * 60)
logger.info("==============================================================")
except KeyboardInterrupt:
logger.info("Keyboard interrupt received. Exiting gracefully...")
sys.exit(0)
if __name__ == "__main__":
main()