truffle-solidity-web3.js之truffle篇2

239 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 接上篇:

1、部署合约

**配置truffle.js/teuffle-config.js文件 **

//linux
module.exports = {
    networks: {
        development: {
            host: "127.0.0.1",
            port: 8545,
            network_id: "*" //watch any network id
        }
    }
};
//winows:
module.exports = {
  /**
   * Networks define how you connect to your ethereum client and let you set the
   * defaults web3 uses to send transactions. If you don't specify one truffle
   * will spin up a development blockchain for you on port 9545 when you
   * run `develop` or `test`. You can ask a truffle command to use a specific
   * network from the command line, e.g
   *
   * $ truffle test --network <network-name>
   */

  networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
    development: {
     host: "127.0.0.1",     // Localhost (default: none)
     port: 7545,            // Standard Ethereum port (default: none)
     network_id: "5777",     // Any network (default: none)
    },
    )
    //可自行配置

2、创建并配置部署的脚本 法一:命令行创建

truffle create migration InsuranceContract

法二(屌丝创法):右键contracts目录创建

然后,migrations目录下就会创建一个部署脚本

配置脚本:

var Simple = artifacts.require("./InsuranceContract.sol");

module.exports = function(deployer) {
  // deployment steps
  deployer.deploy(InsuranceContract);
};

部署:

truffle migrate

truffle migrate --reset //如果修改了合约重新部署,需要加reset参数

3、开启服务喽!!!!

配置bs-config.json

bs-config.jsonbs-config.js为lite-server的配置文件

在项目根目录下创建bs-config.json,然后写入配置

{
    "server":
    {"baseDir": ["./src", "./build/contracts"] }
}

配置./src,直接localhost:3000 即可打开index.html
配置./build/contracts,index.js里$.getJSON第一个参数路径就可以省略,直接写Simple.json即可

修改package.json,加入脚本

"scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "dev": "lite-server"    //新加入的脚本
  },

终端直接输入,启动项目

npm run dev

另外,还可以与ganache节点交互

truffle console
truffle(development)> web3.eth.accounts
truffle(development)> web3.currentProvider //web3所链接的ethereum网络的相关信息

我是通过高鸿祥老师写的文章,内容来自熊丽兵老师****在登链学院上的《以太坊Dapp开发实战》课程,希望对大家有帮助