-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
187 lines (134 loc) · 5.37 KB
/
Copy pathapp.py
File metadata and controls
187 lines (134 loc) · 5.37 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
# Imports
##################################################################################
import os
import json
from web3 import Web3
from pathlib import Path
from dotenv import load_dotenv
import streamlit as st
from datetime import datetime
from web3.gas_strategies.time_based import medium_gas_price_strategy
from web3.middleware import geth_poa_middleware
# Initial Configurations
#################################################################################
load_dotenv()
# Define and connect a new Web3 provider
w3 = Web3(Web3.HTTPProvider(os.getenv("WEB3_PROVIDER_URI")))
# Set streamlit page configuration
st.set_page_config(page_title="CryptoBaras Minter", page_icon="🪙")
# Contract Helper function:
# 1. Loads the contract once using cache
# 2. Connects to the contract using the contract address and ABI
################################################################################
# Cache the contract on load
@st.cache(allow_output_mutation=True)
# Define the load_contract function
def load_contract():
# Load Art Gallery ABI
with open(Path('./contract_abi.json')) as f:
contract_abi = json.load(f)
# Set the contract address (this is the address of the deployed contract)
contract_address = os.getenv("SMART_CONTRACT_ADDRESS")
# Get the contract
contract = w3.eth.contract(
address=contract_address,
abi=contract_abi
)
# Return the contract from the function
return contract
# Load the contract
contract = load_contract()
# User-Friendly Interface
################################################################################
# Set title
title = '<h1 style="font-family:Freestyle Script; font-size: 130px;"><center>CryptoBaras Minter</center></p>'
st.markdown(title, unsafe_allow_html=True)
# Set page banner
st.image('images/preview.gif')
st.markdown("---")
# Interact with contract
##########################
st.markdown("## There's only 100 CryptoBaras in Existence")
st.markdown("Check how many are left for you to mint:")
if st.button("Check Available"):
total_supply = contract.functions.totalSupply().call()
token_list = st.write(100-total_supply)
st.markdown("## How Much Does a CryptoBara Cost?")
st.markdown("Click on **Cost** to retrieve the price of a CryptoBara in **Wei**:")
if st.button("Cost"):
cost = contract.functions.cost().call()
st.write(cost)
st.markdown("---")
# Make a transaction
###########################
st.markdown("## Mint Your Own CryptoBara")
mintAmount = 1
# Enter the purchaser's (To) wallet address
minter_address = st.text_input("Enter Rinkeby Address")
# Enter contract owner's wallet address
contractowner_address = str(os.getenv("CONTRACT_OWNER_ADDRESS"))
contractowner_private_key = os.getenv("CONTRACT_OWNER_PRIVATE_KEY")
# Get Gas Estimate
value = w3.toWei(0.02,'ether')
w3.eth.setGasPriceStrategy(medium_gas_price_strategy)
# Get the nonce
nonce = w3.eth.get_transaction_count(contractowner_address)
# Middleware
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
# Mint Button
if st.button("Mint"):
# Show loading widget
with st.spinner(text='Wait for it...'):
value = value*mintAmount
if minter_address == contractowner_address:
value = 0
print(datetime.now(), "Amount: ", mintAmount, " Nonce:", nonce, " Minting to wallet: ", minter_address)
transaction = {
"from": contractowner_address,
"gas": 3000000,
"gasPrice": w3.eth.generate_gas_price(),
"value": value,
"nonce": nonce
}
# Build the transaction
transaction_build = contract.functions.mint(mintAmount, minter_address).buildTransaction(transaction)
print(datetime.now(), "transaction built")
# Sign transaction
signed_tx = w3.eth.account.sign_transaction(transaction_build, contractowner_private_key)
print(datetime.now(), "transaction signed")
# Send transaction
txn_raw = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
print(datetime.now(), "raw transaction sent")
# Obtain transaction receipt
txn_receipt = w3.eth.wait_for_transaction_receipt(txn_raw)
print(dict(txn_receipt))
# Show receipt to user
st.success('Done')
st.balloons()
st.write("Transaction receipt mined:")
st.write(dict(txn_receipt))
st.markdown("---")
# See Token URI
#########################
st.markdown("## Take a Look at Your Tokens")
st.markdown("Enter Owner Address and Hit the **Check Tokens** button to retrieve TokenIds for all of your CryptoBaras:")
minter_address = st.text_input("Owner Address")
if st.button("Check Tokens"):
tokens_by_owner = contract.functions.walletOfOwner(minter_address).call()
st.write("Tokens You Own:", tokens_by_owner)
see_token = st.text_input("Enter TokenID You'd Like to See:")
if st.button("Get Metadata"):
token_uri = contract.functions.tokenURI(int(see_token)).call()
ipfs_hash = token_uri[7:]
print(ipfs_hash)
st.markdown(f"Go to: [IPFS Gateway Link](https://ipfs.io/ipfs/{ipfs_hash})")
# Hide Streamlit Style
#################################################################################
hide_st_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
</style>
"""
st.markdown(hide_st_style, unsafe_allow_html=True)