Web3.js链接区块链合约并渲染页面

Web3.js链接区块链合约并渲染页面,第1张

Web3.js链接区块链合约并且在前端渲染页面 区块链、比特币、以太坊、智能合约的牵连关系(对要做的东西心里有个大概了解)

从区块链历史上来说,先诞生了比特币,当时并没有区块链这个技术和名词,然后业界从比特币中提取了技术架构和体系,称之为区块链技术。从比特币提取的区块链技术称之为区块链1.0时代,那个时候的应用主要以电子货币和去中心化交易为主,比如各种山寨币。而以太坊将区块链带入了2.0的时代,区块链2.0不是推翻了1.0,而是在1.0的基础上实现了区块知晓、价值知晓、图灵完备,并进行了细节优化,从而形成了以智能合约为特色的区块链2.0。比特币定位于一个应用,而以太坊定位于平台,你可以在这个平台上利用智能合约做各种应用。

1、使用Web3.js链接区块链 创建Web3的对象
var web3 = new Web3(); //注意第一个web3的w是小写,第二个Web3的W是大写
连接到区块链(也可以称为以太坊节点)
web3.setProvider(new Web3.providers.HttpProvider('网址域名'));
合并

上述两步可以合并为一步,如下:

var web3 = new Web3(new Web3.providers.WebsocketProvider('网址域名'));
网址域名 从哪里获取网站域名

首先你需要进入区块链开发平台,然后注册一个账号,并进行邮箱验证。

接着,你需要自己创建一个Web3.js项目

然后你就可以看到NETWORK ENDPOINTS(网络端点)这一板块,看到网址,左边有个下拉菜单,可以选择不同的测试网,比如Ropsten等等,根据自己的需要对网址进行转换。

然后将网址进行复制,粘贴到上述括号中要填写的’网络域名

注意:

因为Http这个已经是老版本了,需要改成wss开头

举例:

var web3 = new Web3(new Web3.providers.WebsocketProvider('http://ropsten.infura.io/ws/v3/f75f263dde5540719b1a3fcebb821485'));
//就需要改成如下:
var web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws/v3/f75f263dde5540719b1a3fcebb821485'));

到目前为止,已经成功链接了区块链

2、使用Web3.js链接合约

首先,要明确合约有两个非常重要的东西——ABI地址,获取一个合约,最重要的就是获取这两个元素

创建合约实例
var abi=[合约中的abi,需要自己复制粘贴];
var 合约名字(可以自己随便起一个) = new web3.eth.Contract(abi,'合约地址');

到目前为止,其实已经将合约链接好了,就是你创建的实例对象合约名字

举个例子:

