【问题标题】:How to connect contract in web3 with flutter如何将 web3 中的合同与颤振连接起来
【发布时间】:2022-06-14 23:35:59
【问题描述】:

我尝试将 web3 中的合同与颤振连接起来,并在其中运行一个方法。我们的 react-js 开发人员给了我这些代码来连接到 getMoney 方法:

const web3 = new Web3(Web3.givenProvider ||"https://rinkeby.infura.io/v3/...");
const contactList = new web3.eth.Contract(CONTACT_ABI, CONTACT_ADDRESS);
const getMoney = await contactList.methods.getMoney().call();
console.log(getMoney);

我尝试使用flutter_web3 包来连接元掩码和合约:

String abi = await rootBundle.loadString("assets/json/Counter.json");
final contract = Contract(CONTACT_ADDRESS, abi, Web3Provider("https://rinkeby.infura.io/v3/..."),);
int money = await contract.call("getMoney");
print(money.toString());

但我无法连接到合约并调用getMoney 方法。你能帮帮我吗?

【问题讨论】:

    标签: flutter flutter-web web3js


    【解决方案1】:

    如果我理解正确,您想从合约中调用一个方法。我用web3darthttp 包做到这一点。此外,您还需要完成以下工作:

    1. 首先,您需要一个 abi 文件。在您的情况下,将您的 Counter.json 文件放在 lib 目录中并将其重命名为 counter.abi.json
    2. 正如web3dart#dart-code-generator所说,您必须在dev_dependency中添加build_runner并在终端中运行pub run build_runner build
    3. 然后,您现在将找到一个 .g.dart 文件,其中包含与合约交互的代码,您必须使用该类。

    然后,初始化这些代码:

    Client httpClient = Client();
    Web3Client ethClient = Web3Client("https://rinkeby.infura.io/v3/...", httpClient);
    

    对于从合约中调用方法:

    var contractAbi = await Counter(address: EthereumAddress.fromHex(contractAddress), client: ethClient);
    var money = await contractAbi.getMoney();
    

    【讨论】:

      猜你喜欢
      • 2020-03-04
      • 2021-08-16
      • 2020-09-29
      • 2021-08-11
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2020-04-03
      • 2021-09-28
      相关资源
      最近更新 更多