'Eth, how to call a deposit function from a smart contract

I am working on a project where I need to send ether from an user to a smart contract and from the smart contract to the user. The smart contract is code in Solidity and I'm using python and web3.py to communicate with it.

I manage to do it like this: From the user to the smart contract in my python script:

#send transaction to the smart contract
web3.eth.sendTransaction({
    'to': address,
    'from': web3.eth.defaultAccount,
    'value': 10000000000000000000
})

And from the smart contract to the user using this function:

function sendEther(address payable recipient, int _amount) public payable {
        recipient.transfer(_amout ether);
    }

Note that this function can be call in the smart contract.

But then I wanted to create a function deposit (from user to smart contract) in my smart contract:

function deposit(uint256 amount) payable public {
        require(msg.value == amount);
        // nothing else to do!
    }

So basicaly, if I need to call this function with my python script, I need to proceed like this:

contract.functions.deposit(10).transac({
        'to': address,
        'from': web3.eth.defaultAccount,
        'value': 10
    })

And by checking the balance of the smart contract, it works correctly.

But how do I need to proceed if I want to call the deposit function inside my smart contract and proceed to a transaction from user to smart contract? How do I parse the 'msg.value' in my smart contract when I call the function inside? Is that even possible?

Many thanks, Alban



Solution 1:[1]

You need to contstruct a Contract object from ABI files created by Solidity compiler.

Here is an example how to call a contract function:

>>> tx_hash = greeter.functions.setGreeting('Nihao').transact()

https://web3py.readthedocs.io/en/stable/contracts.html#contract-deployment-example

Depending on your application, usually users call the contract through their web browser where they have a wallet connected using web3.js.

Here is a nice library how to connect your dApp with your user wallet:

github.com/web3modal/web3modal

Solution 2:[2]

I think the problem is with your code

function deposit(uint256 amount) payable public {
    require(msg.value == amount);
    // nothing else to do!
}

Try using this instead:

function deposit(uint256 amount) payable public {
    require(msg.value != 0);
    // nothing else to do!
}

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 Mikko Ohtamaa
Solution 2 Tyler2P