-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
270 lines (250 loc) · 11.5 KB
/
app.py
File metadata and controls
270 lines (250 loc) · 11.5 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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# app.py
import os
import sys
import requests
import json
from flask import Flask, request, jsonify
from web3 import Web3
from src.config import w3, CONTRACT_ADDRESS, OWNER_ADDRESS, OWNER_PRIVATE_KEY
from time import time
app = Flask(__name__)
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GITHUB_REPO = "EricTylerZ/StagQuest"
STATUS_FILE = "data/stag_status.json" # For GitHub upload
ABI_URL = f"https://raw.githubusercontent.com/EricTylerZ/StagQuest/main/data/abi.json?t={int(time())}" # Use main’s ABI
def load_json_from_url(url):
response = requests.get(url)
if response.status_code == 200:
return response.json()
raise Exception(f"Failed to load {url}: Status {response.status_code}")
try:
abi = load_json_from_url(ABI_URL)
contract = w3.eth.contract(address=CONTRACT_ADDRESS, abi=abi)
except Exception as e:
app.logger.error(f"Failed to load ABI: {e}")
contract = None
def update_github_file(content):
if not GITHUB_TOKEN:
app.logger.error("GITHUB_TOKEN not set")
return False
file_path = STATUS_FILE
api_url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{file_path}"
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
get_response = requests.get(api_url, headers=headers)
sha = get_response.json().get("sha") if get_response.status_code == 200 else None
payload = {"message": f"Update {file_path}", "content": "", "branch": "version-b"}
if sha:
payload["sha"] = sha
import base64
payload["content"] = base64.b64encode(json.dumps(content, indent=2).encode()).decode()
response = requests.put(api_url, headers=headers, json=payload)
if response.status_code in [200, 201]:
app.logger.info(f"Successfully updated {file_path} on GitHub: {response.status_code}")
return True
else:
app.logger.error(f"Failed to update {file_path} on GitHub: {response.status_code} - {response.text}")
return False
@app.route("/api/mint", methods=["POST"])
def mint():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
try:
data = request.get_json() or {}
amount = data.get("amount", "0.0001")
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
tx = contract.functions.mintStag().build_transaction({
"from": OWNER_ADDRESS,
"value": w3.to_wei(amount, "ether"),
"nonce": nonce,
"gas": 300000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_tx = w3.eth.account.sign_transaction(tx, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
token_id = None
for log in receipt["logs"]:
if log["topics"][0].hex() == w3.keccak(text="Transfer(address,address,uint256)").hex():
token_id = int(log["topics"][3].hex(), 16)
break
if token_id:
update_github_file(get_status_data())
return jsonify({"message": "Stag minted", "tokenId": token_id, "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Mint succeeded but no tokenId found", "txHash": tx_hash.hex()}), 500
return jsonify({"error": "Minting failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Mint failed: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/api/novena", methods=["POST"])
def start_novena():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
data = request.get_json()
stag_id = data.get("stagId")
amount = data.get("amount", "0")
if not stag_id or not isinstance(stag_id, int):
return jsonify({"error": "Invalid or missing stagId"}), 400
try:
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
tx = contract.functions.startNovena(stag_id).build_transaction({
"from": OWNER_ADDRESS,
"value": w3.to_wei(amount, "ether"),
"nonce": nonce,
"gas": 300000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_tx = w3.eth.account.sign_transaction(tx, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
update_github_file(get_status_data())
return jsonify({"message": f"Novena started for stagId {stag_id}", "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Novena start failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Novena start failed for stagId {stag_id}: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/api/complete-novena", methods=["POST"])
def complete_novena():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
data = request.get_json()
stag_id = data.get("stagId")
successful_days = data.get("successfulDays", 0)
if not stag_id or not isinstance(stag_id, int) or not isinstance(successful_days, int) or successful_days > 9:
return jsonify({"error": "Invalid stagId or successfulDays (0-9)"}), 400
try:
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
txn = contract.functions.completeNovena(stag_id, successful_days).build_transaction({
"from": OWNER_ADDRESS,
"nonce": nonce,
"gas": 300000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_txn = w3.eth.account.sign_transaction(txn, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_txn.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
update_github_file(get_status_data())
return jsonify({"stagId": stag_id, "successfulDays": successful_days, "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Completion failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Completion failed for stagId {stag_id}: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/api/batch-complete-novena", methods=["POST"])
def batch_complete_novena():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
data = request.get_json()
stag_ids = data.get("stagIds", [])
successes = data.get("successfulDays", [])
if not stag_ids or not isinstance(stag_ids, list) or len(stag_ids) != len(successes):
return jsonify({"error": "Invalid stagIds or successfulDays array"}), 400
try:
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
txn = contract.functions.batchCompleteNovena(stag_ids, successes).build_transaction({
"from": OWNER_ADDRESS,
"nonce": nonce,
"gas": 5000000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_txn = w3.eth.account.sign_transaction(txn, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_txn.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
update_github_file(get_status_data())
return jsonify({"message": "Batch completion successful", "stagIds": stag_ids, "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Batch completion failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Batch completion failed: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/api/transfer", methods=["POST"])
def transfer():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
data = request.get_json()
stag_id = data.get("stagId")
to_address = data.get("toAddress")
if not stag_id or not isinstance(stag_id, int) or not Web3.is_address(to_address):
return jsonify({"error": "Invalid stagId or toAddress"}), 400
try:
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
tx = contract.functions.transferFrom(OWNER_ADDRESS, to_address, stag_id).build_transaction({
"from": OWNER_ADDRESS,
"nonce": nonce,
"gas": 300000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_tx = w3.eth.account.sign_transaction(tx, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
update_github_file(get_status_data())
return jsonify({"message": f"Stag {stag_id} transferred to {to_address}", "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Transfer failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Transfer failed for stagId {stag_id}: {e}")
return jsonify({"error": str(e)}), 500
def get_status_data():
if not contract:
return {"stags": [], "error": "Contract not initialized"}
try:
next_token_id = contract.functions.nextTokenId().call()
stags = []
for token_id in range(1, next_token_id):
try:
owner = contract.functions.ownerOf(token_id).call()
family_size = contract.functions.familySize(token_id).call()
has_novena = contract.functions.hasActiveNovena(token_id).call()
successful_days = contract.functions.successfulDays(token_id).call()
stag_data = {
"tokenId": token_id,
"owner": owner,
"familySize": int(family_size),
"hasActiveNovena": has_novena,
"successfulDays": int(successful_days)
}
stags.append(stag_data)
except Exception as e:
app.logger.error(f"Failed to fetch status for tokenId {token_id}: {e}")
continue
return {"stags": stags}
except Exception as e:
app.logger.error(f"Status fetch failed: {e}")
return {"stags": []}
@app.route("/api/status", methods=["GET"])
def status():
status_data = get_status_data()
return jsonify(status_data), 200
@app.route("/api/owner-withdraw", methods=["POST"])
def owner_withdraw():
if not contract:
return jsonify({"error": "Contract not initialized"}), 500
try:
nonce = w3.eth.get_transaction_count(OWNER_ADDRESS)
tx = contract.functions.withdrawOwnerFunds().build_transaction({
"from": OWNER_ADDRESS,
"nonce": nonce,
"gas": 300000,
"gasPrice": w3.to_wei("5", "gwei"),
"chainId": 84532
})
signed_tx = w3.eth.account.sign_transaction(tx, OWNER_PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
if receipt.status == 1:
return jsonify({"message": "Owner funds withdrawn", "txHash": tx_hash.hex()}), 200
return jsonify({"error": "Owner withdrawal failed", "txHash": tx_hash.hex()}), 500
except Exception as e:
app.logger.error(f"Owner withdrawal failed: {e}")
return jsonify({"error": str(e)}), 500
@app.route("/", methods=["GET"])
def home():
return "StagQuest Owner API", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)