用户应该如何与智能合约互动?

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

在部署智能合约时,如何让我自己的平台(移动或网络)中的用户与之互动?假设我有以下合同:

contract Test {
    event Log(address addr);

    function logMe () public {
        Log(msg.sender);
    }
}

为了使用它,我必须能够访问用户的私钥和公钥。是否可以允许用户通过自己的帐户与区块链进行交互,而无需拥有凭据?

blockchain ethereum solidity smartcontracts
2个回答
1
投票

首先,如果您尝试使用Remix在区块链上部署合同。并且您已经使用创建的API创建了合同,实际上您正在与您的Web合同进行交互。您可以浏览此视频,了解如何在合同中部署和使用呼叫功能。我鼓励你观看这个video并做its tutorial here

如果你想调用函数(公共)有三个步骤,所以你可以使用你的合同。

第一步:在区块链上部署合同,找到您的ABI和合同地址。例如,如果您使用remix部署合同,则可以通过单击编译选项卡中的详细信息来查看这些信息。

enter image description here

第二步:使用web3并将其注入您的Web浏览器(安装Metamask然后您已经将web3注入浏览器)

第三步:通过设置从步骤1获得的web3提供者和ABI以及合同地址来创建合同API,例如实例。

第四步:调用合同函数。

以下是确保已注入web3并连接到正确的区块链(TestNet / MainNet)的方法

var Web3 = require('web3');

if (typeof web3 !== 'undefined') {
     // Use Mist/MetaMask's provider
     console.log('Web3 exist!')
     console.log(web3)
     web3 = new Web3(web3.currentProvider);

     web3.version.getNetwork((err, netId) => {
      switch (netId) {
        case "1":
          console.log('This is mainnet')
          break
        case "2":
          console.log('This is the deprecated Morden test network.')
          break
        case "3":
          console.log('This is the ropsten test network.')
          break
        default:
          console.log('This is an unknown network.')
      }
    })

 } else {
     console.log('No web3? You should consider trying MetaMask!')
     // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
     web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
 }

以下是您与已部署合同进行交互的方式。

 var fooContract = web3.eth.contract( YOUR_ABI, (err, ctr) => { return ctr} );
     web3.eth.defaultAccount = web3.eth.accounts[0];
     $scope.accounts = web3.eth.accounts;

     console.log(web3.eth.defaultAccount);
    var CONTRACT = fooContract.at('YOUR_Deployed_contract_ADDRESS',(err, ctr)=>{
      return ctr;
    } ) 

现在,您可以轻松使用CONTRACT变量来调用其公共函数。

电话看起来像这样:

CONTRACT.contractFunction(params)

PS:如果您有任何疑问或问题,请与我联系(一篇文章很难解释)!


1
投票

是。通常这种方式是有效的,你有一个托管的网络应用程序,说使用javascript(查看web3:https://github.com/ethereum/web3.js/)与你的智能合约进行交互。用户导航到您的Web应用程序,然后他们的帐户已连接,以便他们可以向您的合同发送请求(了解他们如何将他们的帐户连接到metamask:https://metamask.io/或运行以太坊节点,例如geth / parity)。这是一个很好的教程,解释了使用名为Truffle:http://truffleframework.com/tutorials/pet-shop的合同开发框架松散描述的工作流程。

编辑:所以回答你关于凭据的问题,不,你不必拥有他们的凭据。

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