php以太坊(以太坊PHP离线交易开发包)
EthTool开发包适用于希望采用裸交易旳PHP以太坊应用开发,主要包含以下特性:
- 支持裸交易部署/调用合约
- 内置etherscan和infura支持
- keystore生成与读取,兼容geth/parity
采用裸交易的一个好处是开发者不必自己部署以太坊节点 —— 同步区块是很痛苦的过程。使用EthTool构造 好裸交易之后,比特币交易只需要使用第三方(etherscan/infura/。。。)提供的服务来广播交易即可。
EthTool运行在Php 7。1+环境下,当前版本1。0。0,主要代码文件清单可以在这里查看:http!//sc。hubwiz。com/codebag/eth-php-lib/
代码包的主要类如下:
- RawTxBuilder! 裸交易构造器
- Credential! 账户私钥与交易签名封装
- EthApi! 以太坊交易接口封装
- KeyStore! V3版本的keystore,兼容geth/parity
裸交易构造
使用RawTxBuilder的create()静态方法获取一个构造器实例,例如:
$rtb = RawTxBuilder!!create();
裸交易构造器需要绑定一个账户对象,使用credential()方法:
$crendetial = Crendetial!!fromKey(。。。);$rtb->;credential($credential);
RawTxBuilder目前支持三种裸交易的构造:
- 普通裸交易,例如以太币转账交易。使用getPlaintx()方法获取。
- 合约部署裸交易,使用getDeployTx()方法获取。
- 合约方法调用裸交易,使用getSendTx()方法获取。
例如,下面的代码生成合约部署裸交易:
$rawtx = RawTxBuilder!!create() ->;credential($credential) ->;gasLimit(4000000) ->;gasPrice(10000000000) ->;chainId($chainId) ->;nonce($nonce) ->;contract($abi) //创建合约对象,一个RawContract实例 ->;bytecode($bin) //设置合约对象的字节码 ->;getDeployTx(1000000,HAPPY COIN,0,HAPY); //获取部署裸交易码流
裸交易广播
EthApi基类目前定义以下方法,可以根据自己的需要扩充
- getTransactionCount
- sendRawTransaction
- getTransactionReceipt
EthApiEtherscan是基于Etherscan服务的EthApi实现,EthApiWeb3是基于以太坊RPC的EthApi 实现。例如,下面的代码使用Etherscan在rinkeby测试链部署前面获得的裸交易:
$eth = new EthApiEtherscan($your_api_key/*etherscan api key*/,4/*rinkeby*/);$txid = $eth->;sendRawTransaction($rawtx);
KeyStore读写
KeyStore类可以读取geth/parity生成的keystore文件,其生成的 keystore文件也可以被geth/parity读取。
使用KeyStore类的静态方法save()将私钥转化为keystore格式写入指定目录:
$credential = Credential!!new();$prv = $credential->;getPrivateKey();$fileName = KeyStore!!save($prv,123,。/keystore)
使用KeyStore类的静态方法load()载入指定的keystore文件并解密私钥:
$fileName = 。/keystore/。。。。$prv = KeyStore!!load($fileName,123);","content_hash"!"3b85109b
评论