以太坊智能合约 编译脚本

前提准备工作

  • 创建新的项目文件夹 mkdir contract_workflow
  • mkdir contracts   创建合约文件夹
  • mkdir scripts       创建脚本文件夹
  • mkdir compiled   创建编译文件存放的文件夹
  • mkdir tests          创建测试文件夹
  • 使用ls可以看到创建的文件夹,这个时候需要引入包管理工具,初始化列表,使用命令 npm init
  • 安装所需要的插件 solc 使用命令 npm install [email protected]
  • 安装所需要的插件 npm install fs-extra ,这个用于将compile.js文件的输出结果存储为一个文件

准备源码

  • 将Car.sol存放到contracts文件夹下面
pragma solidity ^0.4.17;

contract Car{
    string brand;
    uint public price;
    constructor(string initBrand,uint initPrice)public{
        brand = initBrand;
        price = initPrice;
    }
    function setBrand(string newBrand)public{
        brand = newBrand;
    }
    
    function getBrand() public view returns (string){
        return brand;
    }
    
    function setPrice(uint newPrice)public{
        price = newPrice;
    }
}

编译脚本

  • 将compile.js编译脚本放到scrips文件夹下面
  • 使用命令node compile.js进行对于合约的编译
const fs = require('fs-extra')
const solc = require('solc')
const path = require('path')

const contractPath = path.resolve(__dirname,'../contracts','Car.sol');
const contractSource = fs.readFileSync(contractPath,'utf-8');
let compileResult = solc.compile(contractSource,1);

console.log(compileResult);

Object.keys(compileResult.contracts).forEach(name=>{
    let contractName = name.replace(/^:/,'');
    let filepath = path.resolve(__dirname,'../compiled',`${contractName}.json`);
    fs.outputJsonSync(filepath,compileResult.contracts[name]);
    console.log("Saving json file to ,"filepath);
})
  • 操作显示的结果,如下 

  • 每次都需要重新生成对应的json文件,(ABI文件/存储在compiled文件夹下的内容),就需要删除旧的文件
const compiledPath = path.resolve(__dirname,'../compiled');
fs.removeSync(compiledPath);
fs.ensureDirSync(compiledPath);
  • 测试文件是否是新生成的,在compiled文件夹下,使用命令 ls -l   对比文件的生成时间和当前时间进行验证

  • 如果程序报错,对于错误输出的格式化代码
//check errors
if(Array.isArray(result.errors) && result.errors.length){
    throw new Error(result.errors[0]);
}

compile.js完整代码

const fs = require('fs-extra');
const solc = require('solc');
const path = require('path');

const compiledPath = path.resolve(__dirname,'../compiled');
fs.removeSync(compiledPath);
fs.ensureDirSync(compiledPath);

//check errors
if(Array.isArray(result.errors) && result.errors.length){
    throw new Error(result.errors[0]);
}

const contractPath = path.resolve(__dirname,'../contracts','Car.sol');
const contractSource = fs.readFileSync(contractPath,'utf-8');
let compileResult = solc.compile(contractSource,1);

//console.log(compileResult);

Object.keys(compileResult.contracts).forEach(name=>{
    let contractName = name.replace(/^:/,'');
    let filepath = path.resolve(__dirname, '../compiled', `${contractName}.json`);
    fs.outputJsonSync(filepath,compileResult.contracts[name]);
    console.log("Saving json file to ",filepath);
});

部署脚本

  • 进入scripts文件夹下,创建deploy.js文件,写入部署代码  1.0版本
const Web3 = require('web3')
const web3 = new Web3(new Web3.providers.HttpProvider("Http://localhost:8545"));
const fs = require('fs-extra')
const path = require('path')

const filePath = path.resolve(__dirname,'../compiled/Car.json');
const {interface , bytecode} = require(filePath);

(async()=>{
    let accounts = await web3.eth.getAccounts;
    let result = await new web3.eth.Contract(JSON.parse(interface))
    .deploy({data:bytecode,arguments:["BWM"]})
    .send({from:accounts[0],gas:5000000});
    console.log("result:",result);
})();
  • console.time("deploy time")
  • console.timeEnd("deploy time")  里面的内容得一致,比如deploy time,成对出现
  • 0.20版本
const Web3 = require('web3')
const web3 = new Web3(new Web3.providers.HttpProvider("Http://localhost:8545"));
const path = require('path')

const filePath = path.resolve(__dirname,'../compiled/Car.json');
const {interface , bytecode} = require(filePath);

const abi = JSON.parse(interface);
const contract = web3.eth.contract(abi);
const _from = web3.eth.accounts[0];
const txObj = {data:bytecode,from:_from,gas:5000000};

let contractInstance = contract.new(txObj,(err,res)=>{
    if(err)
        console.log("Error:",err);
    else
        console.log("Result:",res);
});

 

你可能感兴趣的:(区块链,以太坊)