web3j 合约方法调用源码分析

文章目录

        • 调用方法流程
        • Function
        • RawTransaction
        • Credentials
        • signMessage
        • generateTransactionHash
        • toHexString
        • RawTransactionManager
          • 合约执行流程
        • FastRawTransactionManager
        • NoOpProcessor
        • 代码

调用方法流程
  1. 方法包括方法名,参数 返回值 (Function)
  2. 对方法进行编码(FunctionEncoder.encode)
  3. 根据none pirce limit address 方法编码 创建交易信息(RawTransaction.createTransaction)
  4. 签名交易信息 (TransactionEncoder.signMessage)
  5. 并转成16进制数据 (Numeric.toHexString)
  6. 发送交易
  7. 通过交易原数据和签名拿到hash(TransactionUtils.generateTransactionHashHexEncoded)
Function
  public Function(String name, List<Type> inputParameters, List<TypeReference<?>> outputParameters) {
        this.name = name;
        this.inputParameters = inputParameters;
        this.outputParameters = Utils.convert(outputParameters);
    }
RawTransaction
  protected RawTransaction(BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to, BigInteger value, String data, BigInteger gasPremium, BigInteger feeCap) {
        this.nonce = nonce;
        this.gasPrice = gasPrice;
        this.gasLimit = gasLimit;
        this.to = to;
        this.value = value;
        this.data = data != null ? Numeric.cleanHexPrefix(data) : null;
        this.gasPremium = gasPremium;
        this.feeCap = feeCap;
    }
Credentials
 public static Credentials create(ECKeyPair ecKeyPair) {
        String address = Numeric.prependHexPrefix(Keys.getAddress(ecKeyPair));
        return new Credentials(ecKeyPair, address);
    }
signMessage
 public static byte[] signMessage(RawTransaction rawTransaction, Credentials credentials) {
        byte[] encodedTransaction = encode(rawTransaction);
        Sign.SignatureData signatureData = Sign.signMessage(encodedTransaction, credentials.getEcKeyPair());
        return encode(rawTransaction, signatureData);
    }
generateTransactionHash
 public static byte[] generateTransactionHash(RawTransaction rawTransaction, Credentials credentials) {
        byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        return Hash.sha3(signedMessage);
    }
toHexString
 public static String toHexString(byte[] input) {
        return toHexString(input, 0, input.length, true);
    }
    
    
    public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) {
        StringBuilder stringBuilder = new StringBuilder();
        if (withPrefix) {
            stringBuilder.append("0x");
        }

        for(int i = offset; i < offset + length; ++i) {
            stringBuilder.append(String.format("%02x", input[i] & 255));
        }

        return stringBuilder.toString();
    }
RawTransactionManager
 public EthSendTransaction sendTransaction(BigInteger gasPrice, BigInteger gasLimit, String to, String data, BigInteger value, boolean constructor) throws IOException {
        BigInteger nonce = this.getNonce();
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data);
        return this.signAndSend(rawTransaction);
    }
合约执行流程
   //1
   this.executeTransaction(function);
   //2
   this.executeTransaction(function, BigInteger.ZERO);
   //3
   this.executeTransaction(FunctionEncoder.encode(function), weiValue, function.getName());
   //4 weiValue如果是转eth就是数量 如果是调用合约方法就是data
   this.executeTransaction(data, weiValue, funcName, false);
   //5
    TransactionReceipt receipt = this.send(this.contractAddress, data, weiValue, this.gasProvider.getGasPrice(funcName), this.gasProvider.getGasLimit(funcName), constructor);
    //6       
    this.transactionManager.executeTransaction(gasPrice, gasLimit, to, data, value, constructor);
    //7
    this.sendTransaction(gasPrice, gasLimit, to, data, value, constructor);

FastRawTransactionManager

维护了一个nonce 避免每次发送请求都区获取nonce
可以最大限度地减少向节点发送RPC请求的次数,从而提高交易发送的响应速度。

NoOpProcessor

