java用headlong构建请求体
package com.swapbot.bsc.solidity;
import com.esaulpaugh.headlong.abi.*;
import com.esaulpaugh.headlong.util.FastHex;
import com.esaulpaugh.headlong.util.Strings;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
public class HeadlongTestUtil {
//https://github.com/esaulpaugh/headlong/
/**
* function testBool(bool _boolValue) public pure returns (bool) {
* return _boolValue;
* }
*/
public static void testBool() {
Function function = new Function("testBool(bool)");
// 创建参数 Tuple
Tuple tuple = Single.of(true);
// 编码函数调用
byte[] encoded = function.encodeCall(tuple).array();
// 转换为十六进制字符串并打印
String hexEncoded = FastHex.encodeToString(encoded);
System.out.println(Numeric.prependHexPrefix(hexEncoded));
}
/**
* function testUint256(uint256 _uint256Value) public pure returns (uint256) {
* return _uint256Value;
* }
*/
public static void testUint256() {
Function function = new Function("testUint256(uint256)");
// 创建参数 Tuple
Tuple tuple = Single.of(BigInteger.TEN);
// 编码函数调用
byte[] encoded = function.encodeCall(tuple).array();
// 转换为十六进制字符串并打印
String hexEncoded = FastHex.encodeToString(encoded);
System.out.println(Numeric.prependHexPrefix(hexEncoded));
//0x4b6390b2000000000000000000000000000000000000000000000000000000000000000a
}
/**
* function testBytes(bytes memory _bytesValue) public pure returns (bytes memory) {
* return _bytesValue;
* }
*/
public static void testBytes() {
Function function = new Function("testBytes(bytes)");
//去除0x Numeric.cleanHexPrefix()
byte[] bytes = Strings.decode("abcd");
// 创建参数 Tuple
Tuple tuple = Single.of(bytes);
// 编码函数调用
byte[] encoded = function.encodeCall(tuple).array();
// 转换为十六进制字符串并打印
String hexEncoded = FastHex.encodeToString(encoded);
System.out.println(Numeric.prependHexPrefix(hexEncoded));
}
/**
* function testStruct(MyStruct memory _myStructValue) public pure returns (MyStruct memory) {
* return _myStructValue;
* }
*/
public static void testStruct() {
Function function = new Function("testStruct((uint256,string))");
//需要注意双引号
Tuple entity = Tuple.of(BigInteger.ONE, "xx");
// 创建参数 Tuple
Tuple tuple = Tuple.from(entity);
// 编码函数调用
byte[] encoded = function.encodeCall(tuple).array();
// 转换为十六进制字符串并打印
String hexEncoded = FastHex.encodeToString(encoded);
System.out.println(Numeric.prependHexPrefix(hexEncoded));
}
}
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!