0

我是编码新手。我正在尝试通过 html 文件中的 Metamask 连接到钱包。我使用 Moralis SDK。我想通过Moralis.Web3API.account.getNativeBalance({chain: "Rinkeby"})在此处获取 bal 输入图像描述。它在我的 Js 代码中不起作用。但它在浏览器的控制台中工作并正确返回余额。谁能帮我解决我的问题?我应该添加什么吗?

  // connect to Moralis server
  const serverUrl = "https://am8aiexrblny.usemoralis.com:2053/server";
  const appId = "5lcRTWrsHknDsfuxhybsX72SjN6wn4Ba0lJjnxhz";
  Moralis.start({ serverUrl, appId });

  async function login() {
    let user = Moralis.User.current();
    if (!user) {
      user = await Moralis.authenticate();
    }
    console.log("logged in user:", user);
    const userAddress = user.get('ethAddress');
    document.getElementById("walletAddress").innerHTML=userAddress;
    getUserTransactions(user);
    let balance = web3.eth.getBalance(userAddress);
    document.getElementById("balance").innerHTML = balance;
    var version = web3.version.api;
     console.log(version); 
  }
  
  async function logOut() {
    await Moralis.User.logOut();
    document.getElementById("walletAddress").innerHTML=""
    console.log("logged out");
  }

  async function getUserTransactions(user) {
// create query
  const query = new Moralis.Query("EthTransactions");
  query.equalTo("from_address", user.get("ethAddress"));

// subscribe to query updates ** add this**
  const subscription = await query.subscribe();
  handleNewTransaction(subscription);

// run query
  const results = await query.find();
  console.log("user transactions:", results);
}


async function handleNewTransaction(subscription) {
// log each new transaction
subscription.on("create", function(data) {
console.log("new transaction: ", data);
});
}


  //get stats on page load
 

        // bind button click handlers
  document.getElementById("btn-login").onclick = login;
  document.getElementById("btn-logout").onclick = logOut;
<html>
  <head>
    <!-- Moralis SDK code -->
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
  </head>
  <body>
    <h1>Moralis SDK in Site</h1>

    <button id="btn-login">Moralis Login</button>
    <button id="btn-logout">Logout</button>
    <p id="walletAddress"></p>
    <p id="balanc"></p>


    <script type="text/javascript" src="./main_copy.js"></script>
  </body>
</html>

4

0 回答 0