合约部署

要部署的合约

pragma solidity ^0.4.23;
contract test {
uint256 value; function setValue(uint256 _value) public{
value = _value;
} function getValue() public returns (uint256){
return value;
} function () public payable{ }
}

获取合约的ABI和bytecode

合约ABI

[
{
"payable": true,
"stateMutability": "payable",
"type": "fallback"
},
{
"constant": false,
"inputs": [
{
"name": "_value",
"type": "uint256"
}
],
"name": "setValue",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "getValue",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
]

合约bytecode

// add '0x' in front of the bytecode
0x608060405234801561001057600080fd5b5060dc8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632096525514604b57806355241077146073575b005b348015605657600080fd5b50605d609d565b6040518082815260200191505060405180910390f35b348015607e57600080fd5b50609b6004803603810190808035906020019092919050505060a6565b005b60008054905090565b80600081905550505600a165627a7a72305820437e5b6f23c9e202f4188fde72ebdd65de3a5c7fca347bea516a2f576748a9240029

部署代码

const Web3 = require('web3')
// RPC SERVER
const web3 = new Web3('http://localhost:7545')
var Tx = require('ethereumjs-tx').Transaction // your account and private key
const account = '0x1275270073b7CA41Cd1a62736795f80f7b52487c'
const pk1 = '56a0717cbc04b0e47732d5be497ad57052594c03088b9ef889fefca107ffeecb'
const private_key = Buffer.from(pk1, 'hex') // get the nonce of account
web3.eth.getTransactionCount(account, (err, txCount) => { // the bytecode of contract
const data = "0x608060405234801561001057600080fd5b5060dc8061001f6000396000f3006080604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680632096525514604b57806355241077146073575b005b348015605657600080fd5b50605d609d565b6040518082815260200191505060405180910390f35b348015607e57600080fd5b50609b6004803603810190808035906020019092919050505060a6565b005b60008054905090565b80600081905550505600a165627a7a72305820437e5b6f23c9e202f4188fde72ebdd65de3a5c7fca347bea516a2f576748a9240029" // set transaction object
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(6721975),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
data: data
} // sign transaction
const tx = new Tx(txObject)
tx.sign(private_key) const serializedTx = tx.serialize()
const raw = '0x' + serializedTx.toString('hex') // send transaction
web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
})
})

运行结果



注意一个问题,和利用 truffle 部署的智能合约不同,直接用 Web3.js 部署的合约是不会显示在 ganache 的 Contract页面里的,也就是说,它存在,只是没显示。

合约调用

调用代码

