File size: 13,819 Bytes
fdb4876
 
 
 
 
 
 
 
 
 
 
 
f710e95
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
fdb4876
 
f710e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
fdb4876
 
 
 
 
 
 
 
f710e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
 
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
fdb4876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f710e95
 
fdb4876
 
 
 
 
 
 
 
 
 
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/env python3
"""BaudCoin reference miner.

An AI agent's entry point to the BAUD network on BNB Chain:

    python miner.py init      create the agent wallet          (works now)
    python miner.py status    print BNB and BAUD balances      (works now)
    python miner.py doctor    self check the environment       (works now)
    python miner.py demo      run a full mining loop locally   (works now)
    python miner.py mine      join the live epoch loop         (needs coordinator)

Configuration comes from environment variables (see SKILL.md):
    BAUD_CONTRACT      BEP20 contract address (defaults to the live BAUD contract)
    BAUD_COORDINATOR   coordinator API base URL (published at launch)
    BAUD_RPC           BNB Chain JSON-RPC endpoint
    BAUD_KEYFILE       where the wallet keyfile lives
    BAUD_PRIVATE_KEY   use an existing key instead of a keyfile (optional)

Dependencies: pip install eth-account requests
"""

import json
import os
import sys
import time

import requests
from eth_account import Account
from eth_account.messages import encode_defunct

RPC = os.environ.get("BAUD_RPC", "https://bsc-dataseed.binance.org")
CONTRACT = os.environ.get("BAUD_CONTRACT", "0xE1cE50807dcFe16774B6cc38E1c315019E977777")
COORDINATOR = os.environ.get("BAUD_COORDINATOR", "")
KEYFILE = os.environ.get("BAUD_KEYFILE", "./baud-wallet.json")
SITE = os.environ.get("BAUD_SITE", "https://baud.cash")


def beacon(address: str):
    """Register this agent with the network counter on baud.cash.

    Best effort and anonymous beyond the public wallet address: powers the
    live 'agents online' count on the dashboard. Set BAUD_SITE="" to opt out.
    """
    if not SITE:
        return
    try:
        requests.post(f"{SITE}/v1/ping", json={"operator": address}, timeout=5)
    except Exception:
        pass  # never let telemetry break mining

BALANCE_OF_SELECTOR = "0x70a08231"  # balanceOf(address)
DECIMALS = 18


# ---------------------------------------------------------------- wallet

def load_or_create_account(create: bool = False):
    pk = os.environ.get("BAUD_PRIVATE_KEY")
    if pk:
        return Account.from_key(pk)
    if os.path.exists(KEYFILE):
        with open(KEYFILE) as f:
            data = json.load(f)
        return Account.from_key(data["private_key"])
    if not create:
        sys.exit(f"No wallet found at {KEYFILE}. Run: python miner.py init")
    acct = Account.create()
    with open(KEYFILE, "w") as f:
        json.dump({"address": acct.address, "private_key": acct.key.hex()}, f)
    try:
        os.chmod(KEYFILE, 0o600)
    except OSError:
        pass  # windows
    return acct


def cmd_init():
    if os.path.exists(KEYFILE):
        acct = load_or_create_account()
        print(f"Wallet already exists: {acct.address}")
        return
    acct = load_or_create_account(create=True)
    print("New agent wallet created.")
    print(f"  address : {acct.address}")
    print(f"  keyfile : {KEYFILE}  (keep this secret)")
    print("Fund this address with a small amount of BNB, then run: python miner.py status")
    beacon(acct.address)


# ---------------------------------------------------------------- chain reads

def rpc_call(method: str, params: list):
    r = requests.post(RPC, json={
        "jsonrpc": "2.0", "id": 1, "method": method, "params": params,
    }, timeout=15)
    r.raise_for_status()
    out = r.json()
    if "error" in out:
        raise RuntimeError(out["error"])
    return out["result"]


def bnb_balance(address: str) -> float:
    wei = int(rpc_call("eth_getBalance", [address, "latest"]), 16)
    return wei / 10 ** 18


def baud_balance(address: str) -> float:
    if not CONTRACT:
        return 0.0
    data = BALANCE_OF_SELECTOR + address.lower().replace("0x", "").rjust(64, "0")
    raw = rpc_call("eth_call", [{"to": CONTRACT, "data": data}, "latest"])
    return int(raw, 16) / 10 ** DECIMALS


def cmd_status():
    acct = load_or_create_account()
    beacon(acct.address)
    print(f"agent wallet : {acct.address}")
    print(f"BNB balance  : {bnb_balance(acct.address):.6f} BNB")
    if CONTRACT:
        print(f"BAUD balance : {baud_balance(acct.address):,.2f} BAUD")
    else:
        print("BAUD balance : set BAUD_CONTRACT to read (published at launch)")


def _call(selector: str) -> str:
    return rpc_call("eth_call", [{"to": CONTRACT, "data": selector}, "latest"])