var abi = [{
				"constant": true,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					}
				],
				"name": "isIdentityExist",
				"outputs": [
					{
						"name": "",
						"type": "bool"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"constant": true,
				"inputs": [],
				"name": "getFirstBlockNum",
				"outputs": [
					{
						"name": "",
						"type": "uint256"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"constant": false,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					},
					{
						"name": "key",
						"type": "bytes32"
					},
					{
						"name": "value",
						"type": "bytes"
					},
					{
						"name": "updated",
						"type": "int256"
					}
				],
				"name": "setAttribute",
				"outputs": [],
				"payable": false,
				"stateMutability": "nonpayable",
				"type": "function"
			},
			{
				"constant": true,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					}
				],
				"name": "getLatestRelatedBlock",
				"outputs": [
					{
						"name": "",
						"type": "uint256"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"constant": false,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					},
					{
						"name": "key",
						"type": "bytes32"
					},
					{
						"name": "value",
						"type": "bytes"
					},
					{
						"name": "updated",
						"type": "int256"
					}
				],
				"name": "delegateSetAttribute",
				"outputs": [],
				"payable": false,
				"stateMutability": "nonpayable",
				"type": "function"
			},
			{
				"constant": true,
				"inputs": [],
				"name": "getWeIdCount",
				"outputs": [
					{
						"name": "",
						"type": "uint256"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"constant": false,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					},
					{
						"name": "auth",
						"type": "bytes"
					},
					{
						"name": "created",
						"type": "bytes"
					},
					{
						"name": "updated",
						"type": "int256"
					}
				],
				"name": "createWeId",
				"outputs": [],
				"payable": false,
				"stateMutability": "nonpayable",
				"type": "function"
			},
			{
				"constant": false,
				"inputs": [
					{
						"name": "identity",
						"type": "address"
					},
					{
						"name": "auth",
						"type": "bytes"
					},
					{
						"name": "created",
						"type": "bytes"
					},
					{
						"name": "updated",
						"type": "int256"
					}
				],
				"name": "delegateCreateWeId",
				"outputs": [],
				"payable": false,
				"stateMutability": "nonpayable",
				"type": "function"
			},
			{
				"constant": true,
				"inputs": [],
				"name": "getLatestBlockNum",
				"outputs": [
					{
						"name": "",
						"type": "uint256"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"constant": true,
				"inputs": [
					{
						"name": "currentBlockNum",
						"type": "uint256"
					}
				],
				"name": "getNextBlockNumByBlockNum",
				"outputs": [
					{
						"name": "",
						"type": "uint256"
					}
				],
				"payable": false,
				"stateMutability": "view",
				"type": "function"
			},
			{
				"inputs": [
					{
						"name": "roleControllerAddress",
						"type": "address"
					}
				],
				"payable": false,
				"stateMutability": "nonpayable",
				"type": "constructor"
			},
			{
				"anonymous": false,
				"inputs": [
					{
						"indexed": true,
						"name": "identity",
						"type": "address"
					},
					{
						"indexed": false,
						"name": "key",
						"type": "bytes32"
					},
					{
						"indexed": false,
						"name": "value",
						"type": "bytes"
					},
					{
						"indexed": false,
						"name": "previousBlock",
						"type": "uint256"
					},
					{
						"indexed": false,
						"name": "updated",
						"type": "int256"
					}
				],
				"name": "WeIdAttributeChanged",
				"type": "event"
			},
			{
				"anonymous": false,
				"inputs": [
					{
						"indexed": true,
						"name": "identity",
						"type": "address"
					},
					{
						"indexed": false,
						"name": "previousBlock",
						"type": "uint256"
					},
					{
						"indexed": false,
						"name": "created",
						"type": "int256"
					}
				],
				"name": "WeIdHistoryEvent",
				"type": "event"
			}];
var metaTxContract = new web3.eth.Contract(abi,'0xC081739A451cC2d3E6cCE95f70e59e353A10A57F')
3、给合约安排监听事件

具体格式如下:

上述代码中创建的合约实例对象的名字.getPastEvents("合约的名字,需要自己找到并且手动添加", { fromBlock: 0, toBlock: 'latest' })
.then(function(events) {
	for(var i=0;i<events.length;i++){
	console.log(events[i]);
	 }                               //for打印出合约中到现目前为止的所有事件
});
4、在前端渲染页面

首先,我们要明确我们的目的,就是要把合约中的事件直接渲染到(打印)到html页面当中

举例:

//我们写了一个盒子和一个按钮,盒子的目的是装载打印出来的合约中的事件,按钮的作用是加载一个事件,一点击,就会打印
<div class="hao">div>            
<input type="button" value="button-me" onclick="saveAsObject()" />
//我们写了一个saveAsObject函数将整个合约实例和打印事件包装起来,通过上述按钮,添加saveAsObject函数事件,一点击就会打印出事件。最下面如何打印的步骤很重要,以及对问题的分析都很重要
function saveAsObject(){
    var web3 = new Web3(new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws/v3/f75f263dde5540719b1a3fcebb821485'));

//创建合约实例
var abi = [{
            "constant": true,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                }
            ],
            "name": "isIdentityExist",
            "outputs": [
                {
                    "name": "",
                    "type": "bool"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [],
            "name": "getFirstBlockNum",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                },
                {
                    "name": "key",
                    "type": "bytes32"
                },
                {
                    "name": "value",
                    "type": "bytes"
                },
                {
                    "name": "updated",
                    "type": "int256"
                }
            ],
            "name": "setAttribute",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                }
            ],
            "name": "getLatestRelatedBlock",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                },
                {
                    "name": "key",
                    "type": "bytes32"
                },
                {
                    "name": "value",
                    "type": "bytes"
                },
                {
                    "name": "updated",
                    "type": "int256"
                }
            ],
            "name": "delegateSetAttribute",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [],
            "name": "getWeIdCount",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                },
                {
                    "name": "auth",
                    "type": "bytes"
                },
                {
                    "name": "created",
                    "type": "bytes"
                },
                {
                    "name": "updated",
                    "type": "int256"
                }
            ],
            "name": "createWeId",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": false,
            "inputs": [
                {
                    "name": "identity",
                    "type": "address"
                },
                {
                    "name": "auth",
                    "type": "bytes"
                },
                {
                    "name": "created",
                    "type": "bytes"
                },
                {
                    "name": "updated",
                    "type": "int256"
                }
            ],
            "name": "delegateCreateWeId",
            "outputs": [],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [],
            "name": "getLatestBlockNum",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "constant": true,
            "inputs": [
                {
                    "name": "currentBlockNum",
                    "type": "uint256"
                }
            ],
            "name": "getNextBlockNumByBlockNum",
            "outputs": [
                {
                    "name": "",
                    "type": "uint256"
                }
            ],
            "payable": false,
            "stateMutability": "view",
            "type": "function"
        },
        {
            "inputs": [
                {
                    "name": "roleControllerAddress",
                    "type": "address"
                }
            ],
            "payable": false,
            "stateMutability": "nonpayable",
            "type": "constructor"
        },
        {
            "anonymous": false,
            "inputs": [
                {
                    "indexed": true,
                    "name": "identity",
                    "type": "address"
                },
                {
                    "indexed": false,
                    "name": "key",
                    "type": "bytes32"
                },
                {
                    "indexed": false,
                    "name": "value",
                    "type": "bytes"
                },
                {
                    "indexed": false,
                    "name": "previousBlock",
                    "type": "uint256"
                },
                {
                    "indexed": false,
                    "name": "updated",
                    "type": "int256"
                }
            ],
            "name": "WeIdAttributeChanged",
            "type": "event"
        },
        {
            "anonymous": false,
            "inputs": [
                {
                    "indexed": true,
                    "name": "identity",
                    "type": "address"
                },
                {
                    "indexed": false,
                    "name": "previousBlock",
                    "type": "uint256"
                },
                {
                    "indexed": false,
                    "name": "created",
                    "type": "int256"
                }
            ],
            "name": "WeIdHistoryEvent",
            "type": "event"
        }];
var metaTxContract = new web3.eth.Contract(abi,'0xC081739A451cC2d3E6cCE95f70e59e353A10A57F')    

metaTxContract.getPastEvents("WeIdAttributeChanged", { fromBlock: 0, toBlock: 'latest' })
	.then(function(events) {
    //有一个问题,因为如果要将事件打印到前端页面,如果直接写xxx.innerHTML就会出现打印出[object,object]这样的问题,而不能得到我们想要得到的事件,其原因是innerHTML只能打印字符串,那么这是我们的解决办法是将js文件进行json打包处理,通过下面的代码就很好的解决了这一问题
    var json_str = JSON.stringify(events);                                                
    document.querySelector('.hao').innerHTML=(json_str);
});
}

注意:我们再强调一遍遇到的问题,如果要将事件打印到前端页面,如果直接写xxx.innerHTML就会出现打印出[object,object]这样的问题,而不能得到我们想要得到的事件,其原因是innerHTML只能打印字符串,那么这是我们的解决办法是将js文件进行json打包处理,通过上面的代码就很好的解决了这一问题

至此,我们整个Web3.js链接区块链合约并且在前端渲染页面的任务就完成了

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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存