var Tx     = require('ethereumjs-tx').Transaction
// search their github for the detail of usage of 'Common' class
const Common = require('ethereumjs-common').default
const Web3 = require('web3')
const web3 = new Web3('http://localhost:7545') const account = '0x1275270073b7CA41Cd1a62736795f80f7b52487c'
const pk1 = '56a0717cbc04b0e47732d5be497ad57052594c03088b9ef889fefca107ffeecb'
const private_key = Buffer.from(pk1, 'hex') const contractAddress = '0x6F20B2F0149A680116411a01d5Bc6D4B09E869F4'
const contractABI = [
{
"payable": true,
"stateMutability": "payable",
"type": "fallback"
},
{
"constant": false,
"inputs": [
{
"name": "_value",
"type": "uint256"
}
],
"name": "setValue",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [],
"name": "getValue",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
] // initialize the contract object
const contract = new web3.eth.Contract(contractABI, contractAddress) // call the setValue() function with parameter 123
const calldateABI = contract.methods.setValue(123).encodeABI() // All of these network's params are the same than mainnets', except for name, chainId, and
// networkId, so we use the Common.forCustomChain method.
const customCommon = Common.forCustomChain(
'mainnet',
{
// set the parameter as your ganache
name: 'my-network',
networkId: 5777,
chainId: 1337,
},
'petersburg',
) web3.eth.getTransactionCount(account, (err, count) => {
const txObject = {
nonce: web3.utils.toHex(count),
// set the gas limit as same as of ganache's
gasLimit: web3.utils.toHex(6721975),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
to: contractAddress,
// contract.methods.<function name>(<parameter>).encodeABI()
data: contract.methods.setValue(123).encodeABI()
} // We pass our custom Common object whenever we create a transaction
const transaction = new Tx(txObject, { common: customCommon },)
console.log('transaction:', transaction) // sign the transaction
transaction.sign(private_key)
console.log('transaction.sign:', transaction) // returns the rlp encoding of the transaction
const serializedTx = transaction.serialize()
const raw = '0x' + serializedTx.toString('hex') web3.eth.sendSignedTransaction(raw, (err, txHash) => {
console.log('txHash:', txHash)
if(err){
throw err;
}
})
})

运行结果

参考文章

  1. 奇客谷:web3.js 教程
  2. 关于ethereumjs-tx在私链部署
  3. ethereumjs-common 调用方法

【阿菜用工具】利用 Web3.js 在 ganache 上部署以及调用智能合约的更多相关文章

  1. web3.js编译Solidity,发布,调用全部流程(手把手教程)

    web3.js编译Solidity,发布,调用全部流程(手把手教程) 下面教程是打算在尽量牵涉可能少的以太坊的相关工具,主要使用web3.js这个以太坊提供的工具包,来完成合约的编译,发布,合约方法调 ...

  2. 利用exif.js解决手机上传竖拍照片旋转90\180\270度问题

    原文:https://blog.csdn.net/linlzk/article/details/48652635/ html5+canvas进行移动端手机照片上传时,发现ios手机上传竖拍照片会逆时针 ...

  3. 如何利用docker 构建golang线上部署环境

    公司最近开发了一个项目是用golang 写的,现在要部署到线上环境去,又不想在服务器上装单独的golang,决定用docker 封装下,直接打到镜像里面,然后就直接在hub.docker.com上面搜 ...

  4. 【阿菜用工具】Slither:Solidity静态分析框架

    工具简介 Slither 是一个 python3 开发,用于检测智能合约(solidity)漏洞的静态分析框架. Slither 的 Github 地址:https://github.com/cryt ...

  5. 以太坊 web3.js 文档翻译及说明

    这些天,为了录制以太坊DAPP开发实战课程,我准备把web3文档全部翻译一下(并做适当的补充),目前web3.js 0.20.x 版本 已经翻译完成,欢迎大家前往查阅. 这里还几个实用DEMO,供大家 ...

  6. nodejs部署智能合约的方法-web3 0.20版本

    参考:https://www.jianshu.com/p/7e541cd67be2 部署智能合约的方法有很多,比如使用truffle框架,使用remix-ide等,在这里的部署方法是使用nodejs一 ...

  7. 利用n 升级工具升级Node.js版本及在mac环境下的坑

    一.利用n 升级Node.js 最近在用NPM安装一个nodejs工具时发现,我的nodejs的版本有些旧了.这不是大问题,只要升级就可以了,当然,重新从nodejs.org最新版本是一种方法,但我想 ...

  8. 利用tween.js算法生成缓动效果

    在讲tween类之前,不得不提的是贝塞尔曲线了.首先,贝塞尔曲线是指依据四个位置任意的点坐标绘制出的一条光滑曲线.它在作图工具或动画中中运用得比较多,例如PS中的钢笔工具,firework中的画笔等等 ...

  9. 【转】利用 three.js 开发微信小游戏的尝试

    前言 这是一次利用 three.js 开发微信小游戏的尝试,并不能算作是教程,只能算是一篇笔记吧. 微信 WeChat 6.6.1 开始引入了微信小游戏,初期上线了一批质量相当不错的小游戏.我在查阅各 ...

随机推荐

  1. perror()函数的使用

    perror()函数的功能是打印一个系统错误信息.        perror()函数在Linux系统中属于库函数,在头文件中有如下定义: #include <stdio.h>       ...

  2. 透彻详解(3)旁路电容100nF_0.1uF的由来计算

    原文地址点击这里: 前一节我们已经详细解释了旁路电容在数字电路系统中所起的基本且重要作用,即储能与为高频噪声电流提供低阻抗路径,尽管还并未给旁路电容的这些功能概括一个"高大上"的名 ...

  3. 重新整理 .net core 实践篇—————HttpClientFactory[三十二]

    前言 简单整理一下HttpClientFactory . 正文 这个HttpFactory 主要有下面的功能: 管理内部HttpMessageHandler 的生命周期,灵活应对资源问题和DNS刷新问 ...

  4. Golang编写动态库实现回调函数

    Golang编写动态库实现回调函数 我们现在要做一个动态库,但是C++实在是比较难,于是就想能不能用更简单的golang来实现,golang也就是最近的版本才支持编译成动态库,在网上也没找到可用的案例 ...

  5. 【.NET 与树莓派】TM1638 模块的按键扫描

    上一篇水文中,老周马马虎虎地介绍 TM1638 的数码管驱动,这个模块除了驱动 LED 数码管,还有一个功能:按键扫描.记得前面的水文中老周写过一个 16 个按键的模块.那个是我们自己写代码去完成键扫 ...

  6. CentOS7详细安装教程(图文)

    CentOS7安装过程:(图文详解) 为了做实验,装台Linux的虚拟机,手上有这个7的ISO文件就懒得去下载8的了. 0X01.虚拟机配置 0X02.CentOS7系统配置安装 分别创建/boot区 ...

  7. BFS经典面试题——C++版

    文章目录 蛇梯棋 单词接龙 青蛙过河 蛇梯棋 N x N 的棋盘 board 上,按从 1 到 N*N 的数字给方格编号,编号 从左下角开始,每一行交替方向. 例如,一块 6 x 6 大小的棋盘,编号 ...

  8. Jquery 插件 chosen_v1.8.7 下拉复选框带搜索功能

    地址:https://harvesthq.github.io/chosen/ 效果: 因为只需要这个功能,就只研究这个功能了,代码: <!doctype html> <html la ...

  9. 使用kubeadm进行k8s集群升级

    一.目标 操作系统:CentOS Linux release 7.6.1810 (Core) 安装软件: docker:18.06.3-ce 从v1.15.5升级到v1.16.15 当前版本: [ro ...

  10. iOS导入其他APP下载的文件(用其他应用打开)

    今天给自己的APP新增了一个小功能 可以打开iOS其他APPTXT 文件,一个很小的功能,做阅读APP的小伙伴不要错过. 附上APP地址: 一阅阅读 有想看小说的小伙伴可以试下 支持换源 支持自定义书 ...