DragandDropGroup commited on
Commit
0b203f2
·
verified ·
1 Parent(s): 0572dc2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -3
app.py CHANGED
@@ -3,6 +3,104 @@ import requests
3
  import json
4
  import web3
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  total_number_pages = 4
7
  placeholder_buttons = None
8
 
@@ -46,8 +144,9 @@ if "current_page" not in st.session_state:
46
  # Page 1; Video
47
  if st.session_state["current_page"] == 1:
48
 
49
- st.markdown("""<p class="big-font">This is a test survey</p>""", unsafe_allow_html=True)
50
 
 
51
  st.radio(label = "What is your favorite food?",
52
  options = Q1_radio_options,
53
  index = None if st.session_state["Q1"] == None else st.session_state["Q1"],
@@ -173,13 +272,14 @@ elif st.session_state["current_page"] == 4: # Last Page
173
  if st.session_state["disabled"]:
174
  with st.spinner(r"$\textsf{\normalsize Storing data on IPFS and Ethereum. This operation might take a few minutes. Please wait to receive your confirmation code!}$"):
175
  try:
176
- response = {'file': json.dumps({
177
  "Q1": Q1_radio_options[st.session_state["Q1"]],
178
  "Q2": st.session_state["Q2"],
179
  "Q3": st.session_state["Q3"],
180
  "Q4": st.session_state["Q4"],
181
  "Q5": st.session_state["Q5"],
182
- })}
 
183
  except Exception as e:
184
  print(e)
185
  st.error(f'An error ocurred. Here is the error message: {e}', icon="🚨")
 
3
  import json
4
  import web3
5
 
6
+ abi = [{"anonymous":False,"inputs":[{"indexed":False,"internalType":"string","name":"ipfsHash","type":"string"}],"name":"Store","type":"event"},{"inputs":[],"name":"getHashes","outputs":[{"internalType":"string[]","name":"","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"ipfsHash","type":"string"}],"name":"storeHash","outputs":[],"stateMutability":"nonpayable","type":"function"}]
7
+ # function that uploads the results to ipfs
8
+ def upload_json_to_ipfs(data):
9
+ try:
10
+ url = "https://api.pinata.cloud/pinning/pinJSONToIPFS"
11
+
12
+ print("starting upload to ipfs")
13
+
14
+ # check for JWT secret
15
+ if "PinataJWT" not in st.secrets:
16
+ st.write("No JWT secret found, please add your JWT in a secret titled \"PinataJWT\"")
17
+ return
18
+
19
+ jwt_token = st.secrets["PinataJWT"].strip()
20
+ headers = {
21
+ "Authorization": f"Bearer {jwt_token}",
22
+ "Content-Type": "application/json"
23
+ }
24
+
25
+ # Convert Python dictionary to JSON string
26
+ response = requests.post(url, headers=headers, json=data)
27
+
28
+ if response.status_code == 200:
29
+ # Print the IPFS hash from the successful response
30
+ ipfs_hash = response.json().get("IpfsHash")
31
+ return ipfs_hash
32
+ else:
33
+ st.write(f"Failed to upload JSON. Status code: {response.status_code}")
34
+ st.write(response.text)
35
+ return None
36
+ except Exception as e:
37
+ st.write(f"Error uploading to Pinata: {e}")
38
+
39
+ # function that uploads to blockchain
40
+ def upload_to_blockchain(hash):
41
+ print("starting blockchain upload")
42
+ w3 = web3.Web3(web3.HTTPProvider(st.secrets["infura"]))
43
+
44
+ # create an instance of our contract
45
+ contract = w3.eth.contract(address=st.secrets["ContractAddress"], abi = abi)
46
+
47
+ # Call your function: 11155111 is Sepolia's id
48
+ call_function = contract.functions.storeHash(hash).build_transaction({"chainId": 11155111,
49
+ "from": st.secrets["EthWallet"],
50
+ "nonce": w3.eth.get_transaction_count(st.secrets["EthWallet"])})
51
+
52
+ # Sign transaction
53
+ signed_tx = w3.eth.account.sign_transaction(call_function, private_key=st.secrets["pk"])
54
+
55
+ # Send transaction
56
+ send_tx = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
57
+
58
+ # Wait for transaction receipt
59
+ tx_receipt = w3.eth.wait_for_transaction_receipt(send_tx)
60
+
61
+ print("ETH Hash:")
62
+ print(tx_receipt.logs[0].transactionHash.hex())
63
+
64
+ return tx_receipt.logs[0].transactionHash.hex()
65
+
66
+ def get_ipfs_hashes():
67
+ w3 = web3.Web3(web3.HTTPProvider(st.secrets["infura"]))
68
+
69
+ # Create an instance of the contract
70
+ contract = w3.eth.contract(address=st.secrets["ContractAddress"], abi=abi)
71
+
72
+ # Call the getHashes function
73
+ try:
74
+ ipfs_hashes = contract.functions.getHashes().call()
75
+ return ipfs_hashes
76
+ except Exception as e:
77
+ st.write(f"Error retrieving hashes: {e}")
78
+ return []
79
+
80
+ def retreive_ipfs_hash_data(hashes):
81
+ results = []
82
+ for ipfs_hash in hashes:
83
+ url = f"https://gateway.pinata.cloud/ipfs/{ipfs_hash}"
84
+ try:
85
+ response = requests.get(url)
86
+ if response.status_code == 200:
87
+ data = response.json()
88
+ results.append({"hash": ipfs_hash, "data": data})
89
+ else:
90
+ results.append({"hash": ipfs_hash, "error": f"Failed to retrieve data (status {response.status_code})"})
91
+ except Exception as e:
92
+ results.append({"hash": ipfs_hash, "error": str(e)})
93
+ return results
94
+
95
+
96
+ # function that handles survey submission
97
+ # sets up ipfs and blockchain
98
+ def submission(survey_data):
99
+ ipfs_hash = upload_json_to_ipfs(survey_data)
100
+ if ipfs_hash:
101
+ print("IPFS Upload Successful")
102
+ print(ipfs_hash)
103
+ upload_to_blockchain(ipfs_hash)
104
  total_number_pages = 4
105
  placeholder_buttons = None
106
 
 
144
  # Page 1; Video
145
  if st.session_state["current_page"] == 1:
146
 
147
+ st.markdown("""<p style='font-size:18px ;'>Survey Test</p>""", unsafe_allow_html=True)
148
 
149
+ st.markdown("""<p style='font-size:18px;'>This is a test survey</p>""", unsafe_allow_html=True)
150
  st.radio(label = "What is your favorite food?",
151
  options = Q1_radio_options,
152
  index = None if st.session_state["Q1"] == None else st.session_state["Q1"],
 
272
  if st.session_state["disabled"]:
273
  with st.spinner(r"$\textsf{\normalsize Storing data on IPFS and Ethereum. This operation might take a few minutes. Please wait to receive your confirmation code!}$"):
274
  try:
275
+ response = {
276
  "Q1": Q1_radio_options[st.session_state["Q1"]],
277
  "Q2": st.session_state["Q2"],
278
  "Q3": st.session_state["Q3"],
279
  "Q4": st.session_state["Q4"],
280
  "Q5": st.session_state["Q5"],
281
+ }
282
+ submission(response)
283
  except Exception as e:
284
  print(e)
285
  st.error(f'An error ocurred. Here is the error message: {e}', icon="🚨")