使用Atom编写以太坊智能合约

安装库

使用nodejs安装ethereumjs-testrpctruffleethereumjs-testrpc是开发时用到的模拟以太坊网络,如果有私链或者其他节点服务器可以不安装;trufflesolidity开发比较主流的一个框架。

npm install -g ethereumjs-testrpc truffle

创建项目

使用truffle构建项目时,truffle需要一个空的文件夹,如果文件夹内有内容会保错,若以最好新建一个。

mkdir smart-contract-demo
cd smart-contract-demo
truffle init

创建后会生成一些初始的文件,因truffle版本不同而异。

编写合约

在当前目录打开Atom

atom ./

Atom截图

安装插件linter-solidityautocomplete-soliditylinter-solidity。写一个HelloWorld.sol,新建文件contracts/HelloWorld.sol,代码:

pragma solidity ^0.4.4;

contract HelloWorld {
  function sayHello() returns (string) {
    return ("Hello World :-)");
  }
}

启动rpc

testrpc

EthereumJS TestRPC v6.0.3 (ganache-core: 2.0.2)

Available Accounts

==================

(0) 0x92feb02c3f9f579da32daf1946722a5930c59a53

……

(9) 0x08cd557c26ee1b36ae163bed37dcac9f70649dbb

Private Keys

==================

(0) 2abb8a7deb9445881a66ca54827e3f93e2e681b13c0956986f39a3f63b32252b

……

(9) 5202c7c30cbf5a10cc547fe659b1d59cd0083b3784a7ff89e8783cef74f67c88

HD Wallet

==================

Mnemonic: fun arm toast spike include attend ceiling damp embrace nut phone hero

Base HD Path: m/44’/60’/0’/0/{account_index}

Listening on localhost:8545

启动后终端输出Listening on localhost:8545,保持这个终端开启,也不要C掉。

修改truffle.js

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*"
    }
  }
};

编译合约

truffle compile

部署合约

修改1_initial_migration.js

var HelloWorld = artifacts.require("HelloWorld");

module.exports = function(deployer) {
  deployer.deploy(HelloWorld);
};

部署/重新部署

truffle migrate
truffle migrate --reset

呼叫合约

truffle console
let contract
HelloWorld.deployed().then(instance => contract = instance)
contract.sayHello.call()

truffle(development)> let contract

undefined

truffle(development)> HelloWorld.deployed().then(instance => {contract = instance})

TruffleContract {

constructor:

……

address: ‘0xd374574475aaf2845527569b4f38897c6b187d40’,

transactionHash: null }

truffle(development)> contract.sayHello.call()

‘Hello World ?’

结语

以上就是合约基本环境的搭建和调试的过程,VSCode过程类似,区别在于安装的插件不同。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值