NodeClient.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace qiniu\services\blockchain\bsc;
  3. use Exception;
  4. use qiniu\services\blockchain\bsc\src\Providers\HttpProvider;
  5. use qiniu\services\blockchain\bsc\src\RequestManagers\HttpRequestManager;
  6. use qiniu\services\blockchain\bsc\src\Web3;
  7. use think\facade\Config;
  8. class NodeClient extends Web3
  9. {
  10. const Main_Net = 'https://bsc-dataseed.binance.org/';
  11. const Test_Net = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
  12. function __construct($url)
  13. {
  14. $provider = new HttpProvider(
  15. new HttpRequestManager($url, 300) //timeout
  16. );
  17. parent::__construct($provider);
  18. }
  19. static function create($network)
  20. {
  21. if ($network === 'mainNet') return self::mainNet();
  22. if ($network === 'testNet') return self::testNet();
  23. throw new Exception('unsupported network');
  24. }
  25. static function testNet()
  26. {
  27. return new self(self::Test_Net);
  28. }
  29. static function mainNet()
  30. {
  31. return new self(Config::get('blockchain.bsc.node', self::Main_Net));
  32. }
  33. function getBalance($addr)
  34. {
  35. $cb = new Callback;
  36. $this->getEth()->getBalance($addr, $cb);
  37. return $cb->result;
  38. }
  39. function broadcast($rawtx)
  40. {
  41. $cb = new Callback;
  42. $this->getEth()->sendRawTransaction($rawtx, $cb);
  43. return $cb->result;
  44. }
  45. function getReceipt($txid)
  46. {
  47. $cb = new Callback;
  48. $this->getEth()->getTransactionReceipt($txid, $cb);
  49. return $cb->result;
  50. }
  51. function waitForConfirmation($txid, $timeout = 300)
  52. {
  53. $expire = time() + $timeout;
  54. while (time() < $expire) {
  55. try {
  56. $receipt = $this->getReceipt($txid);
  57. if (!is_null($receipt)) return $receipt;
  58. sleep(2);
  59. } catch (Exception $e) {
  60. }
  61. }
  62. throw new Exception('tx not confirmed yet.');
  63. }
  64. function getBlockByNumber()
  65. {
  66. $cb = new Callback;
  67. $number = hex(436);
  68. $this->getEth()->getBlockByNumber($number, true, $cb);
  69. return $cb->result;
  70. }
  71. }