| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace blockchain\web3;
- use Exception;
- use blockchain\web3\src\Providers\HttpProvider;
- use blockchain\web3\src\RequestManagers\HttpRequestManager;
- use blockchain\web3\src\Web3;
- use think\Cache;
- use think\Config;
- class NodeClient extends Web3
- {
- const Main_Net = 'bsc-dataseed.binance.org';
- const Test_Net = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
- function __construct($url)
- {
- $provider = new HttpProvider(
- new HttpRequestManager($url, 300) //timeout
- );
- parent::__construct($provider);
- }
- static function create($chain, $network)
- {
- if ($network === 'mainNet') return self::mainNet($chain);
- if ($network === 'testNet') return self::testNet();
- throw new Exception('unsupported network');
- }
- static function testNet()
- {
- return new self(self::Test_Net);
- }
- static function mainNet($chain)
- {
- $info = Config::get('blockchain.' . $chain);
- return new self('https://' . ($info['node'] ?? self::Main_Net) . '/');
- }
- function getBalance($addr)
- {
- $cb = new Callback;
- $this->getEth()->getBalance($addr, $cb);
- return $cb->result;
- }
- function broadcast($rawtx)
- {
- $cb = new Callback;
- $this->getEth()->sendRawTransaction($rawtx, $cb);
- return $cb->result;
- }
- function getReceipt($txid)
- {
- $cb = new Callback;
- $this->getEth()->getTransactionReceipt($txid, $cb);
- return $cb->result;
- }
- function waitForConfirmation($txid, $timeout = 300)
- {
- $expire = time() + $timeout;
- while (time() < $expire) {
- try {
- $receipt = $this->getReceipt($txid);
- if (!is_null($receipt)) return $receipt;
- sleep(2);
- } catch (Exception $e) {
- }
- }
- throw new Exception('tx not confirmed yet.');
- }
- function getBlockByNumber()
- {
- $cb = new Callback;
- $number = hex(436);
- $this->getEth()->getBlockByNumber($number, true, $cb);
- return $cb->result;
- }
- }
|