0

I need to transfer BNB from inside my token contract with solidity,can any one help about that? On bsc network.

M.Alaghemand
  • 105
  • 2
  • 6

1 Answers1

2

To transfer BNB from your contract to a recipient, you can use the transfer() member method of address payable.

The ether unit simply multiplies the number by 10^18, because the transfer() method accepts the amount in the smallest units - not in BNB (or ETH depending on which network you are).

pragma solidity ^0.8;

contract MyContract {
    function foo() external {
        address recipient = address(0x123);
        payable(recipient).transfer(1 ether);
    }
}

If you want to accept BNB from the sender, you need to mark your function as payable. Then they'll be able to send BNB along with the transaction executing your function.

If you want to transfer tokens belonging to your contract address, you can execute the token contract's function transfer().

pragma solidity ^0.8;

interface IERC20 {
    function transfer(address recipient, uint256 amount) external returns (bool);
}

contract MyContract {

    // this function can accept BNB
    // the accepted amount is in the `msg.value` global variable
    function foo() external payable {
        IERC20 tokenContract = IERC20(address(0x456));
        // sending 1 smallest unit of the token to the user executing the `foo()` function
        tokenContract.transfer(msg.sender, 1);
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Actually I want to get BNB from recipient to my address and send him my token. Can explain more what I have to do? – M.Alaghemand Dec 12 '21 at 14:19
  • 1
    @M.Alaghemand No problem, I updated my answer with a simple example of receiving BNB from the user, and sending tokens. – Petr Hejda Dec 12 '21 at 15:05
  • Tnx petr,you said //this function can accept BNB, then write nothin amd then write foo() for sending token, foo function just are sending token,there is nothing about sending bnb,in your first function instead 1 ether what I shoud to write? – M.Alaghemand Dec 12 '21 at 16:17
  • 1
    @M.Alaghemand It's the `payable` keyword that is important here. If the user sends BNB `value` along with the transaction, only `payable` function can accept it. Sending BNB to non-payable functions reverts... Mind that the sender always needs to make the first step - there's by design no way to pull funds from the user address without them sending the funds proactively. – Petr Hejda Dec 12 '21 at 21:00