Web3.js的学习记录
# 1. geth 的安装### 1. apt-get方式在线安装
~~~cmd
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 文件
~~~~json
{
"nonce":"0x0000000000000042",
"mixhash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"difficulty": "0x4000",
"alloc": {},
"coinbase":"0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x00000000",
"gasLimit":"0xffffffff",
"config":{
"chainId": 666,
"homesteadBlock": 0
}
}
~~~~
- 初始化
~~~cmd
geth --datadir "chain" init genesis.json
~~~
- 启动
~~~cmd
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 下的操作
~~~cmd
1.1 用户列表
eth.accounts
1.2 添加用户
personal.newAccount("password")
1.3 挖矿、停止
miner.start()
miner.stop()
1.4 查看余额
eth.getBalance(eth.accounts)
1.5 获取节点信息
admin.nodeInfo
admin.nodeInfo.enode
admin.nodeInfo.id
admin.nodeInfo.ports.listener
~~~
### 2. ganache 的安装
#### 2.1 npm 安装
~~~cmd
npm install -g ganache-cli
启动
ganache-cli
~~~
#### 2.2 搭建 ganache 交互
~~~cmd
mkdir ganache
npm install web3 -save
~~~
~~~js
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 与区块链交互
~~~cmd
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
~~~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;
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
~~~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
~~~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
~~~js
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)
~~~
- 测试eth 接取地址:(https://faucet.polygon.technology)
- 交易查看地址:(https://mumbai.polygonscan.com/)
!(https://img-blog.csdnimg.cn/img_convert/d107b29cac4286465cec17addc14ec75.png) 学习中……………… 这个是做什么功能的库? web3是用来整什么的 lwlwss 发表于 2021-11-23 09:45
这个是做什么功能的库?
用来与区块链之间的交互 爱吃鹅肉饭 发表于 2021-11-23 10:28
web3是用来整什么的
用来与区块链之间的交互 挖矿啊。。。 魔幻冰扬 发表于 2021-11-23 20:30
挖矿啊。。。
怎么都 觉得 区块链 就是挖矿。。。。 QzyLing 发表于 2021-11-24 11:40
怎么都 觉得 区块链 就是挖矿。。。。
因为不懂,哈哈哈{:301_997:} 落魄前端的我能学会吗
页:
[1]
2