admin08077 commited on
Commit
1a7f549
·
verified ·
1 Parent(s): 5259670

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -72
app.py CHANGED
@@ -13,6 +13,7 @@ from datetime import datetime, timedelta
13
 
14
  import streamlit as st
15
  import streamlit_authenticator as stauth
 
16
 
17
  from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, DateTime, ForeignKey
18
  from sqlalchemy.ext.declarative import declarative_base
@@ -21,7 +22,6 @@ from sqlalchemy.orm import sessionmaker, relationship
21
  from werkzeug.security import generate_password_hash, check_password_hash
22
 
23
  import openai
24
- from web3 import Web3, exceptions
25
 
26
  # ========================
27
  # Streamlit Configuration UI
@@ -178,78 +178,56 @@ class Blockchain:
178
 
179
  def load_contract_abi(self):
180
  """
181
- Load the contract ABI from a JSON file.
182
- Replace this method's implementation with the actual ABI loading mechanism.
183
  """
184
- # For demonstration, we'll define a sample ABI. Replace with your actual contract's ABI.
185
- sample_abi = [
186
- {
187
- "anonymous": False,
188
- "inputs": [
189
- {"indexed": False, "internalType": "uint256", "name": "tokenId", "type": "uint256"},
190
- {"indexed": False, "internalType": "address", "name": "owner", "type": "address"},
191
- {"indexed": False, "internalType": "uint256", "name": "value", "type": "uint256"},
192
- {"indexed": False, "internalType": "string", "name": "hash", "type": "string"}
193
- ],
194
- "name": "TokenMinted",
195
- "type": "event"
196
- },
197
- {
198
- "inputs": [
199
- {"internalType": "uint256", "name": "_grade", "type": "uint256"},
200
- {"internalType": "string", "name": "_hash", "type": "string"}
201
- ],
202
- "name": "mintToken",
203
- "outputs": [
204
- {"internalType": "uint256", "name": "", "type": "uint256"}
205
- ],
206
- "stateMutability": "payable",
207
- "type": "function"
208
- },
209
- {
210
- "inputs": [
211
- {"internalType": "uint256", "name": "_tokenId", "type": "uint256"},
212
- {"internalType": "string", "name": "_hash", "type": "string"}
213
- ],
214
- "name": "verifyToken",
215
- "outputs": [],
216
- "stateMutability": "nonpayable",
217
- "type": "function"
218
- }
219
- ]
220
- return sample_abi
221
 
222
- def mint_token(self, owner_address, grade, verification_hash):
223
  """
224
- Mints a new token on the blockchain based on AI grading.
225
- Returns the token ID.
226
  """
227
- nonce = self.web3.eth.get_transaction_count(self.account.address)
228
- tx = self.contract.functions.mintToken(
229
- grade,
230
- verification_hash
231
- ).buildTransaction({
232
- 'from': self.account.address,
233
- 'value': self.web3.toWei('0.01', 'ether'), # Mint fee
234
- 'gas': 300000,
235
- 'gasPrice': self.web3.toWei('20', 'gwei'),
236
- 'nonce': nonce,
237
- })
238
- signed_tx = self.web3.eth.account.sign_transaction(tx, self.private_key)
 
 
 
 
 
 
 
 
 
 
 
 
239
  try:
240
- tx_hash = self.web3.eth.send_raw_transaction(signed_tx.rawTransaction)
241
- receipt = self.web3.eth.wait_for_transaction_receipt(tx_hash)
242
- # Extract token ID from event logs
243
- events = self.contract.events.TokenMinted().processReceipt(receipt)
244
- if events:
245
- token_id = events[0]['args']['tokenId']
246
- return token_id
247
  else:
248
- st.error("❌ TokenMinted event not found.")
249
- return None
250
  except Exception as e:
251
- st.error(f"❌ Blockchain transaction failed: {str(e)}")
252
- return None
253
 
254
  def verify_output(self, token_id, verification_hash):
