簡體   English   中英

呼叫 function 有錯誤:::: RPCError:得到代碼 -32000 和消息“執行恢復”

[英]call function has error ::::: RPCError: got code -32000 with msg "execution reverted"

我無法將我的前端與智能合約連接起來。 我做了一個小的選舉 dapp,當我在 remix ide 上部署和測試它時它工作正常但是當我嘗試將它與智能合約連接時從我的 flutter 應用程序它不工作

我嘗試再次部署它(相應地更改了 abi 和合同地址)它仍然不起作用它只有在從混音測試時才有效但我想將它連接到我的應用程序我現在該怎么辦?

錯誤:

call function has error ::::: RPCError: got code -32000 with msg "execution reverted".

智能合約:

//SPDX-License-Identifier:UNLICENSED
pragma solidity ^0.8.0;

contract Election{

    struct Candidate{
        string name;
        uint numvotes;
    }

    struct Voter{
        string name;
        bool authorised;
        uint whom;
        bool voted;
    }

    modifier ownerOnly(){
        require(msg.sender == owner);
        _;
    }

    address public owner;
    string public ElectionName;

    mapping(address => Voter) public Voters;
    Candidate[] public candidates;
    uint public totalvotes=0;

    function startElection(string memory _ElectionName)public{
        owner = msg.sender;
        ElectionName = _ElectionName;
    }

    function addCandidate(string memory _candidatename) ownerOnly public{
        candidates.push(Candidate(_candidatename,0));
    }

    function authoriseVoter(address _voteradress)ownerOnly public{
        require(!Voters[msg.sender].voted);
        Voters[_voteradress].authorised = true;
    }

    function getNumcandidates()public view returns(uint){
            return candidates.length;
    }

    function Vote(uint CandidateIndex)public {
        require(!Voters[msg.sender].voted);
        require(Voters[msg.sender].authorised = true);
        Voters[msg.sender].whom = CandidateIndex;
        Voters[msg.sender].voted = true;

        candidates[CandidateIndex].numvotes++;
        totalvotes++;

    }

    function candidateInfo(uint index) public view returns(Candidate memory){ 
        return candidates[index];
    }

    function getTotalVotes()public view returns(uint) {
        return totalvotes;
    } 
    
}

前端 function:

Future<DeployedContract> loadContract() async {
  try{
    String abi = await rootBundle.loadString('assets/abi.json');
    String contractAddress = contractAdressConst;
    final contract = DeployedContract(ContractAbi.fromJson(abi, 'Election'),
        EthereumAddress.fromHex(contractAddress));
    return contract;
  }catch(e){
    print('load contract failed ::::: $e');
    print('{{{{{{{{{{{{{{{[[{{{{{');
    String abi = await rootBundle.loadString('assets/abi.json');
    String contractAddress = contractAdressConst;
    final contract = DeployedContract(ContractAbi.fromJson(abi, 'Election'),
        EthereumAddress.fromHex(contractAddress));
    return contract;
  }
}

Future<String> callFunction(String funcname, List<dynamic> args,
    Web3Client ethClient, String privateKey) async {
  try{
    EthPrivateKey credentials = EthPrivateKey.fromHex(privateKey);
    DeployedContract contract = await loadContract();
    final ethFunction = contract.function(funcname);
    final result = await ethClient.sendTransaction(
        credentials,
        Transaction.callContract(
          contract: contract,
          function: ethFunction,
          parameters: args,
        ),
        chainId: null,
        fetchChainIdFromNetworkId: true);
    return result;
  }catch(e){
    print('call function has error ::::: $e');
    return e.toString();
  }
}

Future<String> startElection(String name, Web3Client ethClient) async {
  try{
    var response =
    await callFunction('startElection', [name], ethClient, owner_private_key);
    print('Election started successfully');
    return response;
  }catch(e){
    print("election not started : : : $e");
    return e.toString();
  }
}

Future<String> addCandidate(String name, Web3Client ethClient) async {
  try{
    var response =
    await callFunction('addCandidate', [name], ethClient, owner_private_key);
    print('Candidate added successfully');
    return response;
  }catch(e){
    print(" candidate not added : : :$e");
    return e.toString();
  }
}

家.dart:

import 'package:election/utils/Constants.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:web3dart/web3dart.dart';

import '../services/functions.dart';
import 'Electioninfo.dart';

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Client? httpClient;
  Web3Client? ethClient;
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    httpClient = Client();
    ethClient = Web3Client(infura_url, httpClient!);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Start Election'),
      ),
      body: Container(
        padding: EdgeInsets.all(14),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: controller,
              decoration: InputDecoration(
                  filled: true, hintText: 'Enter election name'),
            ),
            SizedBox(
              height: 10,
            ),
            Container(
                width: double.infinity,
                height: 45,
                child: ElevatedButton(
                    onPressed: () async {
                      if (controller.text.length > 0) {
                        await startElection(controller.text, ethClient!);
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => ElectionInfo(
                                    ethClient: ethClient!,
                                    electionName: controller.text)));
                      }
                    },
                    child: Text('Start Election')))
          ],
        ),
      ),
    );
  }
}

這是您在開發區塊鏈相關產品時隨時可能遇到的常見錯誤,有一些可能會出現此錯誤,請檢查一下我做了:

 - check the require conditions in your smart contract and make sure the process satisfies these conditions
 - make sure that compiler version and remix version match 
 - make sure that the account(like metamask) is configured correctly through injected provider
 - optimize the smart contract to have minimum amount of gas and maximum efficiency
 - make sure you have enough fund in the account(demo or real)

 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM