狼爱上狸

我胡汉三又回来了

#

第十一课 从宠物商店案例看DAPP架构和WEB3.JS交互接口

https://www.jianshu.com/p/47174718960b

posted @ 2019-06-25 11:05 狼爱上狸 阅读(136) | 评论 (0)编辑 收藏

truffle里的solc版本与实际solc版本冲突的问题

1.因为solc@0.5.1出现调用简单运算合约出现返回0的问题,所以把solc降到了0.4.22。
2.安装truffle后,npm install -g truffle,版本有所不同:
PS C:\> truffle version
Truffle v5.0.24 (core: 5.0.24)
Solidity v0.5.0 (solc-js)
Node v10.16.0
Web3.js v1.0.0-beta.37
3.建立简单合约Greeter.sol后,利用truffle compile后,出现:
Error: CompileError: ParsedContract.sol:1:1: ParserError: Source file requires different compiler version (current compiler is 0.5.8+commit.23d335f2.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity ^0.4.24;
^----------------------^

Compilation failed. See above.
4.修改truffle-config.js文件:
module.exports = {
// Uncommenting the defaults below
// provides for an easier quick-start with Ganache.
// You can also follow this format for other networks;
// see <http://truffleframework.com/docs/advanced/configuration>
// for more details on how to specify configuration options!
/*
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
},
test: {
host: "127.0.0.1",
port: 7545,
network_id: "*"
}
}
*/
compilers: {
solc: {
version: "0.4.24"
}
}
};
5.再次编译,出现
/C/users/administrator/webstormprojects/testtruffle/contracts/Migrations.sol:1:1: SyntaxError: Source file requires different compiler version (current compiler is 0.4.24+commit.e67f0147.Emscripten.clang - note that nightly builds are considered to be strictly less than the released version
pragma solidity >=0.4.25 <0.6.0;
^------------------------------^
6.打开Migrations.sol文件,
把pragma solidity >=0.4.25 <0.6.0;
修改为:pragma solidity >=0.4.24 <0.6.0;
编译通过。

posted @ 2019-06-25 09:05 狼爱上狸 阅读(2056) | 评论 (0)编辑 收藏

ipfs + 以太坊实例解析

本文章的项目基于春哥的博客教程
【IPFS + 区块链 系列】 入门篇 - IPFS + Ethereum (下篇)-ipfs + Ethereum 大图片存储

我个人只是作为记录学习心得所借鉴
项目流程

首先调用代码创建truffle项目

    truffle unbox react

其次,要引入ipfs的api,用作图片存储的相关功能,我们是将图片存储到ipfs当中,而将所获得图片的hash区块链之中,区块链大数据成本的问题

    npm install –save ipfs-api

安装完毕调用complie编译合约代码,,以便使用web3调用合约存储区块链

    compile

替换合约地址,这个需要将合约在以太坊部署并取得对应地址
然后运行ipfs节点

    ipfs daemon

启动项目

    npm start

就可以看到项目成功
代码解读分析

import React, {Component} from 'react'
import SimpleStorageContract from '../build/contracts/SimpleStorage.json'
import getWeb3 from './utils/getWeb3'

import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'

const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: 'localhost', port: '5001', protocol: 'http'});

const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
let account;

/** Declaring this for later so we can chain functions on SimpleStorage.**/
let contractInstance;
//ipfs保存图片方法//
let saveImageOnIpfs = (reader) => {
  return new Promise(function(resolve, reject) {
    const buffer = Buffer.from(reader.result);
    ipfs.add(buffer).then((response) => {
      console.log(response)
      resolve(response[0].hash);
    }).catch((err) => {
      console.error(err)
      reject(err);
    })
  })
}

//创建构造函数,添加状态机变量//

class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      blockChainHash: null,
      web3: null,
      address: null,
      imgHash: null,
      isWriteSuccess: false
    }
  }
//程序启动默认调用方法//
  componentWillMount() {
    //打印项目中网络节点//
    ipfs.swarm.peers(function(err, res) {
      if (err) {
        console.error(err);
      } else {
        /** var numPeers = res.Peers === null ? 0 : res.Peers.length;**/
        /** console.log("IPFS - connected to " + numPeers + " peers");**/
        console.log(res);
      }
    });
    //web3设置,同时调用初始化方法//
    getWeb3.then(results => {
      this.setState({web3: results.web3})

      // Instantiate contract once web3 provided.
      this.instantiateContract()
    }).catch(() => {
      console.log('Error finding web3.')
    })
  }
    //初始化合约实例、web3获取合约账号以及合约实例//
  instantiateContract = () => {

    simpleStorage.setProvider(this.state.web3.currentProvider);
    this.state.web3.eth.getAccounts((error, accounts) => {
      account = accounts[0];
      simpleStorage.at('0xf6a7e96860f05f21ecb4eb588fe8a8a83981af03').then((contract) => {
        console.log(contract.address);
        contractInstance = contract;
        this.setState({address: contractInstance.address});
        return;
      });
    })

  }
  render() {
    return (<div className="App">
      {
        this.state.address
          ? <h1>合约地址:{this.state.address}</h1>
          : <div/>
      }
      <h2>上传图片到IPFS:</h2>
      /**这一部分用于上传文件到ipfs**/
      <div>
        <label id="file">Choose file to upload</label>
        <input type="file" ref="file" id="file" name="file" multiple="multiple"/>
      </div>
      <div>
        <button onClick={() => {
            var file = this.refs.file.files[0];
            var reader = new FileReader();
            // reader.readAsDataURL(file);
            reader.readAsArrayBuffer(file)
            reader.onloadend = function(e) {
              console.log(reader);
              saveImageOnIpfs(reader).then((hash) => {
                console.log(hash);
                this.setState({imgHash: hash})
              });

            }.bind(this);

          }}>将图片上传到IPFS并返回图片HASH</button>
      </div>
       /**这一部分用于上传hash到区块链**/
      {
        this.state.imgHash
          ? <div>
              <h2>imgHash:{this.state.imgHash}</h2>
              <button onClick={() => {
                  contractInstance.set(this.state.imgHash, {from: account}).then(() => {
                    console.log('图片的hash已经写入到区块链!');
                    this.setState({isWriteSuccess: true});
                  })
                }}>将图片hash写到区块链:contractInstance.set(imgHash)</button>
            </div>
          : <div/>
      }
      {
        this.state.isWriteSuccess
          ? <div>
              <h1>图片的hash已经写入到区块链!</h1>
              <button onClick={() => {
                  contractInstance.get({from: account}).then((data) => {
                    console.log(data);
                    this.setState({blockChainHash: data});
                  })
                }}>从区块链读取图片hash:contractInstance.get()</button>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h3>从区块链读取到的hash值:{this.state.blockChainHash}</h3>
            </div>
          : <div/>
      }
      {
        this.state.blockChainHash
          ? <div>
              <h2>浏览器访问:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
              <img alt="" style={{width:200}} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
            </div>
          : <img alt=""/>
      }
    </div>);
  }
}

export default App



该项目算是truffle和ipfs结合以太坊一起使用的综合案例,用与梳理知识点
---------------------
作者:czZ__czZ
来源:CSDN
原文:https://blog.csdn.net/czZ__czZ/article/details/79036567
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-06-25 08:21 狼爱上狸 阅读(326) | 评论 (0)编辑 收藏

nodejs-执行报错Error: Cannot find module 'express'

  1. C:\Users\0>node E:\项目\2018年\11月份\nodejs\express_demo.js
  2. module.js:471
  3. throw err;
  4. ^
  5. Error: Cannot find module 'express'
  6. at Function.Module._resolveFilename (module.js:469:15)
  7. at Function.Module._load (module.js:417:25)
  8. at Module.require (module.js:497:17)
  9. at require (internal/module.js:20:19)
  10. at Object.<anonymous> (E:\项目\2018年\11月份\nodejs\express_demo.js:1:77)
  11. at Module._compile (module.js:570:32)
  12. at Object.Module._extensions..js (module.js:579:10)
  13. at Module.load (module.js:487:32)
  14. at tryModuleLoad (module.js:446:12)
  15. at Function.Module._load (module.js:438:3)
  16. C:\Users\0>express --version
  17. 4.16.0