255
  """
@@ -404,17 +382,21 @@ if authentication_status:
404
  # Grade AI Output
405
  token_amount = calculate_token_grade(ai_output)
406
  if token_amount > 0:
407
- # Mint Token
408
- verification_hash = hashlib.sha256(ai_output.encode()).hexdigest()
409
- token_id = blockchain.mint_token(user.blockchain_address, token_amount, verification_hash)
410
- if token_id:
 
 
 
 
411
  # Update local database
412
  token = Token(
413
  id=str(uuid.uuid4()),
414
  owner_id=user.id,
415
  value=token_amount,
416
  verified=False,
417
- verification_hash=verification_hash
418
  )
419
  session.add(token)
420
  session.commit()
@@ -427,12 +409,14 @@ if authentication_status:
427
  token_id=token.id,
428
  action='minted',
429
  value=token_amount,
430
- hash=verification_hash
431
  )
432
  session.add(transaction)
433
  session.commit()
434
  st.write(f"**Token ID:** {token.id}")
435
  st.write(f"**Tokens Earned:** {token_amount:.2f}")
 
 
436
  else:
437
  st.error("❌ Token amount determined as zero. Please try again.")
438
 
 
13
 
14
  import streamlit as st
15
  import streamlit_authenticator as stauth
16
+ import requests
17
 
18
  from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean, DateTime, ForeignKey
19
  from sqlalchemy.ext.declarative import declarative_base
 
22
  from werkzeug.security import generate_password_hash, check_password_hash
23
 
24
  import openai
 
25
 
26
  # ========================
27
  # Streamlit Configuration UI
 
178
 
179
  def load_contract_abi(self):
180
  """
181
+ Load the contract ABI from 'contract_abi.json'.
 
182
  """
183
+ try:
184
+ with open('contract_abi.json') as f:
185
+ contract_abi = json.load(f)
186
+ return contract_abi
187
+ except FileNotFoundError:
188
+ st.error(" 'contract_abi.json' file not found. Please ensure the ABI file is present.")
189
+ raise
190
+ except json.JSONDecodeError:
191
+ st.error(" Error decoding 'contract_abi.json'. Please ensure it is valid JSON.")
192
+ raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
+ def mint_token_via_api(self, address, token, balance):
195
  """
196
+ Mints tokens by calling the external API endpoint.
197
+ Returns the response status and data.
198
  """
199
+ url = 'https://backend.buildbear.io/node/faucet/erc20/linguistic-doctorstrange-fb0930a4'
200
+ headers = {
201
+ 'accept': '*/*',
202
+ 'accept-language': 'en-US,en;q=0.9',
203
+ 'cache-control': 'no-cache',
204
+ 'content-type': 'application/json',
205
+ 'dnt': '1',
206
+ 'origin': 'https://faucet.buildbear.io',
207
+ 'pragma': 'no-cache',
208
+ 'priority': 'u=1, i',
209
+ 'referer': 'https://faucet.buildbear.io/',
210
+ 'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
211
+ 'sec-ch-ua-mobile': '?0',
212
+ 'sec-ch-ua-platform': '"Chrome OS"',
213
+ 'sec-fetch-dest': 'empty',
214
+ 'sec-fetch-mode': 'cors',
215
+ 'sec-fetch-site': 'same-site',
216
+ 'user-agent': 'Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
217
+ }
218
+ payload = {
219
+ "address": address,
220
+ "token": token,
221
+ "balance": balance
222
+ }
223
  try:
224
+ response = requests.post(url, headers=headers, json=payload)
225
+ if response.status_code == 200:
226
+ return True, response.json()
 
 
 
 
227
  else:
228
+ return False, response.text
 
229
  except Exception as e:
230
+ return False, str(e)
 
231
 
232
  def verify_output(self, token_id, verification_hash):
233
  """
 
382
  # Grade AI Output
383
  token_amount = calculate_token_grade(ai_output)
384
  if token_amount > 0:
385
+ # Mint Token via API
386
+ token_address = user.blockchain_address
387
+ token_contract = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" # Example token address (USDC)
388
+ balance = str(int(token_amount))
389
+ mint_success, mint_response = blockchain.mint_token_via_api(token_address, token_contract, balance)
390
+ if mint_success:
391
+ st.success("✅ Token minted successfully via API!")
392
+ st.write(f"**API Response:** {json.dumps(mint_response, indent=2)}")
393
  # Update local database
394
  token = Token(
395
  id=str(uuid.uuid4()),
396
  owner_id=user.id,
397
  value=token_amount,
398
  verified=False,
399
+ verification_hash=hashlib.sha256(ai_output.encode()).hexdigest()
400
  )
401
  session.add(token)
402
  session.commit()
 
409
  token_id=token.id,
410
  action='minted',
411
  value=token_amount,
412
+ hash=token.verification_hash
413
  )
414
  session.add(transaction)
415
  session.commit()
416
  st.write(f"**Token ID:** {token.id}")
417
  st.write(f"**Tokens Earned:** {token_amount:.2f}")
418
+ else:
419
+ st.error(f"❌ Token minting failed: {mint_response}")
420
  else:
421
  st.error("❌ Token amount determined as zero. Please try again.")
422