factory runner不支持发送交易

问题描述 投票:0回答:1

我正在尝试使用 hyperledger besu 和 Hardhat 来创建一个区块链网络来上传智能合约,但我收到此错误,我想在私有 ibft 2.0 网络上使用此合约:

Error: factory runner does not support sending transactions (operation="sendTransaction", code=UNSUPPORTED_OPERATION, version=6.10.0)
    at makeError  {
  code: 'UNSUPPORTED_OPERATION',
  operation: 'sendTransaction',
  shortMessage: 'factory runner does not support sending transactions'
}

部署.js:

// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
//
// You can also run a script with `npx hardhat run <script>`. If you do that, Hardhat
// will compile your contracts, add the Hardhat Runtime Environment's members to the
// global scope, and execute the script.
const hre = require("hardhat");

async function main() {
  const token = await hre.ethers.deployContract("FakeNewsValidator");
  console.log("Token address:", await token.getAddress());
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

hardhat.config.js:

require("@nomicfoundation/hardhat-toolbox");

/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
  // in built test network to use when developing contracts
  hardhat: {
    chainId: 1337
  },
  quickstart: {
    url: "http://127.0.0.1:8545",
    chainId: 1337,
    // test accounts only, all good ;)
    accounts: [
      "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63",
      "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3",
      "ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f"
    ],
    gas: 1048576,
    gasPrice: 0
  },  
  defaultNetwork: "hardhat",
  solidity: {
    version: "0.8.19",
    settings: {
      optimizer: {
        enabled: true,
        runs: 200
      }
    }
  },
  paths: {
    sources: "./contracts",
    tests: "./test",
    cache: "./cache",
    artifacts: "./artifacts"
  },
  mocha: {
    timeout: 40000
  }
};

合约:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract FakeNewsValidator {
    address public owner; // Variável que armazena o endereço do proprietário do contrato

    // Construtor do contrato, executado apenas uma vez durante a implantação
    constructor() {
        owner = msg.sender; // Define o criador do contrato como o proprietário
    }

    // Função pseudo-aleatória para determinar verdadeiro ou falso
    function getRandomBool(uint256 _newsId) private view returns (bool) {
        uint256 random = uint256(keccak256(abi.encodePacked(block.timestamp, block.prevrandao, _newsId)));
        return random % 2 == 0;
    }

    // Função para obter detalhes de uma notícia existente com base no ID
    function getNewsItem(uint256 _newsId) external view returns (bool) {
        return getRandomBool(_newsId);
    }
}

我想再次尝试部署 contacto,因为每次我通过 Postman 发出请求时都会收到此错误:

Erro ao acessar o contrato: AbiError: Parameter decoding error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
    at decodeParametersWith 
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  innerError: undefined,
  code: 205,
  props: {
    internalErr: AbiError: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
        at decodeParametersWith {
      innerError: undefined,
      code: 205,
      props: {}
    }
  }
}

服务器.js:

const express = require('express');
const { Web3 } = require('web3');

const app = express();
const PORT = 3000;

console.log('Inicializando Web3 com HTTP Provider.');
const web3 = new Web3('http://localhost:8545'); // URL do seu nó Besu

// Carregar o contrato inteligente
console.log('Carregando ABI e endereço do contrato.');
const contractABI = [
  {
    "inputs": [],
    "stateMutability": "nonpayable",
    "type": "constructor"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "_newsId",
        "type": "uint256"
      }
    ],
    "name": "getNewsItem",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "owner",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  }
]
const contractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3'; // Coloque o endereço do seu contrato aqui

// Crie uma instância do contrato
console.log('Criando instância do contrato.');
const contract = new web3.eth.Contract(contractABI, contractAddress);

app.get('/check-news/:newsId', async (req, res) => {
  const { newsId } = req.params;
  console.log(`Recebido newsId: ${newsId}`);

  // Validar o parâmetro de entrada
  if (!newsId || isNaN(newsId)) {
      console.error('ID da notícia inválido:', newsId);
      return res.status(400).json({ error: 'ID da notícia inválido.' });
  }

  try {
    console.log(`Buscando informações para o ID da notícia: ${newsId}`);
    console.log(`Buscando informações para o ID da notícia: ${newsId}`);
    const result = await contract.methods.getNewsItem(newsId).call();
    
    // Decodificar manualmente os valores retornados
    const newsItem = {
        sender: result[0],
        news: result[1],
        isFake: result[2]
    };

    console.log('Informações da notícia recebidas:', newsItem);
    res.json({ newsItem });
  } catch (error) {
      console.error('Erro ao acessar o contrato:', error);
      console.error('Detalhes do erro:', error.reason, error.receipt);
      if (error.message.includes('revert')) {
          res.status(404).json({ error: 'ID da notícia não encontrado.' });
      } else {
          res.status(500).json({ error: 'Erro ao acessar o contrato.' });
      }
  }
});


app.listen(PORT, () => {
  console.log(`Servidor rodando na porta ${PORT}`);
});
blockchain solidity hardhat hyperledger-besu
1个回答
0
投票

我不确定,但在实例化合同时可能需要签名者。我遇到了同样的问题,但我通过使用 ether.js 解决了它。这是未解决问题之前我的代码:

async function safeMint(address,value){
await window.ethereum.request({method: 'eth_requestAccounts'});
const provider = new ethers.BrowserProvider( window.ethereum);

const contract =  new ethers.Contract(contractAddress, erc20, provider);
if (!value){
    value="10000000000";
}

let callback = await contract.safeMint(address,value)
return callback;

}

固定代码:

async function safeMint(address,value){
await window.ethereum.request({method: 'eth_requestAccounts'});
const provider = new ethers.BrowserProvider( window.ethereum);
const signer = await provider.getSigner();
const contract =  new ethers.Contract(contractAddress, erc20, signer);
if (!value){
    value="10000000000";
}

let callback = await contract.safeMint(address,value)
return callback;

}

© www.soinside.com 2019 - 2024. All rights reserved.