实际上我是有安装express模块的

奇了个怪了。

然后试过1种方法是进入项目目录再执行安装express模块,无效

最后,原来是node_modules没有配置环境变量

配置上吧:

1、控制面板\所有控制面板项\系统\高级系统设置\环境变量

新建设‘NODE_PATH’:C:\Users\0\AppData\Roaming\npm\node_modules

 编辑增加环境变量‘PATH’

完美~~


http://www.pianshen.com/article/837378161/


posted @ 2019-06-23 22:31 狼爱上狸 阅读(1562) | 评论 (0)编辑 收藏

调用智能合约简单运算总返回0的问题

1.合约内容
pragma
solidity ^0.5.9;

contract hello {

function mutiply(uint a) public pure returns (uint result) {

return a*3;

}
}
2.部署合约:
var Web3 = require("web3");
var fs = require("fs");
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
var code = '0x' + fs.readFileSync("2_sol_hello.bin").toString();
var abi = JSON.parse(fs.readFileSync("2_sol_hello.abi").toString());
var contract = web3.eth.contract(abi);
console.log(web3.eth.accounts);
console.log('account balance:' + web3.eth.getBalance(web3.eth.accounts[0]))

web3.personal.unlockAccount(web3.eth.accounts[0],"123")
var contract = contract.new({from: web3.eth.accounts[0], data: code, gas: 470000},
function(e, contract){

if(!contract.address) {
console.log("已经发起交易,交易地址:" + contract.transactionHash + "\n正在等待挖矿");
} else {
console.log("智能合约部署成功,地址:" + contract.address);

}

}
)
3.调用合约
var Web3 = require("web3");
var fs = require("fs");
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
var abi = JSON.parse(fs.readFileSync("2_sol_hello.abi").toString());
var contract = web3.eth.contract(abi);
var instance = contract.at('0xb06846c54c6ae67102ed67ce57a357a643d1f1b8')
web3.personal.unlockAccount(web3.eth.accounts[0],"123")
console.log(instance.mutiply(12).toString())
4.显示结果为:
0
原因:solc版本0.5.9太高,可能调用的方法不对。
解决方法:npm install -g solc@0.4.22
降低版本,然后把合约第一行改为:
pragma solidity ^0.4.22;
问题解决。

posted @ 2019-06-23 18:12 狼爱上狸 阅读(287) | 评论 (0)编辑 收藏

以太坊(二)MAC搭建以太坊私有链多节点集群(同一台电脑)

https://www.jianshu.com/p/52e9588116ad

posted @ 2019-06-20 14:47 狼爱上狸 阅读(222) | 评论 (0)编辑 收藏

web3.php Error: The method personal_newAccount does not exist/is not available

很多人遇到这个问题:

web3.php Error: The method personal_newAccount does not exist/is not available。

其实很简单,我们只需要在geth启动时的rpc参数中设置rpcapi时包括 "personal" 即可。

geth --rpc --rpcaddr 0.0.0.0 --rpcport 8545 --rpcapi eth,web3,admin,personal,net


来自:http://www.bcfans.com/toutiao/redian/101819.html


我的是:
geth --identity "Water" --rpc --rpcport "8080" --rpccorsdomain "*" --datadir gethdata --port "30303" --nodiscover --rpcapi "db,eth,net,personal,web3" --networkid 1999 init genesis.json

posted @ 2019-06-19 10:42 狼爱上狸 阅读(535) | 评论 (0)编辑 收藏

windows安装web3

1.安装web3要先安装node。
2.cmd->powershell
3.c:\>node
  >require('web3')