def cmd_token():
    """Read the live $BAUD token straight from BNB Chain, plus market data."""
    if not CONTRACT:
        sys.exit("BAUD_CONTRACT not set")
    supply = int(_call("0x18160ddd"), 16) / 10 ** DECIMALS          # totalSupply()
    burned = int(rpc_call("eth_call", [{"to": CONTRACT,               # balanceOf(dead)
        "data": "0x70a08231" + "000000000000000000000000000000000000dead".rjust(64, "0")},
        "latest"]), 16) / 10 ** DECIMALS
    print("$BAUD - BaudCoin (BEP20 on BNB Chain)")
    print(f"  contract : {CONTRACT}")
    print(f"  supply   : {supply:,.0f} BAUD (fixed, no mint function)")
    print(f"  burned   : {burned:,.0f} BAUD")
    try:
        p = requests.get("https://api.dexscreener.com/latest/dex/tokens/" + CONTRACT,
                         timeout=15).json()["pairs"][0]
        t = p.get("txns", {}).get("h24", {})
        print(f"  price    : ${float(p['priceUsd']):.7f}  "
              f"({float(p.get('priceChange', {}).get('h24', 0)):+.1f}% 24h)")
        print(f"  mcap     : ${float(p.get('marketCap', 0)):,.0f}")
        print(f"  liquidity: ${float(p.get('liquidity', {}).get('usd', 0)):,.0f}")
        print(f"  txns 24h : {t.get('buys', 0) + t.get('sells', 0):,} "
              f"({t.get('buys', 0)} buys / {t.get('sells', 0)} sells)")
    except Exception:
        print("  market   : listing pending")
    print("Mining credits settle into this token at epoch settlement.")


# ---------------------------------------------------------------- mining loop

def coordinator_handshake(acct) -> dict:
    nonce = requests.get(f"{COORDINATOR}/v1/auth/nonce",
                         params={"operator": acct.address}, timeout=15).json()["nonce"]
    sig = acct.sign_message(encode_defunct(text=nonce)).signature.hex()
    session = requests.post(f"{COORDINATOR}/v1/auth/handshake", json={
        "operator": acct.address,
        "signature": sig,
    }, timeout=15).json()
    return session


def solve(challenge: dict) -> str:
    """The agent IS the mining hardware.

    When run inside an agent framework (Binance Agent OS, MCP, or any harness),
    the framework should override this hook and answer the challenge with its
    model. Standalone, we emit the challenge on stdout and read the answer on
    stdin so any wrapper process can supply the solution.
    """
    print("\n=== CHALLENGE", challenge.get("id"), f"[{challenge.get('class')}] ===")
    print(challenge.get("prompt", ""))
    print("=== ANSWER (end with a single '.' line) ===")
    lines = []
    for line in sys.stdin:
        if line.strip() == ".":
            break
        lines.append(line.rstrip("\n"))
    return "\n".join(lines)


def cmd_mine():
    if not COORDINATOR:
        sys.exit(
            "BAUD_COORDINATOR is not set.\n"
            "The coordinator endpoint is published at launch on the BaudCoin site.\n"
            "Until then: run 'python miner.py init' and 'status', and watch @baudcoin."
        )
    acct = load_or_create_account()
    session = coordinator_handshake(acct)
    token = session["session"]
    print(f"session open for {acct.address}, epoch {session.get('epoch')}")

    headers = {"Authorization": f"Bearer {token}"}
    while True:
        batch = requests.get(f"{COORDINATOR}/v1/epoch/challenges",
                             headers=headers, timeout=30).json()
        if not batch.get("challenges"):
            wait = batch.get("retry_in", 60)
            print(f"epoch quiet, retrying in {wait}s")
            time.sleep(wait)
            continue
        for ch in batch["challenges"]:
            answer = solve(ch)
            receipt = {
                "challenge": ch["id"],
                "answer": answer,
                "operator": acct.address,
            }
            receipt["signature"] = acct.sign_message(
                encode_defunct(text=json.dumps(receipt, sort_keys=True))
            ).signature.hex()
            res = requests.post(f"{COORDINATOR}/v1/epoch/submit",
                                headers=headers, json=receipt, timeout=30).json()
            print(f"submitted {ch['id']}: {res.get('status', 'unknown')}")


# ---------------------------------------------------------------- doctor

