Is it possible to create a function in Solidity that would call an arbitrary function on an arbitrary contract with all the parameters?

In JavaScript I would write something like this

function callArbitrary(contract, func, params){

is there a solidity version of that?


This is generally not recommended if you're not sure what you are doing, since it can open a lot of security holes, and it is best to only call contracts that are known beforehand.

That said, the technique looks like this:

address myContract = 0xabcdef....;
myContract.call.gas(msg.gas-3000).value(1 ether)(bytes4(sha3("myFunction(uint256,bytes32,string)")), 42, 0xabc, "hello")

Essentially, you use the call method of an address, then use the gas and value properties to add gas and value (you may ommit the value if it is 0). Then you pass in the first 4 bytes of the sha3 hash of the function you wish to call.

  • thank you for the answer. But is the second line correct? it looks like it should be myContract.call – Micha Roon Sep 30 '16 at 6:52
  • Nice catch, yes it should – Tjaden Hess Sep 30 '16 at 11:29
  • I do not think this is really the answer: In this answer the parameters need to be known at compile time (since you explicitly pass them as 42, 0xabc, "hello" but even having them as variables you need to know the number of parameters and their types). I guess there should be a way to simply pass arbitrary callData (as bytes?) but I cant figure out how to do that. – SCBuergel.eth May 4 '17 at 9:45
  • You're right, this isn't a fully general answer, but I think it's a bit more clear than just passing in a bytes containing all of the calldata. If you want a fully general proxy, you can take a look at the uport proxy – Tjaden Hess May 4 '17 at 14:57
  • @TjadenHess do you have an example of serializing the data for this proxy function? – Frederic Fortier May 3 '18 at 0:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.