I have two contracts, an active contract A is interacting with the external world and many passive contracts P (dynamically added) are designed to trigger some functions when in contract A certain conditions are met.
Therefore contract A is supposed to call a callback function of each of P contracts; I was wondering what would be the best way to register
a callback function of newly added P into already deployed contract A?
contract A{
uint numberOfContractsAdded;
struct ToCallBackContracts{
address contractAddress;
bytes4 contractMethodToCall;
bytes32 theOnlyArgument;
}
mapping(uint -> ToCallBackContracts) contracts;
constructor A(){}
function triggeredFromOutside(bytes32 param)public returns (bool){
for(var i=0; i<numberOfContractsAdded; i++){
//2- how? call the callback function of each registered contract
}
}
function registerCallback(bytes4 _cMethod, address _cAddress){
//1- how? to save contract/method, number of parameters to receive?
}
}
contract P{
address addressOfA;
constructor P(address _addressOfA){
addressOfA = _addressOfA;
}
function _callback(bytes32 param){
//do something
}
function callFromOutsideToRegisterWithA(bytes32 param){
//3- how? to register with A
}
}
There are 3 HOWs pointed out in the code for better understanding to summarize the question if I understand it right..
disclaimer: code is not tested/compiled/checked for syntax and only for demonstration purposes.
Best Answer
This is what I came up with by filling in the blanks and edidting your code as little as possible. The difference with using events in your case, is that for each callback, a different value for
param
can be provided.I'm certainly not very fond of this architure, as I think you should use interfaces instead, but alas.
To use it, first deploy
A
. The, deploy aP
using the address of the deployedA
. After that, callP
'scallFromOutsideToRegisterWithA
method. This registersP
and its_callback
method withA
. To set the value of the argument that is going to be sent to the_callback
method ofP
, useA
'ssetTheOnlyArgument
method providing the address ofP
and the value you wantA
to pass to it.Then, call
A
'striggeredFromOutside
method, which whill call each registeredP
's callback, passing along the given value fortheOnlyArgument
.