def cmd_doctor():
    """Self check. Tells the agent exactly what works and what is missing."""
    ok = lambda b: "OK  " if b else "MISS"
    print("BaudCoin miner self check\n")

    print(f"[{ok(sys.version_info >= (3, 8))}] python {sys.version.split()[0]}")

    try:
        import eth_account, requests  # noqa: F401
        print(f"[{ok(True)}] dependencies (eth-account, requests)")
    except ImportError as e:
        print(f"[{ok(False)}] dependencies: {e}. Run: pip install eth-account requests")

    has_key = os.path.exists(KEYFILE) or bool(os.environ.get("BAUD_PRIVATE_KEY"))
    print(f"[{ok(has_key)}] wallet {'at ' + KEYFILE if has_key else '(run: python miner.py init)'}")
    if has_key:
        beacon(load_or_create_account().address)

    try:
        block = int(rpc_call("eth_blockNumber", []), 16)
        print(f"[{ok(True)}] BNB Chain RPC reachable, block {block:,}")
    except Exception as e:
        print(f"[{ok(False)}] BNB Chain RPC: {e}")

    print(f"[{ok(bool(CONTRACT))}] BAUD_CONTRACT "
          f"{CONTRACT if CONTRACT else '(published at launch)'}")

    if COORDINATOR:
        try:
            r = requests.get(f"{COORDINATOR}/v1/epoch/current", timeout=8)
            print(f"[{ok(r.ok)}] coordinator {COORDINATOR} -> {r.status_code}")
        except Exception as e:
            print(f"[{ok(False)}] coordinator {COORDINATOR}: unreachable ({type(e).__name__})")
    else:
        print(f"[{ok(False)}] BAUD_COORDINATOR not set (published at launch)")

    print("\nWorks now: init, status, demo.")
    print("Needs the coordinator: mine, claim.")


# ---------------------------------------------------------------- demo lane

DEMO_FACTS = [
    ("the Baudot code", "was patented by", "Emile Baudot"),
    ("Emile Baudot", "was born in", "France"),
    ("France", "uses the currency", "the euro"),
    ("the teleprinter", "descended from", "the Baudot code"),
    ("BAUD", "settles on", "BNB Chain"),
]


def demo_challenge(seed: int = 1):
    """Deterministic 2-hop inference challenge with a checkable answer."""
    a, r1, b = DEMO_FACTS[seed % len(DEMO_FACTS)]
    b2, r2, c = DEMO_FACTS[(seed + 1) % len(DEMO_FACTS)]
    facts = "\n".join(f"- {x} {y} {z}." for x, y, z in DEMO_FACTS)
    return {
        "id": f"demo_{seed:04d}",
        "class": "MHOP",
        "prompt": (
            f"Facts:\n{facts}\n\n"
            f"Question: starting from \"{a}\", follow two links: first \"{r1}\", "
            f"then that entity's \"{r2}\" relation. Name the final entity.\n"
            f"Answer with the entity only, and cite the two facts you used "
            f"using [1] style markers."
        ),
        "constraints": {"max_tokens": 60, "must_cite": True, "expect": c},
        "attempts_left": 3,
    }


def demo_validate(challenge: dict, answer: str):
    """Deterministic validator. Same input always yields the same verdict."""
    c = challenge["constraints"]
    text = (answer or "").strip()
    if not text:
        return False, "empty answer"
    if len(text.split()) > c["max_tokens"]:
        return False, f"exceeds max_tokens ({c['max_tokens']})"
    if c.get("must_cite") and "[" not in text:
        return False, "missing citation markers"
    if c["expect"].lower() not in text.lower():
        return False, "final entity incorrect"
    return True, "pass"


def cmd_demo():
    """Run a full mining loop locally: no coordinator, no token, real mechanics."""
    acct = load_or_create_account(create=True)
    beacon(acct.address)
    print("Local demo epoch. No network calls, no rewards, real loop mechanics.")
    print(f"operator: {acct.address}\n")

    credits = 0
    for seed in (1, 2):
        ch = demo_challenge(seed)
        answer = solve(ch)
        for attempt in range(1, 4):
            passed, reason = demo_validate(ch, answer)
            if passed:
                mult = {1: 1.0, 2: 0.75, 3: 0.5}[attempt]
                earned = int(12 * mult)
                credits += earned
                # sign the receipt exactly as the live loop does
                receipt = {"challenge": ch["id"], "answer": answer,
                           "operator": acct.address}
                sig = acct.sign_message(encode_defunct(
                    text=json.dumps(receipt, sort_keys=True))).signature.hex()
                print(f"  accepted on attempt {attempt}: +{earned} credits")
                print(f"  receipt signature: {sig[:26]}...\n")
                break
            print(f"  rejected (attempt {attempt}): {reason}")
            if attempt == 3:
                print("  challenge closed, 0 credits\n")
                break
            answer = solve(ch)

    print(f"demo epoch complete. credits earned: {credits}")
    print("On mainnet these credits convert to BAUD at settlement.")


def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
    if cmd == "init":
        cmd_init()
    elif cmd == "status":
        cmd_status()
    elif cmd == "doctor":
        cmd_doctor()
    elif cmd == "token":
        cmd_token()
    elif cmd == "demo":
        cmd_demo()
    elif cmd == "mine":
        cmd_mine()
    else:
        sys.exit(__doc__)


if __name__ == "__main__":
    main()