准备工作:转账之前你得有一个ERC20代币,代币发行戳这里,可以在测试网上进行测试。
因为发行代币本质就是部署智能合约,是需要消耗gas的,代币转账也是需要消耗eth作为手续费的。
准备工作完成之后,就让我们直接进行ERC20代币转账吧~
通过调用web3j的API完成相关操作,所需maven依赖:
org.web3j
core
3.2.0
一:代币转账
该代币转账是通过构建原始交易的方式进行的,请看代码,主网亲测有效~
/**
* erc20代币转账
*
* @param from 转账地址
* @param to 收款地址
* @param value 转账金额
* @param privateKey 转账这私钥
* @param contractAddress 代币合约地址
* @return 交易哈希
* @throws ExecutionException
* @throws InterruptedException
* @throws IOException
*/
public static String transferERC20Token(String from, String to, BigInteger value, String privateKey, String contractAddress) throws ExecutionException, InterruptedException, IOException {
Web3j web3j = Web3j.build(new HttpService("https://mainnet.infura.io/v3/c313bf2c97834ee29d933a996caaafb0"));
//加载转账所需的凭证,用私钥
Credentials credentials = Credentials.create(privateKey);
//获取nonce,交易笔数
BigInteger nonce;
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
if (ethGetTransactionCount == null) {
return null;
}
nonce = ethGetTransactionCount.getTransactionCount();
//gasPrice和gasLimit 都可以手动设置
BigInteger gasPrice;
EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
if (ethGasPrice == null) {
return null;
}
gasPrice = ethGasPrice.getGasPrice();
//BigInteger.valueOf(4300000L) 如果交易失败 很可能是手续费的设置问题
BigInteger gasLimit = BigInteger.valueOf(60000L);
//ERC20代币合约方法
value = value.multiply(VALUE);
Function function = new Function(
TRANSFER,
Arrays.asList(new Address(to), new Uint256(value)),
Collections.singletonList(new TypeReference() {
}));
//创建RawTransaction交易对象
String encodedFunction = FunctionEncoder.encode(function);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
contractAddress, encodedFunction);
//签名Transaction
byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signMessage);
//发送交易
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
String hash = ethSendTransaction.getTransactionHash();
if (hash != null) {
return hash;
}
return null;
}
二:代币余额查询
private static final String DATA_PREFIX = "0x70a08231000000000000000000000000";
public static BigDecimal getBalance(String address, String contractAddress) throws IOException {
String value = Admin.build(new HttpService("https://mainnet.infura.io"))
.ethCall(org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address,
contractAddress, DATA_PREFIX + address.substring(2)), DefaultBlockParameterName.PENDING).send().getValue();
String s = new BigInteger(value.substring(2), 16).toString();
BigDecimal balance = new BigDecimal(s).divide(WEI, 6, RoundingMode.HALF_DOWN);
return balance;
}
以上代码主网发行的代币亲测有效,如果对您有帮助,就点个赞吧~
最后,附上简单的ERC20代币合约
pragma solidity ^0.4.25;
contract ERC20Interface {
string public constant name = "测试币";
string public constant symbol = "CSB";
uint8 public constant decimals = 18;
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract CSBToken is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowanceOf;
constructor() public payable {
name = "测试币";
symbol = "CSB";
decimals = 18;
totalSupply = 1000000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowanceOf[_from][msg.sender] >= _value);
allowanceOf[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowanceOf[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint remaining){
return allowanceOf[_owner][_spender];
}
function totalSupply() public constant returns (uint totalsupply){
return totalSupply;
}
function balanceOf(address tokenOwner) public constant returns(uint balance){
return balanceOf[tokenOwner];
}
}