简单使用metamascara

package.json

配置文件信息

{
  "name": "test-mascara",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.6.1",
    "ethjs": "^0.4.0",
    "events": "^3.0.0",
    "express": "^4.16.4",
    "metamascara": "^2.2.1",
    "path": "^0.12.7",
    "solc": "^0.4.25",
    "web3": "^1.0.0-beta.36"
  }
}

 

 mascara.js

调用metamascara

const metamask = require('metamascara');
const Web3 = require('web3');
const fs = require("fs");

const ethereumProvider = metamask.createDefaultProvider();

global.web3 = new Web3(ethereumProvider);
console.log(web3);

var miner = '0x7DdaD6a67544efB0c51808c77009a7B98Cc81630';//这个是本人添加在wallet.metamask.io线上钱包的一个账号
web3.eth.getBalance(miner) //得到了它在Rinkeby上的余额,说明它连接的是Rinkeby的测试网站
.then(console.log);


var mydata = web3.utils.sha3('i want to be your friend');
// console.log(mydata);
web3.eth.sendTransaction({//会弹出窗口
    from: '0x7DdaD6a67544efB0c51808c77009a7B98Cc81630',
    to: '0x3B896Fb3e31fC9B91921d19B8C7271d1c3af5B35',
    value: '3000000000000000',
    data:mydata
})
.on('transactionHash', function(hash){
    console.log(hash);
})
.on('receipt', function(receipt){
    console.log(receipt);
})
.on('confirmation', function(confirmationNumber, receipt){
    console.log(confirmationNumber);
})
.on('error', console.error);

 

main.js

设置dapp server服务器

const express = require('express');
const app = new express();
const ejs = require('ejs');
const path = require('path');
app.set('views',path.join(__dirname,'views'));
app.engine('.html',ejs.__express);
app.set('view engine','html');

app.use(express.static(path.join(__dirname,'public')));//放mascara-bundle.js

var server = app.listen(8081,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log("应用实例,访问地址为  %s:%s",host,port);
});

app.get('/', function(req, res){
      res.render('index');
});

 

views/index.html

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
    <span style="white-space:pre"></span>
    <link href="http://www.lituanmin.com/favicon.ico" rel="icon" type="image/x-icon" />
  <title>MetaMask ZeroClient Example</title>
</head>

<body>
  <p>访问网页后鼠标随意点击一下页面就能够弹出确认窗口了</p>
  <script src="/mascara-bundle.js"></script>
</body>
</html>

 

首先调用browserify mascara.js > public/mascara-bundle.js

得到mascara-bundle.js文件

然后在终端运行node main.js,打开server服务器

接着就能够在浏览器访问网址了http://localhost:8081

⚠️在访问该浏览器时我登录了页面版的metamask钱包,否则访问不到相应的账户信息,因为账户是上锁的

这时候点击一下页面就有窗口弹出了

wallet.metamask.io这个线上钱包默认连接的是rinkeby测试网络

这时候如果我将网页版的钱包的信息该成主网版本:

 

那么再运行的时候就是在主网上运行了:

然后点击confirm后,可以看见,该交易失败:

 

posted @ 2018-11-07 16:45  慢行厚积  阅读(468)  评论(0编辑  收藏  举报