Solidity - 使用 openzeppelin 检查用户地址的余额
Solidity - Check balance of a user address using openzeppelin
我正在使用 Truffle
和 upgradable Openzeppelin contracts
。我有两份合同。
Token.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract MyToken is Initializable, ERC20Upgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC20_init("MyToken", "MTK");
_mint(msg.sender, 10000000 * 10 ** decimals());
}
}
AnotherContract.sol:
pragma solidity ^0.8.2;
import "./IAnotherContract.sol";
contract AnotherContract is IAnotherContract {
function doSomethingIfBalanceIsEnough()
external
returns (string memory)
{
// ...
}
}
我如何检查一个用户有多少 MTK
个令牌?我需要在 doSomethingIfBalanceIsEnough
函数中检查它。
代币合约implements一个balanceOf()
函数,即returns地址的代币余额。
您可以从 AnotherContract
向 MyToken
地址进行外部调用,调用其 balanceOf()
函数,将用户地址传递给它。
pragma solidity ^0.8.2;
import "./IAnotherContract.sol";
interface IERC20 {
function balanceOf(address) external view returns (uint256);
}
contract AnotherContract is IAnotherContract {
function doSomethingIfBalanceIsEnough()
external
returns (string memory)
{
uint256 userBalance = IERC20(myTokenAddress).balanceOf(msg.sender);
if (userBalance > 0) {
// ...
}
}
}
我正在使用 Truffle
和 upgradable Openzeppelin contracts
。我有两份合同。
Token.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract MyToken is Initializable, ERC20Upgradeable {
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC20_init("MyToken", "MTK");
_mint(msg.sender, 10000000 * 10 ** decimals());
}
}
AnotherContract.sol:
pragma solidity ^0.8.2;
import "./IAnotherContract.sol";
contract AnotherContract is IAnotherContract {
function doSomethingIfBalanceIsEnough()
external
returns (string memory)
{
// ...
}
}
我如何检查一个用户有多少 MTK
个令牌?我需要在 doSomethingIfBalanceIsEnough
函数中检查它。
代币合约implements一个balanceOf()
函数,即returns地址的代币余额。
您可以从 AnotherContract
向 MyToken
地址进行外部调用,调用其 balanceOf()
函数,将用户地址传递给它。
pragma solidity ^0.8.2;
import "./IAnotherContract.sol";
interface IERC20 {
function balanceOf(address) external view returns (uint256);
}
contract AnotherContract is IAnotherContract {
function doSomethingIfBalanceIsEnough()
external
returns (string memory)
{
uint256 userBalance = IERC20(myTokenAddress).balanceOf(msg.sender);
if (userBalance > 0) {
// ...
}
}
}