File size: 6,026 Bytes
b50be44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import requests
import json
import web3

# Global Variables
radio_options = ["Comedy", "Drama", "Documentary"]

# Auxiliary function to disable buttons
def button_disable():
    st.session_state["disabled"] = True


# Changing the App title
st.set_page_config(page_title="IPFS-Based Survey",)

# Page title
st.title('Sample Survey')

# The following code centralizes all the buttons
st.markdown("<style>.row-widget.stButton {text-align: center;}</style>", unsafe_allow_html=True)

# Initialize state
if "current_page" not in st.session_state:
    st.session_state["current_page"] = 1
    st.session_state["Q1"] = ""
    st.session_state["Q2"] = None
    st.session_state["Q3"] = False
    st.session_state["disabled"] = False


# Page 1
if st.session_state["current_page"]  == 1:

    st.header('Please start by watching the video below', divider = 'gray')

    video_file = open('./media/sample-5s.mp4', 'rb')
    video_bytes = video_file.read()

    st.video(video_bytes)
   
    if  st.button('Next'):
       st.session_state["current_page"] += 1
       st.rerun()


# Page 2
elif st.session_state["current_page"]  == 2:

    st.session_state["Q1"] = st.text_area(r"$\textsf{\Large Q1: What is the meaning of life?}$",
                                           value = st.session_state["Q1"])

    st.markdown("# <br>", unsafe_allow_html=True)
       
    option_selected = st.radio(r"$\textsf{\Large Q2: What's your favorite movie genre?}$",
                                radio_options,
                                index = st.session_state["Q2"])
    for i, x in enumerate(radio_options):
        if x == option_selected:
            st.session_state["Q2"] = i
            break
    

    st.markdown("# <br>", unsafe_allow_html=True)

    col1, col2 = st.columns(2)
    with col1:
        if st.button('Back'):
            st.session_state["current_page"] -= 1
            st.rerun()

    with col2:
        if st.button('Next'):
            st.session_state["current_page"] += 1
            st.rerun()


# Page 3
elif st.session_state["current_page"]  == 3:
   
    st.session_state["Q3"] = st.checkbox('Check if you like this survey', 
                                         value = st.session_state["Q3"], 
                                         disabled = st.session_state["disabled"])

    st.markdown("# <br>", unsafe_allow_html=True)

    col1, col2 = st.columns(2)
    with col1:
        button1 = st.button('Back', disabled = st.session_state["disabled"])
        if button1:
            st.session_state["current_page"] -= 1
            st.rerun()

    with col2:
        button2 = st.button('Submit Responses', 
                            disabled = st.session_state["disabled"],
                            on_click = button_disable)
            
    st.markdown("# <br>", unsafe_allow_html=True)
    if st.session_state["disabled"]:     
        with st.spinner(r"$\textsf{\normalsize Storing data on IPFS and Ethereum. This operation might take a few minutes. Please wait!}$"):
                try:
                    response = {'file': json.dumps({"Q1":st.session_state["Q1"],
                                                    "Q2":radio_options[st.session_state["Q2"]],
                                                    "Q3":st.session_state["Q3"]
                                        })
                            }   
                    
                    response = requests.post('https://ipfs.infura.io:5001/api/v0/add', 
                                            files=response, 
                                            auth=(st.secrets["username"], st.secrets["password"]))
                    
                    IPFS_hash = response.json()["Hash"]
                    print(IPFS_hash)
                

                    # Connect to the Ethereum blockchain
                    w3 = web3.Web3(web3.HTTPProvider(st.secrets["infura"]))

                    # Get the contract address
                    caller = "0xbdB61Ada027eF27ef0709D3848Db1Dd13c96F970"
                    
                    ABI = '[ { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "string", "name": "data", "type": "string" } ], "name": "Store", "type": "event" }, { "inputs": [ { "internalType": "string", "name": "_IPFSHash", "type": "string" } ], "name": "storeHash", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ]'

                    # Create a contract instance. Address is equal to the address of the smart contract
                    contract = w3.eth.contract(address= "0x1e14B06209ACD932EF7731632999Cf4aE1b86e5c", abi=ABI)

                    # Call your function: 11155111 is Sepolia's id
                    call_function = contract.functions.storeHash(IPFS_hash).build_transaction({"chainId": 11155111, 
                                                                                            "from": caller,
                                                                                            "nonce": w3.eth.get_transaction_count(caller)}) # Initialize address nonce
    

                    # Sign transaction
                    signed_tx = w3.eth.account.sign_transaction(call_function, private_key=st.secrets["pk"])

                    # Send transaction
                    send_tx = w3.eth.send_raw_transaction(signed_tx.rawTransaction)

                    # Wait for transaction receipt
                    tx_receipt = w3.eth.wait_for_transaction_receipt(send_tx)

                    print(tx_receipt)

                    st.success('Data successfully stored. Thank you for taking the survey!', icon="✅")
                    st.info(f'The IPFS hash is: {IPFS_hash}', icon="ℹ️")
                    st.info(f'The Ethereum hash is: {tx_receipt.logs[0].transactionHash.hex()}', icon="ℹ️")
                
                except Exception as e:
                    print(e)
                    st.error(f'An error ocurred. Here is the error message: {e}', icon="🚨")