以太坊Dapp开发通过truffle与合约进行交互

以太坊Dapp开发通过truffle与合约进行交互,第1张

以太坊Dapp开发通过truffle与合约交互

上一章节我们使用truffle启动了一个自带的合约,接下来我们自己来编写一个投票的智能合约
先使用Remix来在线编译投票合约,先保证没有错误。

pragma solidity >=0.4.22 < 0.6.0;

contract Voting{
    bytes32[] public candidateList;
    mapping(bytes32 => uint8) public votesReceived;

    constructor(bytes32[] memory candidateListName)public{
        candidateList = candidateListName;
    }

    function validateCandidate(bytes32 candidateName) internal view returns(bool){
        for (uint8 i = 0; i < candidateList.length; i++){
            if(candidateName == candidateList[i]){
                return true;
            }
        }
                 return false;
    }

    function voteForCandidate(bytes32 candidateName)public{
        require(validateCandidate(candidateName));
        votesReceived[candidateName] += 1;
    }

    function totalVotesFor(bytes32 candidateName)view public returns(uint8){
         require(validateCandidate(candidateName));
        return votesReceived[candidateName];
    }
}

在dapp目录下创建一个backupvote目录,进入到backupvote目录执行truffle unbox metacoin命令

truffle unbox metacoin

此时backupvote目录下有以下的内容

[root@ backupvote]# ls
app  build  contracts  migrations  test  truffle-config.js

此时我们可以将contracts目录下的ConvertLib.sol和MetaCoin.sol合约删除

rm  -rf ConvertLib.sol
rm -rf MetaCoin.sol

在contracts目录下我们新建一个Voting.sol智能合约,将上面写的合约复制进去

vim Voting.sol

这里我们还需要改动一下truffle-config.js当中的配置文件,使用vim truffle-config.js命令,将 development配置注释解开,并将develop注释,方便我们进行测试。

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
     development: {
      host: "127.0.0.1",     // Localhost (default: none)
            port: 8545,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
     },

 //    develop: {
 //     port: 8545
 //  },

在backupvote目录下执行编译和部署合约的命令

truffle compile
truffle migrate

这时候可以在backupvote/build/contracts下发现一个Voting.json文件
接下来修改backupvote/migrations下的2_deploy_contracts.js文件

//const ConvertLib = artifacts.require("ConvertLib");
//const MetaCoin = artifacts.require("MetaCoin");

const Voting = artifacts.require("Voting.sol");

module.exports = function(deployer) {
//  deployer.deploy(ConvertLib);
//  deployer.link(ConvertLib, MetaCoin);
//  deployer.deploy(MetaCoin);
     deployer.deploy(Voting,
   ["0x4100000000000000000000000000000000000000000000000000000000000000",
    "0x4200000000000000000000000000000000000000000000000000000000000000"]);
};

我们还需要修改backupvote/app/src下的index.html和index.js文件

[root@ src]# vim index.html


  
    My Voting Dapp
  
  

    Voting Dapp
    

Alice :loading...tickets

Bob :loading...tickets

[root@ src]# vim index.js
import Web3 from "web3";
import votingArtifact  from "../../build/contracts/Voting.json";
const aInBytes32 = "0x4100000000000000000000000000000000000000000000000000000000000000";
const bInBytes32 = "0x4200000000000000000000000000000000000000000000000000000000000000";


const App = {
  web3: null,
  account: null,
  voting: null,

  start: async function() {
    const { web3 } = this;

    try {
      // get contract instance
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = votingArtifact.networks[networkId];
      this.voting = new web3.eth.Contract(
        votingArtifact.abi,
        deployedNetwork.address,
         );

      // get accounts
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];

      this.ready();
    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },


        refresh: async function(id,nameInBytes32){
         const {totalVotesFor} = this.voting.methods;
         const tickets = await totalVotesFor(nameInBytes32).call();
         const element = document.getElementById(id);
         element.innerHTML = tickets.toString();
        },

       ready: async function(){
       try{
             this.refresh("alice",aInBytes32);
             this.refresh("bob",bInBytes32);
        }catch(err){
                console.log(err);
        }
      },

      voteForCandidate: async function(){
       console.log("vote");
      try{
         const { voteForCandidate } = this.voting.methods;
         const candidateName = document.getElementById("candidate").value;

        console.log(candidateName);
         if(candidateName == "Alice"){
                await voteForCandidate(aInBytes32).send({from: this.account});
                this.refresh("alice",aInBytes32);
                }else if(candidateName == "Bob"){
                await voteForCandidate(bInBytes32).send({from: this.account});
                this.refresh("bob",bInBytes32);
                console.log("vote Bob");
        }

        } catch(err){
                console.log(err);
        }
},
}
window.App = App;

window.addEventListener("load", function() {
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn(
      "No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
    );
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(
      new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
    );
  }

  App.start();
});


我在部署过程中碰到以上的问题像TypeError: this voteing is null和Could not connect to contract or chain.
大家需要仔细检查自己index.js当中调用的方法名是否和我们的合约当中的方法名一致,修改完之后,将build/contracts/当中生成的voteing.json文件删除,并在创建的工程目录下重新编译和部署,然后在重新启动,这时候就不会有问题了。

成功启动的页面(这里我已经点击过很多次了,初始页面票数都为0):

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/927856.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-17
下一篇 2022-05-17

发表评论

登录后才能评论

评论列表(0条)