eth-gas-proxy

Middleware to selectively override EVM gas heuristics
git clone git://holbrook.no/eth-gas-proxy.git
Info | Log | Files | Refs

proxy.py (1357B)


      1 import json
      2 import logging
      3 
      4 import websocket
      5 
      6 logg = logging.getLogger()
      7 
      8 
      9 class Oracle:
     10 
     11     def get(self):
     12         raise NotImplementedError
     13 
     14 class JSONRPCOracle(Oracle):
     15 
     16 
     17     def __init__(self, socket, cache=None):
     18         self.query = {
     19             "jsonrpc": "2.0",
     20             "method": "eth_gasPrice",
     21             "params": [],
     22             "id": 0,
     23         }
     24         self.id_seq = 0
     25         self.socket = socket
     26         self.cache = cache
     27 
     28 
     29     def __del__(self):
     30         self.socket.close()
     31 
     32 
     33     def get(self, request_id=None):
     34         o = None
     35         if request_id == None:
     36             request_id = str(self.id_seq)
     37             self.id_seq += 1
     38    
     39         self.query['id'] = request_id
     40 
     41         try:
     42             self.socket.send(json.dumps(self.query))
     43             result = self.socket.recv()
     44             o = json.loads(result)
     45             result_hex = o['result'][2:]
     46             if len(result_hex) % 2 != 0:
     47                 result_hex = '0' + result_hex
     48             result_bytes = bytes.fromhex(result_hex)
     49             result_num = int.from_bytes(result_bytes, 'big')
     50         except Exception as e:
     51             logg.exception('backend error')
     52             if self.cache == None:
     53                 raise(e)
     54             result_num = self.cache.get()
     55 
     56         if self.cache != None:
     57             self.cache.set(result_num)
     58         return result_num