node.js私有连智能合约开发学习1

使用的win10

1、安装geth

1.1 启动一个私有链
geth --rpc --rpcport "8545" --rpcapi "eth,web3,personal,net" --rpccorsdomain * console 2>>test.log --dev

如下图所示:
这里写图片描述
参数解析:

  1. –rpc:激活节点上的RPC
  2. –rpcapi:配置什么API可以通过rpc,geth默认会激活IPC上的所有API,以及RPC上的db、eth、net、web3
  3. –rpcport:配置端口,geth默认的是8080
  4. –rpccorsdomain:指定什么url可以连接到你的节点来执行RPC任务。
1.2 挖矿
miner.start()

node.js代码

const Web3 = require('web3');
const solc = require ('solc');
设置Provider

如果不设置的话,会报错:Error: Provider not set or invalid

let web3 = new Web3();
web3.setProvider(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));

类似命令行中的:

geth attach http://localhost:8545

智能合约代码
const solidity=`pragma solidity ^0.4.20;
contract HelloWorldContract {
  function sayHi() constant returns (string){
    return 'Hello World';
  }
}`;
编译智能合约
const output = solc.compile(solidity.toString(), 1);
const bytecode = output.contracts[':HelloWorldContract'].bytecode;
const abi = output.contracts[':HelloWorldContract'].interface;
创建智能合约对象
//创建一个Solidity的合约对象,用来在某个地址上初始化合约
const helloWorldContract = web3.eth.contract(JSON.parse(abi));
部署合约
const helloWorldContractInstance = helloWorldContract.new({
    data: '0x' + bytecode,
    from: web3.eth.coinbase,
    gas: 1000000
}, (err, res) => {
    if (err) {
        console.log(err);
        return;
    }
    // If we have an address property, the contract was deployed
    console.log("res.address",res.address);
    if (res.address) {//得有人挖矿(miner.start()),不然这个地址就是undifined
        console.log('Contract address: ' + res.address);
        console.log(helloWorldContract.at(res.address).sayHi({gas: 22222}))
    }
});

输出:

res.address undefined
res.address 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Contract address: 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Hello World

可以看出new的回调函数执行了2次,参考文献1
第一次回调是发送交易(sendTransaction)之后,第二次是得到交易的收据(getTransactionReceipt)之后
这个时候,挖矿了
这里写图片描述

参考文献

  1. https://stackoverflow.com/questions/45128027/cannot-call-function-within-deployed-contract
  2. https://tokenmarket.net/blog/creating-ethereum-smart-contract-transactions-in-client-side-javascript/
  3. https://medium.com/@k3no/ethereum-tokens-smart-contracts-3346b62d2a0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值