结果输出一些错误,表明还没安装web3。
4.c:\>npm install web3
5.安装后,再
 c:\>node
  >require('web3')
输出
[Function:Web3]
表明web3就安装好了。

posted @ 2019-06-17 14:26 狼爱上狸 阅读(813) | 评论 (1)编辑 收藏

本地自动化编译、部署和调用智能合约

https://blog.csdn.net/qiubingcsdn/article/details/89703128

posted @ 2019-06-15 23:05 狼爱上狸 阅读(237) | 评论 (0)编辑 收藏

本地搭建以太坊私有网络-基于Ganache和MetaMask

    背景介绍

本文主要介绍如何使用Ganache,在本地搭建以太坊私有网络,并进行简单的测试。

 

    所需软件

      Ganache

Ganache用于搭建私有网络。在开发和测试环境下,Ganache提供了非常简便的以太坊私有网络搭建方法,通过可视化界面可以直观地设置各种参数、浏览查看账户和交易等数据。

下载地址为:https://truffleframework.com/ganache/

        MetaMask

MetaMask用于测试私有网络。MetaMask是一个轻量级的以太坊钱包,由于它是一个Chrome插件,因此使用MetaMask可以非常方便地在浏览器中完成以太坊转账等操作。

下载地址为:https://www.metamask.io

 

    操作步骤

     安装、启动Ganache

1. 使用安装包安装即可。

2. 打开程序后,会显示以下界面,用户可以查看账户(默认创建10个账户)、区块、交易和日志。

 

3. 点击“设置”,如下图所示,用户还可以设置绑定的ip和端口(设置为8545即可,稍后MetaMask会用这个端口)、账户数量以及gas限制等,点击“restart”后设置生效。

 

此时,Ganache已经在本机运行了一个以太坊私有网络,并绑定了8545端口。

 

    安装、启动MetaMask

1. 把插件添加到chrome扩展程序即可

2. 点击Chrome中的MetaMask图标,按照每一步提示启动MetaMask

3. 如下图所示,设置MetaMask连接到本地的以太坊私有网络

    

此时,MetaMask就可以和本地的以太坊私有网络进行交互了。

 

    用MetaMask测试私有网络

1. 从Ganache创建的账户中选择一个导入到MetaMask中

    a. 在Ganache账户页面选定一个账户,点击最右边的小钥匙图标,复制其私钥(private key)

    b. 在MetaMask中点击头像,选择 “import account”,弹出对话框

    c.  把复制的账户私钥填入文本框中,并点击“import”

 

此时,MetaMask就可以操作这个新账户了。

 

2. 用新导入的账户进行转账

    a. 点击“send”按钮,弹出转账对话框

    b. 从Ganache账户页面中,再选定一个其他的账户,复制其地址

    c. 把复制的地址填入到 “to” 文本框中,并在“amount”文本框中填入一个数值,表示要转账的金额(如 “10”);其它文本框默认值即可

    d. 点击next,弹出转账确认框,点击“confirm”确认交易

    e. 提醒转账成功后,可以看到账户余额发生了变化,此时再转到Ganache账户页面,也可看到两个账户的余额也都发生了变化。

 

    注意

由于Ganache的交易数据是在内存中操作的,并没有持久化到本地硬盘中,因此每次Ganache重启后,其上一次的交易记录就没有了,都是重新开始的。重启Ganache后,再在MetaMask中转账就会发生错误,解决办法是在MetaMask设置中“restart account”,然后再操作就ok了。

如果想保留Ganache每一次运行时的交易数据,以便下一次继续使用,可以使用命令行的形式ganache-cli启动Ganache,并指定数据存储目录
---------------------
作者:BigCuttie
来源:CSDN
原文:https://blog.csdn.net/starleelzx/article/details/82943530
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-06-13 22:51 狼爱上狸 阅读(988) | 评论 (0)编辑 收藏

仅列出标题
共38页: First 上一页 5 6 7 8 9 10 11 12 13 下一页 Last