[Ethereum] accepting ether in a smart contract

etherethereumjsremixsolidity

I want to create a simple smart contract for registration of users to a competition where when users can pay to contract and 2 ethers will deduct from his account.
But when I'm trying to do so on my local ganache blockchain,only gas price is being deducted.

But I'm confused on how to accept payments from ethereum network accounts to the contract.

Help me..

Here's the code

pragma solidity >=0.4.22;

contract dCoders {
    // variables
    // storing contract_amount collected for the event
    address public owner;
    uint public regFee;

    mapping (address => uint) public balance; 

    constructor() public {
        owner = msg.sender;
        regFee = 2 ether;
    }

    event reg(address indexed _from);

    // register a user in the event
    function register() payable public {
        // emit reg(_sender, owner, regFee);

        balance[msg.sender] -= regFee;
        balance[address(this)] += regFee;   

        emit reg(msg.sender);
    }

    // distribute the amount collected to winners

    // register a sponser in the event
}

Best Answer

pragma solidity >=0.4.22;

contract dCoders {
 //variables
 //storing contract_amount collected for the event
 address public owner;
 uint public regFee;

 mapping (address => uint) public balance; 

  constructor() public {
  owner = msg.sender;
  regFee = 2 ether;
  }

  event reg(address indexed _from);

  //register a user in the event
 function register() payable external {
 require(msg.value == 2 ether);
 balance[address(this)] += regFee;     
 emit reg(msg.sender); 
 }

 //distribute the amount collected to winners

  //register a sponser in the event

  }

Assuming that at the moment you need to draft only, here it is.

1) you do not need to decrement any balance for your user: it is done automatically when he sends ethers to you and you accept them. The “balance” mapping is a local-to-your contract variable only. It is written by you in order to be readed by you

2) you can call your function “register” or you can avoid to name it.

function () payable external {
...
}

In this way your user must send 2 ether to the contract without calling nothing. This way he can use any wallet to do it.

Just to help you to start... 😉

Related Topic