IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 区块链 -> Web3.js链接区块链合约并渲染页面 -> 正文阅读

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

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链接区块链合约并且在前端渲染页面的任务就完成了

  区块链 最新文章
盘点具备盈利潜力的几大加密板块,以及潜在
阅读笔记|让区块空间成为商品,打造Web3云
区块链1.0-比特币的数据结构
Team Finance被黑分析|黑客自建Token“瞒天
区块链≠绿色?波卡或成 Web3“生态环保”标
期货从入门到高深之手动交易系列D1课
以太坊基础---区块验证
进入以太坊合并的五个数字
经典同态加密算法Paillier解读 - 原理、实现
IPFS/Filecoin学习知识科普(四)
上一篇文章      下一篇文章      查看所有文章
加:2022-09-13 11:21:05  更:2022-09-13 11:21:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 21:25:59-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码