简体   繁体   English

通过 web3.js 调用和访问智能合约功能?

[英]Call and access smart contract function through web3.js?

I need to know how can I call these methods through web3.js into my frontend which is in react and also the structure data.我需要知道如何通过 web3.js 将这些方法调用到我的前端,它在反应中以及结构数据中。

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

struct customer {
   uint256 amount;
}

contract Lottery {
    address payable public admin;
    address payable[] public add;
    mapping(address => customer) public data;
   
  function getBalance() public view onlyOwner returns (uint256) {
     return address(this).balance/1 ether;
    }
    
      
  function getter() view public returns (uint)
  {
   return add.length;
  }

Here's the code of React that I am using which is working but I am not able to call other functions(array length)这是我正在使用的 React 代码,但我无法调用其他函数(数组长度)

useEffect(()=>{
  const getMemebers=async()=>{
    const admin=await web3Api.contract.admin({
      from:account
    });
    setAccount(admin);
  }
  web3Api.contract && getMemebers();
},[web3Api.web3])
  

Assuming you've web3.js file set up in your src folder, the only issue I see is you're calling an async function in useEffect which is always a bad idea.假设您在 src 文件夹中设置了 web3.js 文件,我看到的唯一问题是您在 useEffect 中调用异步函数,这总是一个坏主意。

Instead you can define a different async function and call that normally in useEffect.相反,您可以定义一个不同的异步函数并通常在 useEffect 中调用它。 If you assign any state to it, it'll refresh the dom for you.如果您为其分配任何状态,它将为您刷新 dom。 I don't have enough information to provide better solution but I'm adding a similar code which I wrote and which worked我没有足够的信息来提供更好的解决方案,但我正在添加我编写的类似代码并且有效

import { useState, useEffect } from 'react';
import './App.css';
import web3 from './web3';
import Lottery from './lottery';
function App() {
  const [manager, setManager] = useState('');
  const [players, setPlayers] = useState([]);
  const [balance, setBalance] = useState('0');
  const [value, setValue] = useState('');
  const [message, setMessage] = useState('');
  const [account, setAccount] = useState('');

  async function setInitials(){
    let address = await Lottery.methods.manager().call();
    let playerList = await Lottery.methods.getPlayers().call();
    let contractBalance = await web3.eth.getBalance(Lottery.options.address);
    let accounts = await web3.eth.getAccounts();
    setAccount(accounts[0]);
    setManager(address);
    setPlayers(playerList);
    setBalance(web3.utils.fromWei(contractBalance, 'ether'));
  }

  const enterContract = async (e) => {
    try {
      e.preventDefault();
      setMessage('Waiting for success of transaction...')
      let accounts = await web3.eth.getAccounts();
      await Lottery.methods.enter().send({
        from: accounts[0],
        value: web3.utils.toWei(value, 'ether')
      })
      setMessage('Transaction successful !!!')
      setValue('');
      setInitials();
    } catch (error) {
      setMessage(`Transaction failed: ${error.message}`)
    }
  }

  const pickWInner = async () => {
    try {
      setMessage('Picking Winner');
      let accounts = await web3.eth.getAccounts();
      await Lottery.methods.pickWinner().send({
        from: accounts[0]
      })
      let winner = await Lottery.methods.getWinner().call();
      setMessage(`Winner is ${winner}. Congratulations!!`)
      setInitials();
    } catch (error) {
      setMessage(`Failed to pick winner: ${error.message}`)
    }
  }

  useEffect(() => {
    setInitials();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className="App">
      <h1>Lottery App</h1>
      <p>This contract is managed by: {manager}</p>
      <p>Number of players participated: {players.length}</p>
      {
      players.length > 0 
      ? 
        <ul>List of players currently in Contract:
          {players.map((player, index) => {
            return <li key={index}>{player}</li>
          })}
        </ul>
      :
        <></>
      } 
      <p>Total balance up for Grab: {balance} ether</p>

      <hr />

      <form onSubmit={enterContract}>
        <h3>Want to try your luck?</h3>
        <p>Enter amouth of ether you want to put in</p>
        <input 
          placeholder='Min 0.01 Ether'
          value={value}
          onChange={e => setValue(e.target.value)}
        />
        <button type='Submit'>Enter</button>
      </form>
      {
        account === manager 
        ?
          <>
              <hr />
              <h2>Pick a Winner</h2>
              <button onClick={pickWInner}>Pick Winner</button>
          </>
        :
        <></>
      }
      <h1>{message}</h1>
    </div>
  );
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM