# web3_remix
**Repository Path**: cheerlee/web3_remix
## Basic Information
- **Project Name**: web3_remix
- **Description**: 智能合约
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2022-06-24
- **Last Updated**: 2024-11-22
## Categories & Tags
**Categories**: Uncategorized
**Tags**: web3
## README
### ganache的使用
Ganache奶油巧克力,前身testRPC
Truffle松露巧克力,一般以Ganache为核,上面撒上可可粉
#### 安装ganache
图形界面版本
https://github.com/trufflesuite/ganache/releases
命令行版本ganache-cli(nodejs>=8)
```bash
# npm i ganache-cli与 npm i ganache合并为后者
npm install -g ganache
# 启动ganache,生成10个测试账户及私钥
ganache
```
#### 使用Web3js进行测试
```bash
mkdir ganache
cd ganache
# 安装web3.js
npm install -s web3
# 测试文件
vim test.js
# test.js,8545端口与ganache监听端口一致,默认8545
# HttpProvider表示要访问区块链
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
console.log(web3.version); # 打印web3.js版本
web3.eth.getAccounts().then(console.log); # 打印ganache10个测试账户,ganache需启动
```
### 使用Web3js与区块链交互
#### 安装express服务器
```bash
mkdir DApp
sudo npm install -g express
```
#### 创建工程
```bash
express -e myDApp
cd myDApp
npm install # sudo npm install
npm start
# 浏览器127.0.0.1:3000
```
#### 和区块链交互
```bash
npm install -s web3
# 查看web3版本
node
var Web3 = require('web3');
console.log(Web3.version)
```
##### 修改路由配置
```js
// routes/index.js
var express = require('express');
var router = express.Router();
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
/* GET home page. */
router.get('/', function(req, res, next) {
web3.eth.getAccounts()
.then(function(accounts) {
var account = accounts[0];
web3.eth.getBalance(account).then(function(balance) {
var amount = Web3.utils.fromWei(balance, 'ether');
res.render('index', { account: account, balance: amount });
})
});
});
module.exports = router;
```
##### 修改app.js模板引擎为html
```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');
...
```
##### 展示页面
```html
账户:<%= account %>
余额:<%= balance %>
```
##### 启动私链
进入geth启动geth或进入ganache启动ganache,与geth或ganache交互
```bash
geth --identity "myetherum" --datadir "chain" --port 3001 --networkid 666 --maxpeers=3 --http --http.port 8545 --http.addr 127.0.0.1 --http.corsdomain "*" --http.api "db,eth,net,web3,personal,miner" console 2>1.txt
或
ganache
# 浏览器127.0.0.1:3000分别显示
账户:0xxxx
余额:0/100
```
### 智能合约

#### 部署合约
solidity智能合约在线编辑IDE https://remix.ethereum.org/
```bash
solidity compiler 编译
Deploy & run transactions 部署 / 运行交易
Compilation Details 编译详情
solidity compiler - Compile - Compilation Details - 复制WEB3DEPLOY
```
新建编辑counter.sol
```js
// SPDX-License-Identifier: MIT // 许可声明
pragma solidity >=0.4.22 <0.9.0; // 指定版本
contract MyCounter {
uint256 counter;
constructor() public {
counter = 1;
}
function kipCounter(uint step) public {
counter += step;
}
function getCounter() public view returns (uint256) {
return counter;
}
}
```
编辑部署合约
```js
/*
mkdir mydapp2
cd mydapp2
mkdir deploy
cd deploy
新建编辑deploy.js
参考https://learnblockchain.cn/docs/web3.js/web3-eth-contract.html#deploy
*/
// 连接Web3
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// web3.eth.getAccounts().then(console.log); // 打印ganache中账户
// 粘贴WEB3DEPLOY
var mycounterContract = new web3.eth.Contract([{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"getCounter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"step","type":"uint256"}],"name":"kipCounter","outputs":[],"stateMutability":"nonpayable","type":"function"}]);
// 合约data较长,提取到之前
mycounterContract.options.data = '0x608060405234801561001057600080fd5b5060016000819055506101e6806100286000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80638ada066e1461003b578063e24801d814610059575b600080fd5b610043610075565b60405161005091906100ea565b60405180910390f35b610073600480360381019061006e91906100ae565b61007e565b005b60008054905090565b8060008082825461008f9190610105565b9250508190555050565b6000813590506100a881610199565b92915050565b6000602082840312156100c4576100c3610194565b5b60006100d284828501610099565b91505092915050565b6100e48161015b565b82525050565b60006020820190506100ff60008301846100db565b92915050565b60006101108261015b565b915061011b8361015b565b9250827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff038211156101505761014f610165565b5b828201905092915050565b6000819050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600080fd5b6101a28161015b565b81146101ad57600080fd5b5056fea2646970667358221220c3cafa7dda78c70cb9ab1f326c7afe7f38ba24a102ab69d36e4282f99bab278e64736f6c63430008070033';
var mycounter = mycounterContract.deploy({
}).send({
from: '0x13eB131ce07C7A9e8F217c0233CC1929A3762763',
gas: '4700000'
}, function (e, contract){
console.log(e, contract);
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
}
}).then(function(contract) { // 打印部署合约地址
console.log('address: ', contract.options.address);
})
/*
node deploy.js
运行部署js
*/
```
#### 通过web3.js调用智能合约
```js
/*
cd ../
mkdir dapp 创建新的dapp
cd dapp
express -e dapp 创建名为dapp的express服务
npm install
app.js中修改app.js模板引擎为html
*/
...
var ejs = require('ejs');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
// app.set('view engine', 'ejs');
...
```
```js
// dapp/routes/index.js创建web3.js实例并调用合约
// 参考 https://learnblockchain.cn/docs/web3.js/web3-eth-contract.html#new-contract 中new contract例子
const { log } = require('debug/src/browser');
var express = require('express');
var router = express.Router();
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
// web3.eth.getAccounts().then(console.log);
var myContract = new web3.eth.Contract([ // ABI,remix solidity compiler - Compilation Details下面 - 点击ABI复制
{
"inputs": [],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "getCounter",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "step",
"type": "uint256"
}
],
"name": "kipCounter",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
}
], '0x949F71e6ea971365EBD676D0F922160bFf5ad6F4');
/*
// 调用合约参考 https://learnblockchain.cn/docs/web3.js/web3-eth-contract.html#methods-mymethod-call
myContract.methods.getCounter().call({from: '0x1b86E4CB76E8300BB14152Af05103c4267A53570'}, function(error, result){
console.log('counter: ', result)
});
// getCounter()方法是编辑智能合约Counter.sol定义,from:这里填写ganache地址列表第二个地址
*/
var init_counter = 0;
var current_counter = 0;
myContract.methods.getCounter().call().then(function(counter) {
console.log('init counter', counter);
init_counter = counter;
});
/* GET home page. */
router.get('/', function(req, res, next) {
myContract.methods.kipCounter(5).send({from: '0x1b86E4CB76E8300BB14152Af05103c4267A53570'})
.then(function(){
myContract.methods.getCounter().call().then(function(counter) {
console.log('current counter', counter);
current_counter = counter;
res.render('index', { init: init_counter, current: current_counter });
});
});
});
module.exports = router;
```
```html
init: <%= init %>
current: <%= current %>
```