Reputation: 103
I need to transfer BNB from inside my token contract with solidity,can any one help about that? On bsc network.
Upvotes: 0
Views: 5431
Reputation: 43481
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);
}
}
Upvotes: 2