chainlib-eth

Ethereum implementation of the chainlib interface
Info | Log | Files | Refs | README | LICENSE

online_transaction.py (2077B)


      1 # standard imports
      2 import sys
      3 import os
      4 
      5 # external imports
      6 from crypto_dev_signer.keystore.dict import DictKeystore
      7 from crypto_dev_signer.eth.signer import ReferenceSigner as EIP155Signer
      8 from hexathon import (
      9         add_0x,
     10         strip_0x,
     11         )
     12 
     13 # local imports
     14 from chainlib.chain import ChainSpec
     15 from chainlib.eth.connection import EthHTTPConnection
     16 from chainlib.eth.nonce import RPCNonceOracle
     17 from chainlib.eth.gas import RPCGasOracle
     18 from chainlib.eth.tx import (
     19         TxFactory,
     20         TxFormat,
     21         )
     22 from chainlib.error import JSONRPCException
     23 
     24 script_dir = os.path.dirname(os.path.realpath(__file__))
     25 
     26 
     27 # eth transactions need an explicit chain parameter as part of their signature
     28 chain_spec = ChainSpec.from_chain_str('evm:ethereum:1')
     29 
     30 # create keystore and signer
     31 keystore = DictKeystore()
     32 signer = EIP155Signer(keystore)
     33 
     34 # import private key for sender
     35 sender_keystore_file = os.path.join(script_dir, '..', 'tests', 'testdata', 'keystore', 'UTC--2021-01-08T17-18-44.521011372Z--eb3907ecad74a0013c259d5874ae7f22dcbcc95c')
     36 sender_address = keystore.import_keystore_file(sender_keystore_file)
     37 
     38 # create a new address to use as recipient
     39 recipient_address = keystore.new()
     40 
     41 # set up node connection
     42 rpc_provider = os.environ.get('RPC_PROVIDER', 'http://localhost:8545')
     43 rpc = EthHTTPConnection(rpc_provider)
     44 
     45 # check the connection
     46 if not rpc.check():
     47     sys.stderr.write('node {} not usable\n'.format(rpc_provider))
     48     sys.exit(1)
     49 
     50 # nonce will now be retrieved from network
     51 nonce_oracle = RPCNonceOracle(sender_address, rpc)
     52 
     53 # gas price retrieved from network, and limit from callback
     54 def calculate_gas(code=None):
     55     return 21000
     56 gas_oracle = RPCGasOracle(rpc, code_callback=calculate_gas)
     57 
     58 # create a new transaction
     59 tx_factory = TxFactory(chain_spec, signer=signer, nonce_oracle=nonce_oracle, gas_oracle=gas_oracle)
     60 tx = tx_factory.template(sender_address, recipient_address, use_nonce=True)
     61 tx['value'] = 1024
     62 (tx_hash, tx_rpc) = tx_factory.finalize(tx)
     63 
     64 print('transaction hash: ' + tx_hash)
     65 print('jsonrpc payload: ' + str(tx_rpc))