-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhub_spl.py
More file actions
152 lines (121 loc) · 5.23 KB
/
hub_spl.py
File metadata and controls
152 lines (121 loc) · 5.23 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
"""
HUB SPL Token Transfer Module
Handles on-chain HUB token transfers for bounties, airdrops, etc.
"""
import json, struct, os
import base58
from solana.rpc.api import Client
from solders.keypair import Keypair
from solders.pubkey import Pubkey
from solders.instruction import Instruction, AccountMeta
from solders.transaction import Transaction
from solders.message import Message
from solders.compute_budget import set_compute_unit_price
HUB_MINT = Pubkey.from_string("9XtsrWuScT28ocG6T4w9dCF3QYtdZabxmG3EgW1Jnhue")
TOKEN_PROGRAM = Pubkey.from_string("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
ASSOCIATED_TOKEN_PROGRAM = Pubkey.from_string("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")
SYSTEM_PROGRAM = Pubkey.from_string("11111111111111111111111111111111")
RENT = Pubkey.from_string("SysvarRent111111111111111111111111111111111")
# HUB has 6 decimals
HUB_DECIMALS = 6
# Load wallet once
with open('/home/openclaw/.openclaw/workspace/credentials/sol_wallet.json') as f:
_kd = json.load(f)
WALLET_KP = Keypair.from_bytes(base58.b58decode(_kd['private_key']))
WALLET_PUBKEY = WALLET_KP.pubkey()
SOLANA_RPC_URL = os.environ.get("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com")
CLIENT = Client(SOLANA_RPC_URL)
def get_ata(owner: Pubkey, mint: Pubkey = HUB_MINT) -> Pubkey:
"""Derive associated token account address."""
seeds = [bytes(owner), bytes(TOKEN_PROGRAM), bytes(mint)]
ata, _ = Pubkey.find_program_address(seeds, ASSOCIATED_TOKEN_PROGRAM)
return ata
def create_ata_instruction(payer: Pubkey, owner: Pubkey, mint: Pubkey = HUB_MINT) -> Instruction:
"""Create associated token account instruction."""
ata = get_ata(owner, mint)
return Instruction(
program_id=ASSOCIATED_TOKEN_PROGRAM,
accounts=[
AccountMeta(payer, is_signer=True, is_writable=True),
AccountMeta(ata, is_signer=False, is_writable=True),
AccountMeta(owner, is_signer=False, is_writable=False),
AccountMeta(mint, is_signer=False, is_writable=False),
AccountMeta(SYSTEM_PROGRAM, is_signer=False, is_writable=False),
AccountMeta(TOKEN_PROGRAM, is_signer=False, is_writable=False),
],
data=b'',
)
def spl_transfer_instruction(source: Pubkey, dest: Pubkey, owner: Pubkey, amount_raw: int) -> Instruction:
"""SPL Token transfer instruction."""
data = struct.pack('<BQ', 3, amount_raw) # instruction index 3 = Transfer
return Instruction(
program_id=TOKEN_PROGRAM,
accounts=[
AccountMeta(source, is_signer=False, is_writable=True),
AccountMeta(dest, is_signer=False, is_writable=True),
AccountMeta(owner, is_signer=True, is_writable=False),
],
data=data,
)
def ata_exists(ata: Pubkey) -> bool:
"""Check if an associated token account exists."""
resp = CLIENT.get_account_info(ata)
return resp.value is not None
def get_hub_balance(owner_address: str) -> float:
"""Get HUB balance for an address."""
try:
owner = Pubkey.from_string(owner_address)
ata = get_ata(owner)
resp = CLIENT.get_token_account_balance(ata)
if resp.value:
return resp.value.ui_amount or 0.0
except Exception:
pass
return 0.0
def send_hub(recipient_address: str, amount: float) -> dict:
"""
Send HUB tokens to a recipient.
Creates ATA if needed. Returns tx signature or error.
Args:
recipient_address: Solana wallet address (base58)
amount: Amount of HUB to send (human-readable, e.g. 100.0)
Returns:
{"success": True, "signature": "...", "amount": 100.0}
or {"success": False, "error": "..."}
"""
try:
recipient = Pubkey.from_string(recipient_address)
amount_raw = int(amount * (10 ** HUB_DECIMALS))
source_ata = get_ata(WALLET_PUBKEY)
dest_ata = get_ata(recipient)
instructions = []
# Priority fee for reliable inclusion
instructions.append(set_compute_unit_price(50_000))
# Create ATA if it doesn't exist
if not ata_exists(dest_ata):
instructions.append(create_ata_instruction(WALLET_PUBKEY, recipient))
# Transfer
instructions.append(spl_transfer_instruction(source_ata, dest_ata, WALLET_PUBKEY, amount_raw))
# Build and send transaction
recent = CLIENT.get_latest_blockhash()
msg = Message.new_with_blockhash(instructions, WALLET_PUBKEY, recent.value.blockhash)
tx = Transaction.new_unsigned(msg)
tx.sign([WALLET_KP], recent.value.blockhash)
result = CLIENT.send_transaction(tx)
sig = str(result.value)
return {
"success": True,
"signature": sig,
"amount": amount,
"recipient": recipient_address,
"solscan": f"https://solscan.io/tx/{sig}",
}
except Exception as e:
return {"success": False, "error": str(e)}
def get_treasury_balance() -> float:
"""Get Brain's HUB treasury balance."""
return get_hub_balance(str(WALLET_PUBKEY))
if __name__ == "__main__":
print(f"Wallet: {WALLET_PUBKEY}")
print(f"HUB Mint: {HUB_MINT}")
print(f"Treasury: {get_treasury_balance()} HUB")