Skip to content

Instantly share code, notes, and snippets.

@SerpentChris
Last active September 28, 2017 21:12
Show Gist options
  • Save SerpentChris/369e13c8bd58cf0149ced01fd3d91860 to your computer and use it in GitHub Desktop.
Save SerpentChris/369e13c8bd58cf0149ced01fd3d91860 to your computer and use it in GitHub Desktop.
Using ethereum.tester with Solidity
# Copyright (c) 2017 Christian Calderon
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import ethereum.tools.tester as tester
from ethereum.tools.tester import Chain, ABIContract
import subprocess
import os
import json
import binascii
def sol_compile(code_path: str, *, optimized: bool=False, chain: Chain = None, creator: bytes = None) -> ABIContract:
"""Compiles a Solidity file and returns an ABIContract to use for testing.
Argument:
code_path -- str -- the path to the source file.
Keyword Arguments:
optimized -- bool -- tell the compiler to produce an optimized binary. Default is False.
chain -- Chain -- reuse a Chain object by providing it here. Default behavior creates a new Chain object.
creator -- bytes -- The private key to use for contract creation. Defaults to tester.k0.
"""
if chain is None:
chain = Chain()
if creator is None:
creator = tester.k0
code_path = os.path.abspath(code_path)
solc_args = ['solc', code_path, '--bin', '--abi']
if optimized:
solc_args.append('--optimize')
output = subprocess.run(solc_args, check=True, stdout=subprocess.PIPE).stdout.decode()
EVM_TAG = 'Binary: \n'
ABI_TAG = 'Contract JSON ABI \n'
evm_start = output.find(EVM_TAG) + len(EVM_TAG)
evm_end = output.find(ABI_TAG)
abi_start = evm_end + len(ABI_TAG)
evm = binascii.unhexlify(output[evm_start:evm_end].strip())
abi = json.loads(output[abi_start:].strip())
addr = chain.contract(evm, language='evm', sender=creator)
return ABIContract(chain, abi, addr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment