File size: 9,513 Bytes
635881c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f89223
635881c
 
 
 
 
 
 
 
 
3f89223
635881c
 
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
# metamask_component.py
import os
import json
import streamlit as st
import streamlit.components.v1 as components

# Define the MetaMask component HTML
def get_metamask_component_html():
    """
    Creates an HTML component that can interact with MetaMask browser extension.
    """
    return """
    <script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.8.0/web3.min.js"></script>
    <div id="metamask-connector">
        <div id="metamask-status">
            <p id="connection-status">MetaMask Status: Not Connected</p>
            <p id="wallet-address">Wallet: Not Connected</p>
            <p id="network-name">Network: Unknown</p>
        </div>
        <button id="connect-button" class="metamask-button">Connect MetaMask</button>
        <button id="disconnect-button" class="metamask-button" style="display:none;">Disconnect</button>
    </div>

    <style>
        #metamask-connector {
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
        }
        .metamask-button {
            background-color: #F6851B;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
        .metamask-button:hover {
            background-color: #E2761B;
        }
        #metamask-status {
            margin-bottom: 10px;
        }
    </style>

    <script>
        // Function to check if MetaMask is installed
        function isMetaMaskInstalled() {
            return Boolean(window.ethereum && window.ethereum.isMetaMask);
        }

        // Function to update connection status
        function updateConnectionStatus(connected, address = null, networkName = null) {
            const statusElement = document.getElementById('connection-status');
            const addressElement = document.getElementById('wallet-address');
            const networkElement = document.getElementById('network-name');
            const connectButton = document.getElementById('connect-button');
            const disconnectButton = document.getElementById('disconnect-button');
            
            if (connected) {
                statusElement.textContent = 'MetaMask Status: Connected';
                statusElement.style.color = 'green';
                addressElement.textContent = `Wallet: ${address}`;
                networkElement.textContent = `Network: ${networkName}`;
                connectButton.style.display = 'none';
                disconnectButton.style.display = 'inline-block';
                
                // Send connection info to Streamlit
                const data = {
                    connected: true,
                    address: address,
                    networkName: networkName,
                    networkId: window.ethereum.networkVersion
                };
                window.parent.postMessage({
                    type: "metamask-status",
                    data: data
                }, "*");
            } else {
                statusElement.textContent = 'MetaMask Status: Not Connected';
                statusElement.style.color = 'red';
                addressElement.textContent = 'Wallet: Not Connected';
                networkElement.textContent = 'Network: Unknown';
                connectButton.style.display = 'inline-block';
                disconnectButton.style.display = 'none';
                
                // Send disconnection info to Streamlit
                window.parent.postMessage({
                    type: "metamask-status",
                    data: { connected: false }
                }, "*");
            }
        }

        // Function to get network name
        async function getNetworkName(chainId) {
            const networks = {
                '1': 'Ethereum Mainnet',
                '5': 'Goerli Testnet',
                '11155111': 'Sepolia Testnet',
                '137': 'Polygon Mainnet',
                '80001': 'Mumbai Testnet',
                '56': 'Binance Smart Chain',
                '97': 'BSC Testnet',
                '42161': 'Arbitrum One',
                '421613': 'Arbitrum Goerli',
                '10': 'Optimism',
                '420': 'Optimism Goerli',
                '1337': 'Local Development Chain',
                '31337': 'Hardhat Network'
            };
            
            return networks[chainId] || `Chain ID: ${chainId}`;
        }

        // Function to handle MetaMask connection
        async function connectMetaMask() {
            if (!isMetaMaskInstalled()) {
                alert("MetaMask is not installed. Please install MetaMask and try again.");
                return;
            }

            try {
                // Request account access
                const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                const networkId = await window.ethereum.request({ method: 'eth_chainId' });
                const networkName = await getNetworkName(parseInt(networkId, 16).toString());
                
                if (accounts.length > 0) {
                    updateConnectionStatus(true, accounts[0], networkName);
                }
            } catch (error) {
                console.error("Error connecting to MetaMask:", error);
                alert("Error connecting to MetaMask: " + error.message);
                updateConnectionStatus(false);
            }
        }

        // Handle disconnection (note: MetaMask doesn't have a disconnect method,
        // so this just updates the UI without actually disconnecting)
        function disconnectMetaMask() {
            updateConnectionStatus(false);
        }

        // Add event listeners
        document.addEventListener('DOMContentLoaded', function() {
            // Check if MetaMask is installed
            if (!isMetaMaskInstalled()) {
                document.getElementById('connection-status').textContent = 'MetaMask Status: Not Installed';
                document.getElementById('connect-button').disabled = true;
                document.getElementById('connect-button').title = "Please install MetaMask first";
            }
            
            // Connect button event listener
            document.getElementById('connect-button').addEventListener('click', connectMetaMask);
            
            // Disconnect button event listener
            document.getElementById('disconnect-button').addEventListener('click', disconnectMetaMask);
            
            // Listen for account changes
            if (window.ethereum) {
                window.ethereum.on('accountsChanged', function (accounts) {
                    if (accounts.length === 0) {
                        // User disconnected all accounts
                        updateConnectionStatus(false);
                    } else {
                        // Account changed
                        connectMetaMask();
                    }
                });
                
                // Listen for chain changes
                window.ethereum.on('chainChanged', function (chainId) {
                    // Chain changed, reconnect
                    connectMetaMask();
                });
            }
        });
    </script>
    """

def metamask_connector():
    """
    Component that renders the MetaMask connector UI and returns connection info.
    
    Returns:
        dict: Connection information if connected, None otherwise
    """
    # Generate a unique key for the component
    component_key = "metamask_connector"
    
    # Create a placeholder for the component if it doesn't exist
    if component_key not in st.session_state:
        st.session_state[component_key] = {
            "connected": False,
            "address": None,
            "network_name": None,
            "network_id": None
        }
    
    # Render the HTML component
    components.html(
        get_metamask_component_html(),
        height=200,
        scrolling=False
    )
    
    # JavaScript callback to update session state
    st.markdown("""
    <script>
    window.addEventListener('message', function(event) {
        if (event.data.type === 'metamask-status') {
            window.parent.postMessage({
                type: 'streamlit:setComponentValue',
                value: event.data.data,
                dataType: 'json'
            }, '*');
        }
    });
    </script>
    """, unsafe_allow_html=True)
    
    # For demonstration - since we can't get real callbacks in this version,
    # let's add some manual controls for testing
    col1, col2 = st.columns(2)
    
    with col1:
        if st.button("Simulate Connection"):
            st.session_state[component_key] = {
                "connected": True,
                "address": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
                "network_name": "Ethereum Mainnet",
                "network_id": "1"
            }
            st.rerun()  # Use st.rerun() instead of st.experimental_rerun()
    
    with col2:
        if st.button("Simulate Disconnection"):
            st.session_state[component_key] = {
                "connected": False,
                "address": None,
                "network_name": None,
                "network_id": None
            }
            st.rerun()  # Use st.rerun() instead of st.experimental_rerun()
    
    return st.session_state[component_key]