-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauto_mine.py
More file actions
240 lines (194 loc) · 8.36 KB
/
Copy pathauto_mine.py
File metadata and controls
240 lines (194 loc) · 8.36 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
#!/usr/bin/env python3
"""AgentCoin 自动挖矿脚本 - 直接调用合约,无需 CLI"""
import requests, time, sys, re, logging, os
from web3 import Web3
from dotenv import load_dotenv
load_dotenv()
# ── 配置 ──────────────────────────────────────────────
API_URL = "https://api.agentcoin.site/api/problem/current"
LLM_URL = "https://api.minimax.chat/v1/text/chatcompletion_v2"
LLM_KEY = "sk-cp-41ukit2PquDIZAGnTh9v9kyU_hNZHz0jEcT6UwYdmILS8iQNTVo_b01diWP-gVORSyyEMHwuuzVuMyVA2xRiR3T_JmqFh7bXTEJexSouUEaiw8dBnycrP6I"
LLM_MODEL = "MiniMax-Text-01"
RPC_URL = os.getenv("AGC_RPC_URL", "https://mainnet.base.org")
PRIVATE_KEY = os.getenv("AGC_PRIVATE_KEY", "")
PROBLEM_MANAGER = "0x7D563ae2881D2fC72f5f4c66334c079B4Cc051c6"
AGENT_REGISTRY = "0x5A899d52C9450a06808182FdB1D1e4e23AdFe04D"
REWARD_DISTRIBUTOR = "0xD85aCAC804c074d3c57A422d26bAfAF04Ed6b899"
LOOP_INTERVAL = 300
CLAIM_EVERY = 12
RETRY_WAIT = 30
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("auto_mine")
# ── ABI ──────────────────────────────────────────────
import json
REGISTRY_ABI = json.loads("""[
{"inputs":[{"name":"wallet","type":"address"}],"name":"getAgentIdByWallet","outputs":[{"name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[{"name":"agentId","type":"uint256"}],"name":"isEligibleToMine","outputs":[{"name":"","type":"bool"}],"stateMutability":"view","type":"function"}
]""")
PROBLEM_ABI = json.loads("""[
{"inputs":[{"name":"problemId","type":"uint256"},{"name":"answer","type":"int256"}],"name":"submitAnswer","outputs":[],"stateMutability":"nonpayable","type":"function"}
]""")
REWARD_ABI = json.loads("""[
{"inputs":[{"name":"agentId","type":"uint256"}],"name":"claimableRewards","outputs":[{"name":"","type":"uint256"}],"stateMutability":"view","type":"function"},
{"inputs":[],"name":"claimRewards","outputs":[],"stateMutability":"nonpayable","type":"function"}
]""")
# ── 链上操作 ──────────────────────────────────────────
def init_web3():
w3 = Web3(Web3.HTTPProvider(RPC_URL))
if not w3.is_connected():
log.error(f"无法连接 RPC: {RPC_URL}")
sys.exit(1)
if not PRIVATE_KEY:
log.error("未设置 AGC_PRIVATE_KEY 环境变量")
sys.exit(1)
account = w3.eth.account.from_key(PRIVATE_KEY)
return w3, account
def send_tx(w3, account, func):
tx = func.build_transaction({
"from": account.address,
"nonce": w3.eth.get_transaction_count(account.address),
"gas": 300000,
"gasPrice": w3.eth.gas_price,
"chainId": 8453,
})
signed = account.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
log.info(f"📤 tx: {tx_hash.hex()}")
receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)
status = "✅ 成功" if receipt.status == 1 else "❌ 失败"
log.info(f"{status} (block {receipt.blockNumber})")
return receipt
def get_agent_id(w3, account):
registry = w3.eth.contract(
address=w3.to_checksum_address(AGENT_REGISTRY), abi=REGISTRY_ABI
)
agent_id = registry.functions.getAgentIdByWallet(account.address).call()
if agent_id == 0:
log.error("该钱包未注册 Agent,请先在 agentcoin.site 注册")
return None
return agent_id
def submit_answer(w3, account, problem_id, answer):
pm = w3.eth.contract(
address=w3.to_checksum_address(PROBLEM_MANAGER), abi=PROBLEM_ABI
)
return send_tx(w3, account, pm.functions.submitAnswer(problem_id, int(answer)))
def claim_rewards(w3, account):
registry = w3.eth.contract(
address=w3.to_checksum_address(AGENT_REGISTRY), abi=REGISTRY_ABI
)
reward = w3.eth.contract(
address=w3.to_checksum_address(REWARD_DISTRIBUTOR), abi=REWARD_ABI
)
agent_id = registry.functions.getAgentIdByWallet(account.address).call()
claimable = reward.functions.claimableRewards(agent_id).call()
if claimable == 0:
log.info("💰 无可领取奖励")
return None
log.info(f"💰 领取 {Web3.from_wei(claimable, 'ether')} AGC")
return send_tx(w3, account, reward.functions.claimRewards())
# ── API / LLM ────────────────────────────────────────
def get_problem():
for attempt in range(5):
try:
resp = requests.get(API_URL, timeout=15)
resp.raise_for_status()
data = resp.json()
if data.get("is_active"):
return data
log.info(f"题目未激活,{RETRY_WAIT}s 后重试 ({attempt+1}/5)")
time.sleep(RETRY_WAIT)
except Exception as e:
log.error(f"获取题目失败: {e}")
time.sleep(10)
return None
def ask_llm(question):
try:
resp = requests.post(
LLM_URL,
headers={
"Authorization": f"Bearer {LLM_KEY}",
"Content-Type": "application/json",
},
json={
"model": LLM_MODEL,
"messages": [
{
"role": "system",
"content": "你是一个逻辑专家,请直接给出这道题的整数答案,不要输出任何多余文字。",
},
{"role": "user", "content": question},
],
"temperature": 0,
},
timeout=30,
)
resp.raise_for_status()
data = resp.json()
text = data["choices"][0]["message"]["content"].strip()
m = re.search(r"-?\d+", text)
return m.group(0) if m else text
except Exception as e:
log.error(f"LLM 调用失败: {e}")
return None
def countdown(seconds):
for remaining in range(seconds, 0, -1):
mins, secs = divmod(remaining, 60)
sys.stdout.write(f"\r⏳ 下次拉题: {mins:02d}:{secs:02d} ")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\r" + " " * 30 + "\r")
sys.stdout.flush()
# ── 主循环 ────────────────────────────────────────────
def main():
w3, account = init_web3()
log.info(f"👛 钱包: {account.address}")
agent_id = get_agent_id(w3, account)
if not agent_id:
sys.exit(1)
log.info(f"🤖 Agent ID: {agent_id}")
# 检查挖矿资格
registry = w3.eth.contract(
address=w3.to_checksum_address(AGENT_REGISTRY), abi=REGISTRY_ABI
)
if not registry.functions.isEligibleToMine(agent_id).call():
log.warning("⚠️ 未质押或质押不足 10,000 AGC,可能无法提交答案")
log.warning(" 运行: python mine.py stake --amount 10000")
loop_count = 0
log.info("🚀 AgentCoin 自动挖矿启动")
while True:
loop_count += 1
log.info(f"═══ 第 {loop_count} 轮 ═══")
try:
# 1. 获取题目
problem = get_problem()
if not problem:
log.warning("跳过:无法获取题目")
countdown(LOOP_INTERVAL)
continue
pid = problem["problem_id"]
template = problem.get("template_text") or problem.get("template", "")
log.info(f"题目 #{pid}: {template[:80]}...")
# 2. 替换 Agent ID
question = template.replace("{AGENT_ID}", str(agent_id))
log.info(f"题目: {question}")
# 3. AI 解题
answer = ask_llm(question)
if not answer:
log.warning("跳过:LLM 未返回答案")
countdown(LOOP_INTERVAL)
continue
log.info(f"🧠 答案: {answer}")
# 4. 提交上链
submit_answer(w3, account, pid, answer)
# 5. 定时 claim
if loop_count % CLAIM_EVERY == 0:
claim_rewards(w3, account)
except Exception as e:
log.error(f"本轮异常: {e}")
countdown(LOOP_INTERVAL)
if __name__ == "__main__":
main()