如何用web3部署智能合約

合約示例

pragma solidity ^0.4.18;

contract CallMeChallenge {
    bool public isComplete = false;

    function callme() public {
        isComplete = true;
    }
}

能夠用solc編譯合約,也能夠用Remix編譯。javascript

若是用solc編譯的話,須要下載同合約使用的solidity版本相同的solc版本。java

npm install solc@0.4.18

Remix編譯後直接複製bytecode到代碼裏便可。node

web3.js部署合約

環境:nodejspython

npm install web3@^0.20.1
npm install ethereumjs-tx@^1.3.7
var Web3 = require('web3');
var Tx = require('ethereumjs-tx');
var solc = require('solc');
var fs = require('fs');

//init
if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/1b8...b0"));
}

var fromAddr = '0x97...5B7';
var count = web3.eth.getTransactionCount(fromAddr);
var gasPrice = web3.eth.gasPrice;
var gasLimit = 3000000;
var privateKey = new Buffer.from('bb07...ed3c', 'hex');

//編譯合約,得到bytecode
var source = fs.readFileSync("./test.sol", "utf8");
var compilied = solc.compile(source, 1);
var bytecode = compilied.contracts[':CallMeChallenge'].bytecode;

//要打包的交易信息
var rawTx = {
    'from': fromAddr,
    'nonce': web3.toHex(count),
    'gasPrice': web3.toHex(gasPrice),
    'gasLimit': web3.toHex(gasLimit),
    'value': '0x0',
    'data': '0x'+bytecode
};

var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();

var hashTx = web3.eth.sendRawTransaction('0x'+serializedTx.toString('hex'));
console.log('txHash: ' + hashTx);
var makeTx;
while (true) {
    makeTx = web3.eth.getTransaction(hashTx);

    if (makeTx["blockNumber"] !== null) {
        var receipt = web3.eth.getTransactionReceipt(hashTx);
        console.log("address: " + receipt["contractAddress"]);
        break;
    }
}

在運行同一個腳本的時候遇到玄學問題,Error: Invalid JSON RPC response: undefined報出這個錯誤,找了好久才發現是網絡問題,加載infura有時候須要掛個代理來訪問,若是你也遇到這個問題,就掛個代理跑跑。web

web3.py部署合約

環境:python3.6npm

# -*- coding:utf-8 -*-

from web3 import Web3, HTTPProvider

true = True
false = False

web3 = Web3(HTTPProvider('https://ropsten.infura.io/v3/1b...b0'))

fromAddr = '0x97D7...5B7'
privateKey = '0xbb...ed3c'
nonce = web3.eth.getTransactionCount(fromAddr)
gasPrice = web3.eth.gasPrice
rawTx = {
    'from': fromAddr,
    'nonce': nonce,
    'gasPrice': gasPrice,
    'gas': 300000,
    'value': web3.toWei(0, 'ether'),
    'data': '0x606060405260008060006101000a81548160ff021916908315150217905550341561002957600080fd5b60e4806100376000396000f3006060604052600436106049576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063a3c8e39314604e578063b2fa1c9e146060575b600080fd5b3415605857600080fd5b605e608a565b005b3415606a57600080fd5b607060a6565b604051808215151515815260200191505060405180910390f35b60016000806101000a81548160ff021916908315150217905550565b6000809054906101000a900460ff16815600a165627a7a723058208fd18624eaaac9c24521a084590bb1b536e9a94f23086c49864b9c02300ff0c20029'
}

def deploy(rawTx):
    signedTx = web3.eth.account.signTransaction(rawTx, private_key=privateKey)
    hashTx = web3.eth.sendRawTransaction(signedTx.rawTransaction).hex()
    receipt = web3.eth.waitForTransactionReceipt(hashTx)

    return receipt

if __name__ == '__main__':
    receipt = deploy(rawTx)
    print('address: ' + receipt['contractAddress'])

後話

這裏用JavaScript和Python兩個web3版原本實現自動部署合約,免去了在Remix上手動部署,另外還有Java版的web3等等。網絡

相關文章
相關標籤/搜索