使用NoOpProcessor的一个常见场景是,当我们只需要发送交易,而不关心区块事件或其他通知时,可以将其设置为事件处理器,避免不必要的事件处理开销。
这允许调用方对提交到网络的交易拥有交易哈希。

     ///使用7
     public  static TransactionManager getTxManager(Credentials credentials, Web3j web3j){
        NoOpProcessor processor = new NoOpProcessor(web3j);
        return new FastRawTransactionManager(web3j, credentials, processor);
    }
    ///使用
    this.sendTransaction(gasPrice, gasLimit, to, FunctionEncoder.encode(function), BigInteger.ZERO, false);
    
    
     public  static String sendEthTransaction(Credentials credentials, Web3j web3j,BigInteger weiValue,BigInteger gasPrice, BigInteger gasLimit, String to){
        try {
           return getTxManager(credentials,web3j).sendTransaction(gasPrice, gasLimit, to, "", weiValue, false).getTransactionHash();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
代码
@Throws(
    IOException::class,
    ExecutionException::class,
    InterruptedException::class
)
fun signTokenTransaction(
    amount: String,
    to: String,
    privateKey: String,
    coinAddress: String,
    decimals: Int,
    nonce: BigInteger
): Pair<String, String> {
    //支付的矿工费
    val gasPrice = getWeb3j().ethGasPrice().send().gasPrice
    val gasLimit = BigInteger("60000")
    val credentials = Credentials.create(privateKey)
    val amountWei =
        BigDecimal.TEN.pow(decimals).multiply(BigDecimal(amount)).toBigInteger()
    //封装转账交易
    val function = Function(
        "transfer",
        listOf<Type<*>>(
            Address(to),
            Uint256(amountWei)
        ), emptyList()
    )
    val data = FunctionEncoder.encode(function)
    //签名交易
    val rawTransaction = RawTransaction.createTransaction(
        nonce,
        gasPrice,
        gasLimit,
        coinAddress,
        data
    )
    val signMessage = TransactionEncoder.signMessage(rawTransaction, credentials)

    val hexValue = Numeric.toHexString(signMessage)
    val hash = TransactionUtils.generateTransactionHashHexEncoded(
        rawTransaction,
        Credentials.create(privateKey)
    )
    return hexValue to hash

    //广播交易
//    return getWeb3j().ethSendRawTransaction(Numeric.toHexString(signMessage)).sendAsync().get()
//        .transactionHash
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/581696.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

开发总结-Controller层

Controller层一定要try catch一下&#xff0c;不然里面报的错可能导致程序报错。 catch中就表示有错误就 Return ResultUtils.err(e.getMessage()) 必填项校验 在实体属性中添加注解 NotNull : 用在基本类 型上 不能为null 但可以为空字符串 NotEmpty : 用在集合类上 不能为…

Java Swing 桌面程序使用 GraalVM 封装为 exe 文件进行Native化

背景 本文主要基于如下两点情况&#xff0c;进行的实际案例&#xff0c;并记录的操作步骤。 使用 Java Swing 开发的小型桌面程序&#xff0c;运行需要依赖当前电脑安装 jre 环境&#xff0c;对使用者很不友好&#xff0c;且相比原生的 exe 程序偏慢。 GraalVM Native 允许开…

SpringMVC整体工作流程

. 用户发起一个请求&#xff0c;请求首先到达前端控制器前端控制器接收到请求后会调用处理器映射器&#xff0c;由此得知&#xff0c;这个请求该由哪一个Controller来进行处理(并未调用Controller)&#xff1b;前端控制器调用处理器适配器&#xff0c;告诉处理器适配器应该要…

甘特图是什么?利用甘特图来优化项目管理流程

在现代项目管理中,图表是一种强大而直观的工具,可以帮助项目经理和团队成员清晰地了解并掌控整个项目进程。其中,甘特图是最常用和最有效的图表之一。 甘特图是一种条形图,可以用来直观地展示项目中各个任务的进度、持续时间和相互关系。它由一个横轴和一个纵轴组成。横轴代表时…

[LitCTF 2023]Ping、[SWPUCTF 2021 新生赛]error、[NSSCTF 2022 Spring Recruit]babyphp

[LitCTF 2023]Ping 尝试ping一下127.0.0.1成功了&#xff0c;但要查看根目录时提示只能输入IP 查看源代码&#xff0c;这段JavaScript代码定义了一个名为check_ip的函数&#xff0c;用于验证输入是否为有效的IPv4地址。并且使用正则表达式re来匹配IPv4地址的格式。 对于这种写…

【计算机组成原理 1】计算机硬件概念

0️⃣ 参考 王道计算机考研408 1️⃣ 冯诺依曼机 核心思想【存储程序】 存储程序就是将指令先放入内存中&#xff0c;再从内存读取指令执行&#xff0c;从而实现自动化。核心 【运算器】 说明&#xff1a;在计算机系统中&#xff0c;软件和硬件在逻辑上是等效的 例如&#xf…

Debian 系统设置SSH 连接时长

问题现象&#xff1a; 通过finalshell工具连接Debian系统远程操作时&#xff0c;总是一下断开一下断开&#xff0c;要反复重新连接 &#xff0c;烦人&#xff01; 解决办法&#xff1a; 找到ssh安装目录下的配置文件&#xff1a;sshd_config vi sshd_config &#xff1a; 找到…

基于Springboot+Vue的Java项目-火车票订票系统开发实战(附演示视频+源码+LW)

大家好&#xff01;我是程序员一帆&#xff0c;感谢您阅读本文&#xff0c;欢迎一键三连哦。 &#x1f49e;当前专栏&#xff1a;Java毕业设计 精彩专栏推荐&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb;&#x1f447;&#x1f3fb; &#x1f380; Python毕业设计 &am…

Matlab实现CNN-LSTM模型,对一维时序信号进行分类

1、利用Matlab2021b训练CNN-LSTM模型&#xff0c;对采集的一维时序信号进行分类二分类或多分类 2、CNN-LSTM时序信号多分类执行结果截图 训练进度&#xff1a; 网络分析&#xff1a; 指标变化趋势&#xff1a; 代码下载方式&#xff08;代码含数据集与模型构建&#xff0c;附…

基于Springboot的爱心商城系统(有报告)。Javaee项目,springboot项目。

演示视频&#xff1a; 基于Springboot的爱心商城系统&#xff08;有报告&#xff09;。Javaee项目&#xff0c;springboot项目。 项目介绍&#xff1a; 采用M&#xff08;model&#xff09;V&#xff08;view&#xff09;C&#xff08;controller&#xff09;三层体系结构&…

Idea异常 | Process 453 is still running

问题现象 Idea启动报错"Cannot connect to already running IDE instance. Exception: Process 453 is still running" 问题原因 通常原因是Idea未正常关闭&#xff0c;导致进程锁文件没有删除。同样Pycharm等其它JeBrains等产品也有可能出现这个问题 解决办法 查…

图像预处理工具_CogImageFileTool

CogImageFileTool工具可以用来将单张图片或idb格式的图片数据库读入内存。也可使用CoglmageFileTool工具将图片插入到.idb数据库里。 添加工具 参数介绍 文件名 写入模式 读取模式 删除

正点原子[第二期]Linux之ARM(MX6U)裸机篇学习笔记-6.4

前言&#xff1a; 本文是根据哔哩哔哩网站上“正点原子[第二期]Linux之ARM&#xff08;MX6U&#xff09;裸机篇”视频的学习笔记&#xff0c;在这里会记录下正点原子 I.MX6ULL 开发板的配套视频教程所作的实验和学习笔记内容。本文大量引用了正点原子教学视频和链接中的内容。…

Django初步了解

目录 一、什么是Django 二、Django的设计模式 三、涉及的英文缩写及其含义 四、安装&#xff08;官方教程&#xff09; 一、什么是Django Django是一个Python Web框架&#xff0c;可以快速开发网站&#xff0c;提供一站式的解决方案&#xff0c;包括缓存、数据库ORM、后台…

CAPS Wizard for Mac:打字输入辅助应用

CAPS Wizard for Mac是一款专为Mac用户设计的打字输入辅助应用&#xff0c;以其简洁、高效的功能&#xff0c;为用户带来了全新的打字体验。 CAPS Wizard for Mac v5.3激活版下载 该软件能够智能预测用户的输入内容&#xff0c;实现快速切换和自动大写锁定&#xff0c;从而大大…

用Jenkins实现cherry-pick多个未入库的gerrit编译Android固件

背景: 在做Android固件开发的时候,通常我们可以利用gerrit-trigger插件,开发者提交一笔的时候自动触发jenkins编译,如果提交的这一笔的编译依赖其他gerrit才能编译过,我们可以在commit message中加入特殊字段,让jenkins在编译此笔patch的时候同时抓取依赖的gerrit代码下…

Maven介绍 主要包括Maven的基本介绍,作用,以及对应的Maven模型,可以对Maven有一个基本的了解

1、Maven介绍 1.1 什么是Maven Maven是Apache旗下的一个开源项目&#xff0c;是一款用于管理和构建java项目的工具。 官网&#xff1a;https://maven.apache.org/ Apache 软件基金会&#xff0c;成立于1999年7月&#xff0c;是目前世界上最大的最受欢迎的开源软件基金会&…

【办公类-22-13】周计划系列(5-5)“周计划-05 周计划表格内教案部分“节日”清空改成“节日“” (2024年调整版本)Win32

背景需求&#xff1a; 本学期19周&#xff0c;用了近10周的时间&#xff0c;终于把周计划教案部分的内容补全了&#xff08;把所有教案、反思的文字都撑满一个单元格&#xff09;&#xff0c; 一、原始教案 二、新模板内的教案 三、手动添加文字后的样式&#xff08;修改教案…

第 4 篇 : Netty客户端互发图片和音/视频

说明 因为图片和音/视频不能确定其具体大小, 故引入MinIO。客户端之间只发送消息, 通过上传/下载来获取额外信息 1. MinIO搭建(参考前面文章), 并启动 2. 登录MinIO创建3个Bucket: image、voice、video 3. 客户端改造 3.1 修改 pom.xml <?xml version"1.0" …

党建3d互动虚拟现实网上展厅有何优势?

在数字化浪潮席卷全球的今天&#xff0c;企业如何迅速踏上虚拟世界的征程&#xff0c;开启元宇宙之旅?答案就是——3D虚拟云展。这一创新平台&#xff0c;华锐视点以虚拟现实技术和3D数字建模为基石提供3D云展搭建服务&#xff0c;助力企业轻松搭建起虚拟数字基础设施&#xf…
最新文章