How to send eth_requestAccounts to Metamask in PyScript?

2024/9/21 8:24:54

I am trying to get address from installed MetaMask on the browser. We used to do this in JS as follow:

  const T1 = async () => {let Address = await window.ethereum.request({method: "eth_requestAccounts",});accountChangeHandler(Address.toString());//   console.log(Address.toString());};

or

let balance = await window.ethereum.request({method: "eth_getBalance",params: [address, "latest"],});

In PyScript, I know we could import js module and use window.ethereum but I am not sure how to send requests with methods. I am aware of pyfetch.

I am failing to see how I could import address or send transactions same as we use to do in JS.

I wrote this PyScript code:

from js import document, alert, window, console
from pyodide import create_proxy
from pyodide.http import pyfetch
import asynciodocument.getElementById("status").innerHTML = "Click the button to check Metamask"async def Check_if_Metamask(param):if not window.ethereum:alert("install metamask")else:document.getElementById("status").innerHTML = "Metamask is already installed"document.getElementById("msg").innerHTML = "Welcome!"# console.log(window.ethereum.request)a = await window.ethereum.request({method: "eth_requestAccounts",})Address = await pyfetch(a, method="Get")output = Addressconsole.log(output)console.log("This is a")console.log(a)def setup():# Create a JsProxy for the callback functionclick_proxy = create_proxy(Check_if_Metamask)# Set the listener to the callbacke = document.getElementById("submit-button2")e.addEventListener("click", click_proxy)setup()

and the associated HTML is as follow

<html><head><title>Button Event Proxy</title><!-- <link rel="stylesheet" href="../Illustration 2/pyscript.css" /> --><link rel="stylesheet" href="./buttoncss.css" /><script defer src="../Illustration 2/pyscript.js"></script></head><body><div id="status">Check Metamask!</div><br /><div id="msg"></div><br /><button class="button-17" id="submit-button2">check</button><py-script src="./code.py"> </py-script></body>
</html>
Answer

When calling javascript functions on DOM from pyscript we have to create a proxy and set it as our callback.

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /><script defer src="https://pyscript.net/alpha/pyscript.js"></script></head><body><button id="connect" style="color:blue" >Connect</button> <py-script>from js import alert, window,console,document# since sending request to metamask async we need thisimport asynciofrom pyodide import create_proxyif not window.ethereum: alert("install metamask")if window.ethereum:button = document.querySelector("button")# you need to pass "event" arg even though you do not use it. Otherwise it will throw this error# TypeError: request_eth() takes 0 positional arguments but 1 was givenasync def request_eth(event):   try:await window.ethereum.request(method="eth_requestAccounts")except Exception as e:console.log(e)function=create_proxy(request_eth)button.addEventListener("click", function,False)   </py-script></body>
</html>
https://en.xdnf.cn/q/119226.html

Related Q&A

Extract strings that start with ${ and end with }

Im trying to extract the strings from a file that start with ${ and ends with } using Python. I am using the code below to do so, but I dont get the expected result.My input file looks like this:Click …

Weibull distribution and the data in the same figure (with numpy and scipy) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

python: use agg with more than one customized function

I have a data frame like this.mydf = pd.DataFrame({a:[1,1,3,3],b:[np.nan,2,3,6],c:[1,3,3,9]})a b c 0 1 NaN 1 1 1 2.0 3 2 3 3.0 3 3 3 6.0 9I would like to have a resulting dataframe like…

sending multiple images using socket python get sent as one to client

I am capturing screenshots from the server, then sending it to the client, but the images get all sent as one big file to the client that keeps expanding in size. This only happens when i send from one…

What are the different methods to retrieve elements in a pandas Series?

There are at least 4 ways to retrieve elements in a pandas Series: .iloc, .loc .ix and using directly the [] operator.Whats the difference between them ? How do they handle missing labels/out of range…

Speaker recognition - Bad Request error on microsoft oxford

I am using the python wrapper that has been given in the SDK section. Ive been trying to enroll a voice file for a created profile using the python API.I was able to create a profile and list all profi…

Remove list of phrases from string

I have an array of phrases: bannedWords = [hi, hi you, hello, and you]I want to take a sentence like "hi, how are tim and you doing" and get this:", how are tim doing"Exact case mat…

ImportError: No module named... (basics?) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…

How to pass python list address

I want to convert c++ code to python. I have created a python module using SWIG to access c++ classes.Now I want to pass the following c++ code to PythonC++#define LEVEL 3double thre[LEVEL] = { 1.0l, 1…

Python open says file doesnt exist when it does

I am trying to work out why my Python open call says a file doesnt exist when it does. If I enter the exact same file url in a browser the photo appears.The error message I get is:No such file or direc…