Try โ€‚โ€‰HackMD

msg.value vs ERC-20 Solidity Examples

Ethereum Example

This example uses msg.value the native token of a network

/// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; contract Game { function startGame() external payable { (bool sent, bytes memory data) = payable(address(this)).call{value: msg.value}(""); require(sent, "Failed to send Ether"); } }

ERC-20 Example

This example uses an ERC-20 token which can vary network by network.
This example also uses Open Zeppelin for the ERC-20 standard.

/// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import โ€œ@openzeppelin/contracts/token/ERC20/IERC20.solโ€; contract Game { IERC20 token; constructor(address token) { token = IERC20(token); } function startGame() external { (bool succes, ) = token.transferFrom(msg.sender, payable(address(this)), 1 ether); require(success, "Failed To Transfer"); } }

SafeERC20 Utility

This is an extension on the above example that handles the error catching/throwing for you on failed transfers.

/// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import โ€œ@openzeppelin/contracts/token/ERC20/IERC20.solโ€; contract Game { using SafeERC20 for IERC20; IERC20 token; constructor(address token) { token = IERC20(token); } /** * SafeERC20 handles throwing an error for you */ function startGame() external { token.safeTransferFrom(msg.sender, payable(address(this)), 1 ether); } }