最近在寫solidity智能合約,用java與solidity互動程序中,需要傳遞陣列引數到智能合約,但是用web3j轉換后的陣列引數去呼叫智能合約介面一直回傳錯誤資訊,在萬能的互聯網上翻閱了大量資料后,終于解決,在此記錄一下:
首先java專案需要引入web3j的依賴包:
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.5.18</version>
<exclusions>
<exclusion>
<artifactId>okhttp</artifactId>
<groupId>com.squareup.okhttp</groupId>
</exclusion>
</exclusions>
</dependency>
合約demo代碼如下:
function arrTest(bytes32[] memory arr) public view returns(string memory) {
return bytes32ToString(arr[0]);
}
function bytes32ToString(bytes32 bname) view public returns(string memory){
// 此處要加上memory
// 先將有效字符計算出來
bytes memory bytesChar = new bytes(bname.length);
uint charCount = 0;
for(uint i = 0;i < bname.length; i++){
bytes1 char = bname[i];
if(char != 0){
charCount++;
}
}
// 新建陣列,指定長度為有效位元組長度
bytes memory bytesName = new bytes(charCount);
for(uint j = 0;j < charCount;j++){
bytesName[j] = bname[j];
}
return string(bytesName);
}
java呼叫合約方法代碼如下:
public static Bytes32 stringToBytes32(String string) {
byte[] byteValue = string.getBytes();
byte[] byteValueLen32 = new byte[32];
System.arraycopy(byteValue, 0, byteValueLen32, 0, byteValue.length);
return new Bytes32(byteValueLen32);
}
public RemoteCall<Utf8String> arrTest(List<String> data) {
//首先把String轉換成Bytes32
Bytes32[] _dataBytes32 = new Bytes32[data.size()];
List<Uint> _dataUint = new ArrayList<>();
for(int i = 0 ; i < data.size() ; i++) {
_dataBytes32[i] = stringToBytes32(data.get(i));
}
//需要使用DynamicArray 進行引數傳遞其他傳遞方式均出現錯誤 如: 直接傳入引數dataBytes32 的陣列,程式報錯 ;List形式傳參,程式報錯
DynamicArray<Bytes32> inputDataByte32 = new DynamicArray<Bytes32>(Bytes32.class , _dataBytes32);
final Function function = new Function(
"arrTest",
Arrays.<Type>asList(
//錯誤示例
//dataBytes32
//正確示例
inputDataByte32
),
Arrays.asList(
new TypeReference<Utf8String>() {
}
)
);
return executeRemoteCallSingleValueReturn(function);
}
通過各種嘗試,發現java呼叫合約帶陣列的引數,需要用 DynamicArray 作為中轉呼叫,
歡迎交流區塊鏈問題,qq群組: 786937587
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/232513.html
標籤:區塊鏈
上一篇:Vue-cli 搭建專案詳情
下一篇:markdown快速上手
