JWLAZY / block_chain_know

区块链相关笔记

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

智能合约(Smart Contract)/编译

JWLAZY opened this issue · comments

commented

交流地址: telegram

智能合约(Smart Contract)

写在以太坊链上的代码,在每个节点中都会存在,在节点中可以调用这些代码,可以保存一些数据,在调用时可以访问数据,也可以修改这些数据.

注意: 我们编写智能合约的语言叫做Solidity,可以理解为一种新的语法,其实和js的语法差不多.写智能合约其实就是写Solidity.

下面是一个智能合约的例子

pragma solidity ^0.4.11;

contract SimpleStorage {
    uint data;
    
    function setData(uint x) {
        
        data = x;
    }
    
    function getData() constant returns (uint) {
        
        return data;
    }
}

合约可以看成是一个类,由一组数据和方法组成.写完后可以发布到链上去,发布到链上的过程就是写到以太坊链上的每一个节点上.每一个智能合约发布后都有一个地址,当访问这个地址时就可以调用这个合约了.

合约编译

合约的编译可以通过solc 这个库来实现,合约编译主要是把写的solidity 编译成 bytecode 和 ABI,其中bytecode可以了解为存储到链上的数据.

还可以通过remix这个网站来编译发布.这个后面说一说怎么使用.

solc使用

  1. 下载solc 到项目中去.

    	npm i --save solc
    
  2. 新建compile.js文件主要处理编译

    const solc = require('solc');
    const fs = require('fs');
    const path = require('path')
    // 获取智能合约文件
    const solfile = path.resolve(__dirname, './Solidity/SimpleStorage.sol');
    // 读取智能合约
    const source = fs.readFileSync(solfile, 'utf8');
    // 编译智能合约
    const compiledContract = solc.compile(source, 1);
    console.log(compiledContract);
  3. 运行compile.js

    	node compile.js
    

运行完成后可以看见输出结果为

上图中bytecode和interface就是我们编译后重点要使用的两个数据.

  1. 写入数据

    代码修改如下

    // 获取智能合约文件
    const solfile = path.resolve(__dirname, './Solidity/SimpleStorage.sol');
    // 读取智能合约
    const source = fs.readFileSync(solfile, 'utf8');
    // 编译智能合约
    const compiledContract = solc.compile(source, 1);
    // 生成目标路径
    const buildPath = path.resolve(__dirname,'build');
    for(let contract in compiledContract.contracts){
        const filePath = path.resolve(buildPath,contract.replace(':','') + '.json')
    	// 写入目标文件夹
        fs.writeFileSync(filePath, JSON.stringify(compiledContract.contracts[contract],null,4))
    }

修改后运行compile.js,可以看见目标文件夹下生成了SimpleStorage.json文件

这就是我们需要的编译后文件.

代码地址:github

微信交流群: