Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js私有连智能合约开发学习1大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

1、安装geth

1.1 启动一个私有链

geth --rpc --rpcport "8545" --rpcapi "eth,web3,personal,net" --rpccorsdomain * console 2>>test.log --dev

如下图所示:

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


参数解析:

  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"));

类似命令行中的:

智能合约代码

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@H_674_238@.address undefined
res@H_674_238@.address 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Contract address: 0x466e386e1707f4fa9fe34deaabb6f500429521d4
Hello World

可以看出new的回调函数执行了2次,参文献1
第一次回调是发送交易(sendtransaction)之后,第二次是得到交易的收据(gettransactionReceipt)之后
这个时候,挖矿了

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

文献

  1. @L_489_14@
  2. https://tokenmarket.net/blog/creating-ethereum-smart-contract-transactions-in-client-side-javascript/
  3. https://medium.com/@k3no/ethereum-tokens-smart-contracts-3346b62d2a0

大佬总结

以上是大佬教程为你收集整理的node.js私有连智能合约开发学习1全部内容,希望文章能够帮你解决node.js私有连智能合约开发学习1所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。