最近在作以太坊智能合約DAPP的開發,在使用PHP作接口的時候遇到不少問題,記錄下來當作參考。本文的操做環境爲Mac,已經安裝好truffle
/ganache
等開發須要的相關工具php
新建truffle項目laravel
mkdir test_truffle cd test_truffle truffle init
pragma solidity ^0.4.17; contract Hello_falco { function say() public pure returns (string) { return "Hello falco"; } function print(string name) public pure returns (string) { return name; } }
執行truffle compile
命令web
能夠看到Hello_falco.sol這個合約已經編譯了
編譯好的合約都會在build/contracts下生成一個json文件,打開剛剛生成的Hello_falco.json文件,能夠看到有abi
,bytecode
等信息,之後要用到json
配置truffle.js
bash
module.exports = { networks: { development: { host: "127.0.0.1", port: 9545,//我本機的ganache端口 network_id: "*" } } };
執行truffle migrate --reset
命令composer
合約已經遷移過去了,會消耗主帳號一部分ETH,能夠看到帳號餘額已經發生了變化函數
執行truffle console
,打開控制檯工具
truffle(development)> var contract; undefined truffle(development)> Hello_falco.deployed().then(function(instance){contract= instance;}); undefined truffle(development)> contract.say(); 'Hello falco'
上面爲使用truffle部署和測試合約,下面會使用PHP操做web3的方式再部署一次測試
composer require jcsofts/laravel-ethereum
詳細安裝說明Laravel ethereumui
配置.env
文件
ETH_HOST=http://127.0.0.1 ETH_PORT=9545
use Jcsofts\LaravelEthereum\Facade\Ethereum; use Jcsofts\LaravelEthereum\Lib\EthereumTransaction; private $mainAddress = "0x80d2F5BA14983a671e29068958Eb60a45b01e49c"; public function deploy(){ $byteCode = "xxx"; $ethereumTransaction = new EthereumTransaction( $this->mainAddress,null,null,'0x47b760',null,$byteCode); $response = Ethereum::eth_sendTransaction($ethereumTransaction); dd($response); }
主帳號地址爲ganache的第一個帳戶地址
智能合約的byteCode使用的是編譯好的Hello_falco.json中的bytecode段0x47b760
爲gas,我設置的固定值用做測試
執行deploy方法以後,咱們把response打印出來
0x0ca011fd3856b34ee5169ec0c0ddad465f5e6bec1795751b41bbab9e295ac0a0
這是一段TransactionHash,稍等以後咱們來經過它來取部署後的合約地址
public function receipt(){ $hash = "0x0ca011fd3856b34ee5169ec0c0ddad465f5e6bec1795751b41bbab9e295ac0a0"; $response = Ethereum::eth_getTransactionReceipt($hash); dd($response); }
如圖咱們拿到了合約地址,以後就能夠經過上面的合約地址來執行智能合約內定義的方法體了
要訪問合約內的方法咱們首先要獲取方法的簽名(function signature),那麼如何獲取方法簽名呢?
1.進入truffle console
控制檯
2.經過web3的sha3方法計算
truffle(development)> web3.sha3("say()") '0x954ab4b21481711a1e363afa5d2b9003ed2702949b83f2d36d03d3b90ebb0f26' truffle(development)> web3.sha3("say()").substr(2,8) '954ab4b2'
只須要拿到除去0x的前八位便可
繼續編寫say方法php函數
public function say(){ $contractAddress = "0x00a800ff57861294dd3db449dbe0367ae66d9e86"; $ethereumTransaction = new EthereumTransaction( $this->mainAddress,$contractAddress,null,'0x47b760',null,'0x954ab4b2'); $response = Ethereum::eth_sendTransaction($ethereumTransaction); dd($response); }
執行完以後咱們會獲得一串TransactionHash
若是一切正常那麼咱們的ganache log裏會出現一個新區塊,php返回的TransactionHash就是這個區塊的Hash
若是出現錯誤或者方法不存在,會出現下面的狀況
以上是一個簡單的hello world拋磚引玉,咱們能夠編寫更復雜的合約,好比拍賣、競猜的智能合約。
簡單說下拍賣智能合約思路: