使用 Web3.js 进行 Matic 测试网上链操作

1. geth 的安装

1. apt-get方式在线安装

sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
1.1 查看版本

geth version

2. 在geth目录创建 genesis.json 文件

{
    "nonce":"0x0000000000000042", 
    "mixhash":"0x0000000000000000000000000000000000000000000000000000000000000000", 
    "difficulty": "0x4000", 
    "alloc": {}, 
    "coinbase":"0x0000000000000000000000000000000000000000", 
    "timestamp": "0x00", 
    "parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000", 
    "extraData": "0x00000000", 
    "gasLimit":"0xffffffff",	
	"config":{
		"chainId": 666,
		"homesteadBlock": 0
	}
}
  • 初始化
geth --datadir "chain" init genesis.json
  • 启动
geth --datadir "./chain" --networkid 666 --port 30303 --http --http.addr "0.0.0.0" --http.port 8545 --http.api 'db,net,eth,web3,personal' --allow-insecure-unlock --http.corsdomain '*' console 2>> geth.log

3. console 下的操作

1.1 用户列表
	eth.accounts
1.2 添加用户
	personal.newAccount("password")
1.3 挖矿、停止
	miner.start()
	miner.stop()
1.4 查看余额
	eth.getBalance(eth.accounts[0])
1.5 获取节点信息
	admin.nodeInfo
  admin.nodeInfo.enode
  admin.nodeInfo.id
  admin.nodeInfo.ports.listener

2. ganache 的安装

2.1 npm 安装
npm install -g ganache-cli

启动
ganache-cli
2.2 搭建 ganache 交互
mkdir ganache
npm install web3 -save
const Web3 = require("web3")
console.log("判断浏览器是否启用Metamask插件的对象Web3.givenProvider结果为:",Web3.givenProvider);
const web3 = new Web3(Web3.givenProvider || new Web3.providers.HttpProvider('http://localhost:8545'));
console.log(web3.version)
web3.eth.getAccounts().then(console.log)

3. web3.js 与区块链交互

npm install -g express-generator  
npm install express -g
express -e myapp

npm install
npm start
	172.16.13.17:3000
3.1 routes/index.js
const express = require('express');
const router = express.Router();
const Web3 = require("web3")
const web3 = new Web3(Web3.givenProvider || new Web3.providers.HttpProvider('http://localhost:8545'));
web3.eth.getAccounts().then(console.log)

/* GET home page. */
router.get('/', function(req, res, next) {
  web3.eth.getAccounts().then(accounts=>{
    const account = accounts[0];
    web3.eth.getBalance(account).then(balance=>{
      const amount = web3.utils.fromWei(balance, 'ether');
      res.render('index',{account: accounts, balance: amount})
    })
  })
});

module.exports = router;
3.2 app.js
var app = express();

var ejs = require('ejs')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html',ejs.__express);
app.set('view engine', 'html');
3.3 views/index.html
<!DOCTYPE html>
<html>
	<head>
		<title>账户余额</title>
		<link rel='stylesheet' href='/stylesheets/style.css' />
	</head>
	<body>
		<h1>账户是:<%= account %> </h1>
		<h1>余额是:<%= balance %> </h1>
	</body>
</html>
  • MetaMask/外部账户导入到Geth私链

    https://www.cnblogs.com/shizhe99/p/15087068.html

2. web3.js的使用(上链操作)

1. 测试Demo

const Web3 = require("web3")
// ABI
const ERC721V1ABI = require("../config/erc721_v1.json");

// 连接测试链:https://rpc-mumbai.maticvigil.com
const web3 = new Web3("https://rpc-mumbai.maticvigil.com");

// 通过私钥获取账户信息
const key_account = web3.eth.accounts.privateKeyToAccount("0xe6c68097bd7e6377c10a9010ba8362e014bbfb57b50202481671d4a4ae9fca18")

// 只有添加到wallet 才能交易
web3.eth.accounts.wallet.add(key_account);

const encodedParams =
        "0x485f0f700000000000000000000000000000000000000000000000000000000000ad253b0000000000000000000000\
    00000000000000000000000000000000000013081b00000000000000000000000000000000000000000000000000000000000000600000000000000\
      000000000000000000000000000000000000000000000000008676976656e55524c000000000000000000000000000000000000000000000000";

class FirstContractWeb3 {
    constructor() {
        // this.initContract1155()
        // this.initContract721()
        this.getAccountBalance()
        // this.createAccount()
    }

		// 创建钱包
    createAccount(){
        // address: '0x1afF0Db20192Bd4c040e8e284943566bb4e66F0C',
        // privateKey: '0xe6c68097bd7e6377c10a9010ba8362e014bbfb57b50202481671d4a4ae9fca18',
        // console.log(web3.eth.accounts.wallet.create(1));

        // address: '0x1A72dd6735bDA5Ad219D3ffB6Dd544E3dcda57e8',
        // privateKey: '0xbf249f4d9602ee6e40f852b161e38c9b0e8590296af739d7206e293023ea0090',
        //console.log(web3.eth.accounts.create(1));
      	const key_account1 = web3.eth.accounts.privateKeyToAccount("0xe6c68097bd7e6377c10a9010ba8362e014bbfb57b50202481671d4a4ae9fca18")
       	const key_account2 = web3.eth.accounts.privateKeyToAccount("0xbf249f4d9602ee6e40f852b161e38c9b0e8590296af739d7206e293023ea0090")

        web3.eth.accounts.wallet.add(key_account1);
      	web3.eth.accounts.wallet.add(key_account2);
      	transaction(key_account2,key_account2)
    }


  	// 基于 721 协议
    initContract721() {
        // 基于 web3.eth.Contract 对象来创建合约(调用合约的方法)
        const ERC721_v1 = new web3.eth.Contract(
                ERC721V1ABI,
                "0x72B6Dc1003E154ac71c76D3795A3829CfD5e33b9"
        );
        const uri = 'http://127.0.0.1:5200/ipfs/QmSTGeo63NHDxgwtKsvbz81gWmVupftzcarZw58h5Hn3kE'
        ERC721_v1.methods.mintToCaller(key_account.address, uri).send({from: key_account.address, gas: 500000})
            .then(r => console.log("result721: ", r))
            .catch(console.error);

        web3.eth.getBalance(key_account.address)
        .then(result => {console.log("balance: " + result)})
    }

    
    // 转账
    transaction(key_account1,key_account2){
       web3.eth.sendTransaction({
           from: key_accoun1t.address,
           to: key_account2.address,
           gasPrice: "20000000000",
           gas: "21000",
           value: 1000000000
        }).then(console.log)
    }
}

// 执行程序
let first_contract = new FirstContractWeb3();
// console.log(Web3.modules)

image-20211014171521811

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值