solidity合约逻辑
我们来理一下逻辑
第一步.编写合约--solidity
第二步.编译合约
用编译器将solidity代码编译出bytecode和ABI
ABI是不上链的
只有bytecode上链
第三步.部署合约
然后将bytecode部署到区块链上
部署后,会返回合约的地址
然后想要和合约交互
那么要知道
1.地址
2.ABI
通过这两个东西,构造一个合约实例
那么如何通过自己的页面来和以太坊进行交互
可以用node.js
node 提供node.js代码的运行环境
npm node包管理工具
ES6常用新语法
let: 可以修改变量,不能重新定义
const: 不能修改,定义后是常量
解构赋值
numbers= [1,2,3]
let [a,b,c]=numbers;
console.log(a);
//同名解构
let person = {'name':'Alice', 'age':20}
let {name,age} = person
函数
function printInfo(name,age){
console.log(name,age)
}
printInfo('Alice',20)
我们可以给printInfo这个函数加一下默认值
function printInfo(name,age=10){
console.log(name,age)
}
printInfo('Alice')
但是如果是这样
function printInfo(name='Alice',age){
console.log(name,age)
}
printInfo(20)
这样就会输出
Alice,undefined
所以一定要按照顺序来
箭头函数
普通写法
function add(a,b){
return a+b
}
箭头函数的写法
let add = (a,b) =>{
return a+b
}
然后调用
let result=add(1,2)
如果是一个参数或者一个语句
可以这样
let mul = a => a * 10
console.log(mul(2))
class继承
class Person{
constructor(name,age){
this.name=name
this.age=age
}
sayHello(){
console.log(this.name+this.age)
}
}
class Student extends Person{
constructor(name,age){
super(name,age)
}
sayHello(){
console.log('student'+this.name+this.age)
}
}
node.js异步操作
先来看看同步读取文件
let fs = require('fs')
let info = fs.readFileSync('./test.js')
console.log(info.toString())
然后看下异步读取文件
let fs = require('fs')
fs.readFile('./test.js','utf-8', (err,data)=>{
if (err)
})
系统模块
exports与require
导出
hello.js
let hello = () =>{
console.log('hello world')
}
module.exports=hello;
导入
var hello = require('./hello')
hello()
导出多个
exportFunc = {hello01,hello02}
module.exports = exportFunc
导入
let exportFunc = require('./exportTest')
exportFunc.hello01()
exportFunc.hello02()
或者可以这样写
module.exports={
hello01,
hello02
}
fs模块
1.fs.stat
2.fs.readFile
3.fs.writeFile
4.fs.readdir
5.fs.unlink
6.fs.rmdir
7.fs.watchFile
异步读写文件
let fs = require('fs');
fs.readFile('./data.txt','utf-8',(err, data) => {
if (err) {
console.log('fail');
} else {
console.log(data.toString());
}
})
let fs = require('fs');
fs.readFile('./data.txt', 'utf-8', (err, data) => {
if (err) {
console.log('fail');
} else {
console.log(data.toString());
fs.writeFile('./1.txt', data, 'utf-8', (err, data) => {
if (err) {
console.log('write fail');
} else {
console.log('write success');
fs.stat('./1.txt', (err, info) => {
if (err) {
console.log('stat fail');
} else {
console.log(info);
}
})
}
})
}
})
这种情况叫做回调地狱 Callback Hell
为了解决这种情况
Promise和async/await诞生了
Promise可以把异步操作写成同步的形式
我们来看一下
let promiseFunc = new Promise(function(resolve,reject)){
}
1.Promise是一个类型
2.接收一个回调函数作为参数
3.这个回调函数包含两个参数回调函数
resolve回调函数,成功时调用
reject回调函数,失败时调用
然后我们说一下async和await
async 异步
await 等待
这两个和promise配合着使用
async和await是同时出现的
相互配合使用的关键字
然后我们的代码变成这样
let readFileInfo = async() =>{
let data = await readFilePromise()
console.log(data)
}
readFileInfo()
然后我们再try/catch一下
也就是这样
let readFileInfo = async() => {
try{
let data = await readFilePromise()
console.log(data)
}catch(e){
console.log(e)
}
}
readFileInfo()
我们发现
let data = await readFilePromise()
这行就很像同步了
就直接返回data