Solidity

如何加快數據從區塊鏈載入到前端?

  • April 2, 2022

我有一個函式,根據汽車的唯一 ID,它給了我它的所有特徵:

function getCarArray(uint _carId) 
       public 
       view 
       returns (uint[12] memory) 
   {
       CarData memory car = cars[_carId];

       uint[12] memory carInfo;

       carInfo[0] = car.statusEnd;
       carInfo[1] = car.number;
       carInfo[2] = car.load;
       carInfo[3] = car.capacity;
       carInfo[4] = car.region;
       carInfo[5] = car.status;
       carInfo[6] = car.abrasion;
       carInfo[7] = car.repairs;
       carInfo[8] = uint(car.currentOwner);
       carInfo[9] = uint(car.movingTo);
       carInfo[10] = car.resourceType;
       carInfo[11] = car.resourceAmount;

       return carInfo;
   }

當我在前端呼叫這個方法時,為了展示所有的汽車和它們的特性,我有很長的時間來處理這個整體。假設我有 1000 輛汽車。我經歷了所有的自動循環

for(i=0;i<1000;i++){
    contractAddress.getCarArray(i)….
}

然後我收到 1000 次對節點的呼叫,這導致載入所有資訊的時間很長。

這就是問題 - 是否有任何機制可以減少獲取所有可用汽車及其相關資訊的時間?或者在前端還是在 Solidity 方面?

用這段程式碼解決了我的問題

function getCarsInfo()
   public view
   returns (uint[] memory)
{   
   uint i;
   uint j = 0;
   uint carCount = 10; 
   uint[] memory carIdArray = new uint[](carCount);
   for (i = 0; i < carCount; i++){
       carIdArray[j] = i;
       j++;
   }

   uint lengthArray = carCount*12;
   uint[] memory allCarInfoBigArray = new uint[](lengthArray);
   i=0;
   for (j = 0; j < carIdArray.length; j++) {
       CarData memory car = cars[carIdArray[j]];

       allCarInfoBigArray[i] = car.statusEnd;
       allCarInfoBigArray[i+1] = car.number;
       allCarInfoBigArray[i+2] = car.load;
       allCarInfoBigArray[i+3] = car.capacity;
       allCarInfoBigArray[i+4] = car.region;
       allCarInfoBigArray[i+5] = car.status;
       allCarInfoBigArray[i+6] = car.abrasion;
       allCarInfoBigArray[i+7] = car.repairs;
       allCarInfoBigArray[i+8] = uint(car.currentOwner);
       allCarInfoBigArray[i+9] = uint(car.movingTo);
       allCarInfoBigArray[i+10] = car.resourceType;
       allCarInfoBigArray[i+11] = car.resourceAmount;
       i = i + 12;
   }
   return allCarInfoBigArray;
}

在輸出中,我得到一個數組,其中每輛車的所有參數都按順序寫入

   allCarInfoBigArray = [
       1550702844,0,0,20,1,0,0,0,address,0,0,0,
       1550702849,1,0,20,1,0,0,0,address,0,0,0,
       1550702851,2,0,20,1,0,0,0,address,0,0,0
       1550702855,3,0,20,1,0,0,0,address,0,0,0
       1550702860,4,0,20,1,0,0,0,address,0,0,0
       1550702865,5,0,20,1,0,0,0,address,0,0,0
       1550702870,6,0,20,1,0,0,0,address,0,0,0
       1550702875,7,0,20,1,0,0,0,address,0,0,0
       1550702880,8,0,20,1,0,0,0,address,0,0,0
       1550702885,9,0,20,1,0,0,0,address,0,0,0]

你可以有一個getCarsArray返回一個長度為 .length 的數組,12*cars並在其中填充所有汽車的數據。此外,如果您使用 v2 abi 編碼器,您可以只返回一個我相信的結構數組,這樣使用起來會更乾淨。

這將使您只需等待 1 的響應eth_call

引用自:https://ethereum.stackexchange.com/questions/67371