ERC20代币转账以及余额查询–java(web3j)

准备工作:转账之前你得有一个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];

}

}

android web3j 代币查询_ERC20代币转账以及余额查询--java(web3j)相关推荐

  1. VUE调用WEB3.0实现代币查询,批量转账功能

    VUE调用WEB3.0实现代币查询,批量转账功能 DeFi的爆火让越来越多的人开始关注去中心化这一概念,这也将是网络中的下一个前沿,Web3.0提出了一种去中心化的替代方案,建立在点对点的模式上.下面 ...

  2. java使用web3J进行代币转账、余额查询

    <!-- io常用工具类 --><dependency><groupId>commons-io</groupId><artifactId>c ...

  3. 加密新潮流:社交代币衰落 社区代币崛起?

    这不是 Forefront 首次回顾加密行业中代币化社区赛道的年度发展历程,但毫无疑问,2022 年的情况确实发生了很大变化. 其中 Forefront 的第一份报告<2020 年社交代币年度回 ...

  4. 最佳 DeFi 代币模型:治理代币 or 生产性代币 or veToken?

    代币经济学是一个新兴的领域. 该行业正在集体探索最佳设计.分配.效用.治理框架和其他一切.而这实际上是一张空白的画布. 随着代币团队多年来的实验,我们已经看到了几个不同的代币模型作为标准出现. 比如无 ...

  5. html怎么查QQ,q币查询 怎么查询QQ号里总共充过多少QQ币

    怎么查自己一共充了多少Q币 从开始玩QQ到现在,都冲了好多Q币了,怎么能查询一共充了多少? 首先打开手机QQ,进入主页,然后单击页面左上角的"头像"位置. 然后在打开的新页面中单击 ...

  6. 火车车次查询api代码文档及返回示例分享

    火车车次查询api代码文档及返回示例分享,支持出发站名称.到达站名称.车次类型等查询,将其集中到APP中,使用更加方便. 接口名称:火车车次查询api 接口平台:api接口 接口地址:http://a ...

  7. 天眼查一年 可查询导出代导自动发货下载

    天眼查一年 可查询导出代导自动发货下载:备忘链接 或者在这里留言,我看到就帮你们下载啦.

  8. Torah主网上线,利好不断,分析测试币与主网币的区别

    洛杉矶时间11月18日10:00 Torah官方宣布主网上线,并公告将在2021年11月20日10点正式启动漩涡节点的数据交互. 在推特中就其中对于上线问题进行回复和解答,其中测试币rVP跟主网币VP ...

  9. 代餐启示录:代餐奶昔,成年人的精装饲料?【姜太公公】

    人和猫貌似都一样--在喂猫粮的时候,我陷入了沉思.如果这只猫生活在大自然里面,会吃些什么?可能会自己抓鱼吃吧,新鲜美味.可是被驯化后呢,它吃的是一粒一粒的精装猫饲料,有点可怜哈.虽然能吃饱,但是丧失了 ...

最新文章

  1. 请给SpringBoot多一些内存
  2. R语言ggplot2可视化在lines线图的尾端添加线图标签、并且去除图例实战
  3. 前端工程化系列[02]-Grunt构建工具的基本使用
  4. band math函数_ENVI波段运算(bandmath)运算逻辑及常用运算符详解
  5. 网站制作---科讯万能搜索系统的简单实用教程
  6. html语言漂移属性,设置层的漂移_html/css_WEB-ITnose
  7. Windows 文件一直被占用,无法删除(对应解决方法)
  8. 2021-07-07 https://github.com/pasu/ExamplesforCesium/wiki
  9. 从VC6到VC9移植代码问题总结
  10. 单片机c语言设计电风扇,基于单片机的智能电风扇的设计(毕业论文).docx
  11. 复利思维研究量子计算机,复利思维到底令人能有多震撼?
  12. Swift里的CAP理论和NWR策略应用
  13. NVIDIA Forceware 260.89 Final 提升了多款游戏的性能
  14. 大数据技术_ 基础理论 之 大数据可视化
  15. 固定定位相对于当前父元素
  16. 5G承载网,到底有哪些关键技术?
  17. 【脉冲发生器的实际应用】- 大物理试验
  18. java中钩子函数回调函数_钩子函数和回调函数
  19. 计算机科学文科学士,计算机科学文科学士
  20. Android MVC框架,个人见解

热门文章

  1. 2023华中农业大学计算机考研信息汇总
  2. SpringBoot通过自定义注解实现模板方法设计模式
  3. 树形DP(放置街灯,uva 10859)
  4. PMP考试章节口诀-关键词篇(1~7章)
  5. Linux基础入门-2
  6. 字节跳动技术评级与面试
  7. 洛谷.P3374 树状数组
  8. 基于BALKANFamilyTreeJS插件的家谱可视化项目功能Demo
  9. OSI七层网络模型和网络协议
  10. oracle19c创建表空间,Oracle19c 创建表空间