I'm trying to call a function from another contract and need a way to accommodate errors.
Say contract A has the method getBalance:
function getBalance(address x)
public
view
returns(uint output)
{ output = Balance(x);}
I'd like to call this function and treat a null response as a zero. Currently, I can't get my function to simply revert, in that if I call addressA.getBalance(x), and x or addressA is misspecified, the function reverts and does not allow me to simply assume it is zero. I'd like it to find something like 'try:' in python for solidity.
Note: It's hard to communicate because I just wanted to abstract from contract logic that would be distracting, but that generates sloppy examples (so, thanks for your patience). Contract A has daughter contracts A(i). Contract B calls Contract A looking for data on A(1), A(2), and A(3). If A(1) doesn't exist, the getter function reverts, and contract B doesn't look for A(2) or A(3). I changed the code so that Contract A reports null values if A(i) doesn't exist, so that if A(1) does not exist, it presumes the output is set to default values (zero). I did this by adding an if statement within the getter function in contract A that looks to see if A(i) exists:
import "./DaughterTemplate";
.....
function getter(playerAddress) public view returns (uint data)
{
address daughter = activeDaughters[playerAddress];
if (daughter != address(0)) {
DaughterTemplate d = DaughterTemplate(daughter);
data = d.data;
}
}
x
, there is no such thing as "misspecified". Any value is legitimate, and your function should (and probably does) return a validuint
value. ForaddressA
- why would you ever "misspecify" it??? You should show your could and explain how you've managed to write a contract with this case being possible. In any case, you'll have to do that "try thing" in assembly. If you showed your code, then I might be able to explain in more specific details and an actual coding example..call
andabi.encodeWithSignature
, but it is usually not a good idea.call to ContractA.callContractB errored: VM error: revert.
revert The transaction has been reverted to the initial state.
This causes everything to stop within contract B That’s a silly example, but it also applies if I’m calling, say, another contract that has a totally different ABI (eg, I put in a correct eth address, just it’s the wrong address).