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;
編譯通過。
本文章的項目基于春哥的博客教程
【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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
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;
問題解決。
很多人遇到這個問題:
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
背景介紹
本文主要介紹如何使用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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!