创建一个“ Hello World”全栈dapp
该dapp实现了“ Hello World”样式的应用程序,该应用程序将传递给合约的消息回显到前端。本教程旨在使用studio.ethereum.org上的在线IDE 并选择“ Hello World”模板来进行。
智能合约
第一行pragma solidity ^0.5.10
指定源代码用于大于0.5.10的Solidity版本。编译指示是编译器有关如何处理源代码的常见说明(例如,一次编译指示)。
紧密性意义上的合约是驻留在以太坊区块链上特定地址的代码(其功能)和数据(其状态)的集合。该行string public message
声明了一个名为message
type 的公共状态变量string
。您可以将其视为数据库中的单个插槽,可以通过调用管理数据库的代码的函数来查询和更改它。关键字public会自动生成一个函数,该函数使您可以从合约外部访问状态变量的当前值。没有此关键字,其他合约将无法访问该变量。
该constructor
是创建合约的过程中运行一个特殊的功能,不能被称为后。在这种情况下,它采用一个字符串值initMessage
,将该值memory
存储在数据存储区域中,并设置message
为该值。
该update
函数是另一个类似于构造函数的公共函数,它使用字符串作为参数并更新message
变量。
网络应用
本教程不涉及HTML或CSS,因为它不是web3特定的,除了JavaScript操纵的元素ID。许多JavaScript代码遵循面向对象JavaScript的标准模式,因此本教程重点介绍web3js的特定部分。
首先创建智能合约的实例,将其作为属性传递,使web3js与其进行交互。
function HelloWorld(Contract) {
this.web3 = null;
this.instance = null;
this.Contract = Contract;
}
初始化HelloWorld
对象并创建web3js库的实例,并将Metamask传递为合约或您可以在IDE设置中配置的任何其他网络终结点的提供程序。然后,初始化函数使用web3js合约对象定义合约的接口,然后为该对象定义合约实例的地址HelloWorld
。
HelloWorld.prototype.init = function() {
this.web3 = new Web3(
(window.web3 && window.web3.currentProvider) ||
new Web3.providers.HttpProvider(this.Contract.endpoint));
var contract_interface = this.web3.eth.contract(this.Contract.abi);
this.instance = contract_interface.at(this.Contract.address);
};
添加其他JavaScript样板来创建HelloWorld
上面定义的对象的实例,并在页面上显示HTML元素:
HelloWorld.prototype.main = function() {
$(".blocknumber").show();
$(".message").show();
this.update();
}
HelloWorld.prototype.onReady = function() {
this.init();
this.main();
};
var helloWorld = new HelloWorld(Contracts['HelloWorld']);
$(document).ready(function() {
helloWorld.onReady();
});
该getMessage
函数获取传递到合约实例的消息值。使用IDE,可以从合约文件的披露三角形下的Configure选项中传递此值,但在IDE外部,可以通过多种方式传递该值。
该getBlockNumber
作品类似,但使用web3js
函数返回配置的端点中最新块的值。
HelloWorld.prototype.getMessage = function(cb) {
this.instance.message(function (error, result) {
cb(error, result);
});
};
HelloWorld.prototype.getBlockNumber = function(cb) {
this.web3.eth.getBlockNumber(function(error, result) {
cb(error, result);
});
};
该update
函数将所有内容联系在一起,调用上面定义的两个函数,并将H2
标签设置为它们返回的值或显示错误消息。
HelloWorld.prototype.update = function() {
var that = this;
this.getMessage(function(error, result) {
if(error) {
$(".error").show();
return;
}
$("#message").text(result);
that.getBlockNumber(function(error, result) {
if(error) {
$(".error").show();
return;
}
$("#blocknumber").text(result);
setTimeout(function() {that.update()}, 1000);
});
});
}