Skip to content

Instantly share code, notes, and snippets.

@loiluu
Created August 21, 2014 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loiluu/fc89b4592ed084b7a6ab to your computer and use it in GitHub Desktop.
Save loiluu/fc89b4592ed084b7a6ab to your computer and use it in GitHub Desktop.
Ethereum example of contract calling itself
__author__ = 'loi'
contract_code = '''
command = msg.data[0]
if command == 1: #option 1
contract.storage[0] = 99
contractToCall = msg.data[1]
tmp = call(contractToCall, [2], 1)
return (tmp)
#option 2
elif command == 2:
contract.storage[0] = 1
return ('bb')
'''
import serpent
from pyethereum import transactions, blocks, processblock, utils
code = serpent.compile(contract_code)
key = utils.sha3('cow')
addr = utils.privtoaddr(key)
#initialize the block
genesis = blocks.genesis({addr: 10**18})
#This is to initialize the contract
tx1 = transactions.contract(0,10**12,10000,0,code).sign(key)
result, contract = processblock.apply_transaction(genesis, tx1)
#Call the contract
#nonce, gasprice, startgas, to, value, data
tx2 = transactions.Transaction(1, 10**12, 100000, contract, 0, serpent.encode_datalist([1, contract])).sign(key)
result, ans = processblock.apply_transaction(genesis,tx2)
print genesis.to_dict()
print('Storage at location 0 is: %s' %str(hex(genesis.get_storage_data(contract, 0))))
print 'answer ' + str(ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment