- 所需环境
- TP版本:thinkphp 5
- 节点服务器:https://infura.io/
- 所需扩展
- JSON-RPC(也可以使用web3)
- guzzlehttp(https://github.com/guzzle/guzzle)
- ethereum-client (https://github.com/myxtype/ethereum-client)
- simplito(https://github.com/simplito/elliptic-php)
- neb.php(https://github.com/nebulasio/neb.php)
- gmp PHP扩展
- scrypt PHP扩展
- 发行代币
- 创建钱包
-
$client = new \Client($this->url); list($address, $privateKey) = $client->newAccount();
生成钱包地址以及私钥。
-
私钥一般通过keystore进行加密存储
-
- 钱包加密/解密
-
public function toKeyStore($password = '', $privateKey = '') { //私钥加密 $acc1 = Account::newAccount(); $acc1->setPrivateKey($privateKey); $keyString = $acc1->toKeyStore($password); return $keyString; } public function fromKeyStore($keyString = '', $password = '') { //私钥解密 $data = Account::fromKeyStore($keyString, $password);//解密 $privateKey = $data->getPrivateKey(); return $privateKey; }
-
- 转账交易
- 如果是代币转账,使用remix 发行代币后,一定要记录好合约地址。
- 如果是USDT(0xdac17f958d2ee523a2206206994597c13d831ec7)或其他币种,去ETH区块链浏览器中查询合约地址。
-
public function transfer($from = '', $address = '', $privateKey = '', $num = '', $hash = '') { //转账 $client = new \Client($this->url); $client->addPrivateKeys([$privateKey]); $contract = '';//合约地址 //代币转账VALUE=0 即可 $trans = [ "from" => $from, "to" => $contract, "value" => '0x0', ]; $hash = Keccak::hash("transfer(address,uint256)", 256); $hash_sub = mb_substr($hash, 0, 8, 'utf-8'); $fill_from = Tool::fill0(Utils::remove0x($address));//收款地址加密 //转账金额 $num10 = Utils::ethToWei($num); $num16 = Utils::decToHex($num10); $count = Tool::fill0(Utils::remove0x($num16));//转账金额加密后 //拼接 data 字符串 $trans['data'] = "0x" . $hash_sub . $fill_from . $count;; $trans['gas'] = dechex(hexdec($client->eth_estimateGas($trans)) * 1.5);//计算GAS值 $trans['gasPrice'] = $client->eth_gasPrice(); $trans['nonce'] = $client->eth_getTransactionCount($from, 'pending');//查询最后的区块 $return_array = $client->sendTransaction($trans);//广播交易 $return_array = json_decode($return_array, true); }
- 交易监听
- 需要自己写轮询或者websocket 进行监听区块链交易,查询到有自己数据库中同样的钱包地址,进行后续的处理
- 需要自己写轮询或者websocket 进行监听区块链交易,查询到有自己数据库中同样的钱包地址,进行后续的处理
- 交易归集
- 如果是一个纯钱包,其实做不做归集都可以,转账款矿工费用,可由用户自行承担。
- 非纯钱包,需要监听到数据后,归集到平台总账户,归集完成后,更新用户数据,用户发起提币时,再有总账户转账到指定地址。
- 如有更好的方式或者技术,欢迎留言交流