NodeClient.php 2.1 KB

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