ethereum合约交互
从以太坊上获取已经部署好的合约实例
需要的数据
1.ABI
2.合约地址
const ABI = [{...}]
const address = 0xabcd....
然后我们还是需要web3来设置网络
let Web3 = require('web3')
let web3 = new Web3('http://127.0.0.1:7545')
然后获取实例
let instance = new web3.eth.Contract(ABI,address)
然后导出
module.exports = instance
然后我们创建一个interaction.js文件
来进行交互
let instance = require('./loadInstance')
//账户
let account1 = '0xabcd.....'
//调用函数
let test = async() =>{
let msg = await instance.methods.getValue().call({
from: account1,
})
console.log(msg)
}
test()
然后我们看一下这段完整代码
loadInstance.js
const ABI = '[{"constant":true,"inputs":[],"name":"getValue","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_str","type":"string"}],"name":"setValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_str","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]';
const address = '0xabcd....'
//然后我们还是需要web3来设置网络
let Web3 = require('web3')
let web3 = new Web3('http://127.0.0.1:7545')
//然后获取实例
let instance = new web3.eth.Contract(JSON.parse(ABI), address)
//然后导出
module.exports = instance
然后是interaction.js文件
let instance = require('./loadInstance')
//账户
let account1 = '0xabcd....'
//调用函数
let test = async() =>{
let msg = await instance.methods.getValue().call({
from: account1,
})
console.log(msg)
}
test()
我们执行 node interaction.js
成功调用成功了getValue()
获取到了hello world
接下来我们执行setValue
也就是写的操作,send操作
let res = await instance.methods.setValue('second message').send({
from: account1,
gas: '100000',
value: 0
})
console.log(res)
value是这笔交易携带的钱,我们这里是没有payable,所以value为0
然后我们再看下完整代码
let instance = require('./loadInstance')
//账户
let account1 = '0xd5957914c31e1d785ccc58237d065dd25c61c4d0'
//调用函数
let test = async() =>{
let res = await instance.methods.setValue('second message').send({
from: account1,
gas: '100000',
value: 0
})
console.log(res)
let msg = await instance.methods.getValue().call({
from: account1,
})
console.log(msg)
}
test()