'How to call external contract with abi.encodeWithSignature with no arguments?

I'm using solidity 0.5.16 and in a contract's function, I want to make a call to another contract's initialize() method. This method does not take in any arguments.

        contract.call.value(0)(
          abi.encodeWithSignature("initialize()",);
        );

However the above method does not compile properly..



Solution 1:[1]

  1. Don't use the reserved keyword contract - replace it to externalContract for example.

  2. When you're not passing any arguments, remove the comma sign , within the encodeWithSignature() function.

  3. Remove the semicolon ; after the encodeWithSignature(). This would cause another parse error because you're still building an argument within the call function.

pragma solidity 0.5.16;

contract MyContract {
    function foo() external {
        address externalContract = address(0x123);
        (bool success, bytes memory returnedData) = externalContract.call.value(0)(
            abi.encodeWithSignature("initialize()")
        );
    }
}

Solution 2:[2]

The above syntax is deprecated now, you can use this instead:

pragma solidity ^0.8.0;

contract MyContract {
    function foo() external {
        address externalContract = address(0x123);
        (bool success, bytes memory returnedData) = externalContract.call{value: 0}(abi.encodeWithSignature("initialize()"));
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petr Hejda
Solution 2 Ghatothkachh