Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encode_hex helper to ensure hex strings have "0x" prefix #27

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions ethjsonrpc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from ethereum.abi import encode_abi, decode_abi

from ethjsonrpc.constants import BLOCK_TAGS, BLOCK_TAG_LATEST
from ethjsonrpc.utils import hex_to_dec, clean_hex, validate_block
from ethjsonrpc.utils import hex_to_dec, clean_hex, validate_block, encode_hex
from ethjsonrpc.exceptions import (ConnectionError, BadStatusCodeError,
BadJsonError, BadResponseError)

Expand Down Expand Up @@ -98,6 +98,9 @@ def create_contract(self, from_, code, gas, sig=None, args=None):
types = sig[sig.find('(') + 1: sig.find(')')].split(',')
encoded_params = encode_abi(types, args)
code += encoded_params.encode('hex')
if not code.startswith('0x'):
code = '0x' + code

return self.eth_sendTransaction(from_address=from_, gas=gas, data=code)

def get_contract_address(self, tx):
Expand All @@ -113,7 +116,7 @@ def call(self, address, sig, args, result_types):
transaction (useful for reading data)
'''
data = self._encode_function(sig, args)
data_hex = data.encode('hex')
data_hex = encode_hex(data)
response = self.eth_call(to_address=address, data=data_hex)
return decode_abi(result_types, response[2:].decode('hex'))

Expand All @@ -125,7 +128,7 @@ def call_with_transaction(self, from_, address, sig, args, gas=None, gas_price=N
gas = gas or self.DEFAULT_GAS_PER_TX
gas_price = gas_price or self.DEFAULT_GAS_PRICE
data = self._encode_function(sig, args)
data_hex = data.encode('hex')
data_hex = encode_hex(data)
return self.eth_sendTransaction(from_address=from_, to_address=address, data=data_hex, gas=gas,
gas_price=gas_price, value=value)

Expand All @@ -147,7 +150,7 @@ def web3_sha3(self, data):

TESTED
'''
data = str(data).encode('hex')
data = encode_hex(str(data))
return self._call('web3_sha3', [data])

def net_version(self):
Expand Down
6 changes: 6 additions & 0 deletions ethjsonrpc/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ def clean_hex(d):
'''
return hex(d).rstrip('L')

def encode_hex(s):
'''
encode string to hex, adding 0x prefix
'''
return '0x' + s.encode('hex')

def validate_block(block):
if isinstance(block, basestring):
if block not in BLOCK_TAGS:
Expand Down