JWLAZY / block_chain_know

区块链相关笔记

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

智能合约(Smart Contract)/发布-1

JWLAZY opened this issue · comments

commented

智能合约(Smart Contract)/发布

上一篇文章写了编译一个智能合约,这一篇将简单的介绍下如何在模拟环境中部署一个智能合约.
部署智能合约需要满足如下几个条件

1. 获取智能合约的abi来构建一个合约实例
2. 调用实例的deply方法来构建和节点的交易,需要合约bytecode和初始化参数
3. 调用send方法来触发节点交易传输
4. 节点返回节点

以下为代码实现

const fs = require('fs');
const path = require('path')
const Web3 = require('web3');
const ganache_cli = require('ganache-cli');
const web3 = new Web3(ganache_cli.provider());

const filepath = path.resolve(__dirname,'build','SimpleStorage.json')
let contractabi = JSON.parse(fs.readFileSync(filepath, 'utf8'));
let deply = () => {
    let contract = new web3.eth.Contract(JSON.parse(contractabi.interface));
    web3.eth.getAccounts()
    .then(accounts => {
        contract.deploy({
            data: contractabi.bytecode
        })
        .send({
            from: accounts[0],
            gas: 1500000,
            gasPrice: '30000000000000'
        })
        .then(d => {
            if(d.options.address){
                console.log("模拟部署智能合约成功,合约地址:" + d.options.address);
            }
        })
    });
}

deply();

注意这个是在内存中模拟的智能合约部署,在程序重新启动的时候,之前的合约都不存在.

微信交流群: