Building Your Own TREZ Mining App: A Developer's Guide
Last updated: October 2025
This guide provides in-depth instructions for developers to create their own mining application for the TREZ token on Solana,
based on the TREZ mining contract (EUBkEwKJJnuenTnocaUHDZUaSegeWWZAFwBTqTRcQ1sJ). It covers interacting with the contract,
implementing mining logic, wallet management, and (optionally) setting up a mining pool for collaborative mining. The guide assumes
familiarity with Python (as used in the reference app trez_miner.py), Solana development, and basic blockchain concepts.
For the full contract source, see programs/trez-mining/src/lib.rs.
The TREZ mining system uses proof-of-work (PoW) with SHA-256 challenges, dynamic difficulty adjustment (targeting ~180-second blocks), referral bonuses (3 TREZ each for miner and referrer), and era-based emission reductions. Rewards are paid from a distributor PDA, ensuring secure on-chain distribution.
Table of Contents
- Prerequisites
- Setting Up the Development Environment
- Understanding the TREZ Mining Contract
- Interacting with the Contract Using Anchorpy
- Implementing Wallet Management
- Building the Mining Logic
- Adding a User Interface (Optional)
- Handling Referrals and Rewards
- Setting Up a Mining Pool
- Security Considerations
- Testing and Deployment
- Resources
Prerequisites
- Languages: Python 3.8+ for the app; Rust if you plan to modify the contract.
- Solana Tools:
- Solana CLI:
sh -c "$(curl -sSfL https://release.solana.com/v1.18.20/install)" - Anchor:
cargo install --git https://github.com/coral-xyz/anchor anchor-cli --locked
- Solana CLI:
- Python Dependencies: install with pip install -r requirements.txt
- Solana RPC Endpoint:
https://api.mainnet-beta.solana.com(mainnet) orhttp://127.0.0.1:8899(localnet). - TREZ Mint:
TREZuzaCxTVsg4U9c4MTe7dterWcLe5LA92PHG12Jez(6 decimals). - IDL:
idl/trez.json(generate with Anchor if needed).
Sample requirements.txt
PyQt5==5.15.9 # Optional GUI
anchorpy==0.19.0 # Program interactions
solana==0.34.3 # RPC client
solders==0.21.0 # Solana types
base58==2.1.1 # Base58 encoding
requests==2.32.3 # HTTP requests
pyperclip==1.9.0 # Optional (UI)
construct==2.10.70 # Binary parsing
typing-extensions==4.12.2
Install
# Linux/macOS
python3 -m pip install -r requirements.txt
# Windows PowerShell
python -m pip install -r requirements.txt
Setting Up the Development Environment
- Clone the Repository
git clone https://github.com/<your-username>/trez-mining.git cd trez-mining - Localnet (for testing)
- Run a validator:
solana-test-validator - Airdrop SOL:
solana airdrop 10 <your-wallet-address> - Deploy (if modifying):
cd programs/trez-mining && anchor build && anchor deploy
- Run a validator:
- Environment Variables
# macOS/Linux export TREZ_RPC_URL="https://api.mainnet-beta.solana.com" export TREZ_MINT="TREZuzaCxTVsg4U9c4MTe7dterWcLe5LA92PHG12Jez" # Windows PowerShell $env:TREZ_RPC_URL="https://api.mainnet-beta.solana.com" $env:TREZ_MINT="TREZuzaCxTVsg4U9c4MTe7dterWcLe5LA92PHG12Jez" - IDL (if needed)
anchor idl init -f programs/trez-mining/src/lib.rs \ --program-id EUBkEwKJJnuenTnocaUHDZUaSegeWWZAFwBTqTRcQ1sJ
Understanding the TREZ Mining Contract
The contract uses PDAs to manage state and authority:
- State PDA: global mining state (challenge, difficulty, block count, era, reward).
- MinerData PDA: per-miner info (referrer, mined totals).
- Distributor PDA: token distribution authority (pays rewards).
Key instructions: initialize, register_user, set_referrer (one-time), claim_reward.
Security is enforced by program-derived addresses and on-chain validation of PoW claims.
Interacting with the Contract Using Anchorpy
Load the Program
import json
from anchorpy import Program, Provider, Wallet, Idl
from solana.rpc.async_api import AsyncClient
from solders.pubkey import Pubkey
from solders.keypair import Keypair
RPC_URL = "https://api.mainnet-beta.solana.com"
PROGRAM_ID = Pubkey.from_string("EUBkEwKJJnuenTnocaUHDZUaSegeWWZAFwBTqTRcQ1sJ")
IDL_PATH = "idl/trez.json"
async def load_program(wallet: Wallet):
client = AsyncClient(RPC_URL)
provider = Provider(client, wallet)
with open(IDL_PATH, "r") as f:
idl_json = json.load(f)
idl = Idl.from_json(idl_json)
program = Program(idl, PROGRAM_ID, provider)
return program, client, provider
Register User
async def register_user(program: Program, user_pubkey: Pubkey):
state_pda = Pubkey.find_program_address([b"state"], PROGRAM_ID)[0]
miner_data_pda = Pubkey.find_program_address([b"miner_data", bytes(user_pubkey)], PROGRAM_ID)[0]
await program.rpc["register_user"](
accounts={{
"miner_data": miner_data_pda,
"state": state_pda,
"user": user_pubkey,
"system_program": Pubkey.from_string("11111111111111111111111111111111"),
}}
)
Set Referrer
async def set_referrer(program: Program, miner_pubkey: Pubkey, referrer_pubkey: Pubkey):
miner_data_pda = Pubkey.find_program_address([b"miner_data", bytes(miner_pubkey)], PROGRAM_ID)[0]
await program.rpc["set_referrer"](
referrer_pubkey,
accounts={{
"miner_data": miner_data_pda,
"miner": miner_pubkey,
"system_program": Pubkey.from_string("11111111111111111111111111111111"),
}}
)
Claim Reward
from spl.token.instructions import get_associated_token_address
async def claim_reward(program: Program, miner_pubkey: Pubkey, nonce: int, digest: bytes):
state_pda = Pubkey.find_program_address([b"state"], PROGRAM_ID)[0]
distributor_pda = Pubkey.find_program_address([b"distributor"], PROGRAM_ID)[0]
trez_mint = Pubkey.from_string("TREZuzaCxTVsg4U9c4MTe7dterWcLe5LA92PHG12Jez")
miner_token = get_associated_token_address(miner_pubkey, trez_mint)
distributor_token = get_associated_token_address(distributor_pda, trez_mint)
await program.rpc["claim_reward"](
nonce, list(digest),
accounts={{
"miner": miner_pubkey,
"state": state_pda,
"miner_token": miner_token,
"distributor_token": distributor_token,
"distributor_authority": distributor_pda,
"token_program": Pubkey.from_string("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
"system_program": Pubkey.from_string("11111111111111111111111111111111"),
}}
)
Implementing Wallet Management
Generate a Wallet
import base58
from solders.keypair import Keypair
def generate_wallet():
kp = Keypair()
return {{
"public_key": str(kp.pubkey()),
"secret_key": base58.b58encode(bytes(kp)).decode(),
}}
Save / Load Wallets
import os, json
def wallets_dir():
base = os.path.join(os.environ.get("APPDATA", os.path.expanduser("~")), "TREZMiner", "wallets")
os.makedirs(base, exist_ok=True)
return base
def save_wallet(data: dict, filename: str):
path = os.path.join(wallets_dir(), filename)
with open(path, "w") as f:
json.dump(data, f, indent=2)
def load_wallet(filename: str):
path = os.path.join(wallets_dir(), filename)
with open(path, "r") as f:
return json.load(f)
Building the Mining Logic
PoW Loop
import hashlib, random
from solders.pubkey import Pubkey
def meets_difficulty(digest: bytes, difficulty: int) -> bool:
u192 = int.from_bytes(digest[:24], "little")
return (u192 >> (192 - difficulty)) == 0
def compute_digest(challenge: bytes, miner_pk: Pubkey, block_count: int, nonce: int) -> bytes:
nonce_b = nonce.to_bytes(8, "little")
miner_b = bytes(miner_pk)
block_b = block_count.to_bytes(8, "little")
return hashlib.sha256(challenge + miner_b + block_b + hashlib.sha256(nonce_b).digest()).digest()
async def mine_once(pubkey: Pubkey, challenge: bytes, difficulty: int, block_count: int):
while True:
nonce = random.getrandbits(64)
digest = compute_digest(challenge, pubkey, block_count, nonce)
if meets_difficulty(digest, difficulty):
return nonce, digest
Integrate with claim_reward
async def mining_cycle(program: Program, pubkey: Pubkey):
state_pda = Pubkey.find_program_address([b"state"], PROGRAM_ID)[0]
state = await program.account["State"].fetch(state_pda)
challenge = bytes(state.challenge_number)
difficulty = int(state.difficulty_high)
block_count = int(state.block_count)
nonce, digest = await mine_once(pubkey, challenge, difficulty, block_count)
await claim_reward(program, pubkey, nonce, digest)
Adding a User Interface (Optional)
Use PyQt5 to build a simple GUI (wallet creation, referrer set, start/stop mining) while using asyncio to keep the UI responsive.
Handling Referrals and Rewards
- Allow users to set a referrer once with
set_referrer(lock after set). - On successful claims, the program pays base reward + 3 TREZ to miner and +3 TREZ to referrer (if set), on-chain.
- Show balances via SPL Token reads and recent claim events.
Setting Up a Mining Pool
A pool aggregates miners and smooths payouts. Implement a WebSocket server that assigns work (challenge, block count, pool difficulty),
validates shares, submits full-difficulty solutions to claim_reward, and distributes rewards (e.g., PPLNS).
See the separate “Creating a TREZ Mining Pool” guide for a full reference implementation.
Security Considerations
- Wallet Security: protect keys (consider OS keychain/HSM); never log secrets.
- Rate Limits: throttle RPC and pool endpoints to prevent DoS.
- Error Handling: retry with backoff; verify transaction results.
- Audits: review nonce handling, PDA derivations, and token transfers.
Testing and Deployment
- Localnet:
solana-test-validatorto iterate quickly. - App Testing: run your miner, verify claims, track balances.
- Packaging: ship binaries (e.g., PyInstaller) for simple installs.
- Monitoring: add logs/metrics (hashrate, solves, errors).
Resources
- Solana Docs: docs.solana.com
- Anchor Framework: anchor-lang.com
- Anchorpy: anchorpy.readthedocs.io
- FastAPI: fastapi.tiangolo.com
- Explorers: Solscan, SolanaFM for verifying transactions/state.
- Contract Source:
programs/trez-mining/src/lib.rs - Reference App:
mining-app/trez_miner.py
This guide is for developers. Mining involves risk and costs. Always test thoroughly before using real funds.
