[Ethereum] How to call a smart contract function using Nethereum and Infura

infuranethereumsmart-contract-wallets

I am using Nethereum to call a smart contract function in Ropsten. I am also using Infura.

The function required the contract owner's permission to execute.
This is my code:

var account = new Account(ownerPrivateKey)
var web3 = new Web3(account, $"https://ropsten.infura.io/v3/{infuraId}");
var contract = web3.Eth.GetContract(abi, contractAddress);
var function = contract.GetFunction("myFunction");
var result = await function .CallAsync<dynamic>(address, true);

I got error: Nethereum.JsonRpc.Client.RpcResponseException: execution reverted: Ownable: caller is not the owner.
I think I need to sign the transaction before sending it but I don't know how.
I don't know whether I should use CallAsync or SendTransactionAsync because the function writes data down, not reading anything.
I tried SendTransactionAsync but it doesn't seem to work with Infura.
Anyone have experience with this, please help me. I am new to this.

My contract function:

function myFunction(address account, bool flag) internal {
    _address[account] = flag;
}

Best Answer

It seems that your function checks is the valid owner, hence you have a revert error message Nethereum.JsonRpc.Client.RpcResponseException: execution reverted: Ownable: caller is not the owner. This is the output after making a CallAsync and getting the solidity revert message.

If you want to change the state of the contract (mainly write to the contract / ethereum) you need to use SendTransactionAsync instead of a CallAsync

Back to the first issue, as you are working "untyped", (interacting using strings and not specific contract definitions), you need to set the from parameter to your account when making a CallAsync. You can use the account.Address for this. Mainly when doing a call / query to the smart contract, setting the from value in the CallAsync will make that the msg.sender in solidity as in a transaction call.

Check this example http://playground.nethereum.com/csharp/id/1045 (very big example not fit for here) on how to interact that way.

In the long run I recommend using the code generator with typed contract definitions, it is much easier in the long run (also gives you support for structs, generate your events, and multiple output, auto estimate gas, etc)