Solidity

運算符 == 與類型字元串儲存 ref 和 literal_string 不兼容

  • April 7, 2022

有人可以幫助解決所述錯誤,我正在嘗試執行程式碼來檢查字元串變數的狀態。在使用線上 Solidity 編譯器進行編譯時,我在 customcheck 和 portcheck 上遇到兩個錯誤。請看下面的程式碼:

contract tradefin {

   uint public prodcode;
   address public seller;
   address public buyer;
   uint public price;
   uint public units;
   address public port;
   address public customs;
   address public delivery;
   string public portcheck;
   string public customscheck;
   string public deliverycheck;
   string public msg1;


   function initiate(uint code, address vendor, address applicant, 
       uint amount, uint quantity, address p, address c, address d) {
       prodcode = code;
       seller = vendor;
       buyer = applicant;
       price = amount;
       units = quantity;
       port = p;
       customs = c;
       delivery = d;
   }

   function review() constant returns (uint retval) {
       return uint(prodcode);
   }

   function finall() constant returns (string retval) {
       return string(deliverycheck);
   }    

   function approve() constant returns (string retval) {
       if (msg.sender == port) {
           portcheck = "signed";
       }

       if (msg.sender == customs) {
           if (portcheck == "signed")             
               customscheck = "signed";
           else 
               msg1 = "Port yet to sign";
           return msg1;
       }
   
       if (msg.sender == delivery) {
           if (customscheck == "signed")
               deliverycheck = "signed";
           else            
               msg1 = "Custom yet to sign";
           return msg1;            
       }
   }    
}

與 Java 中一樣,== 運算符不比較兩個字元串的文字。您應該改用StringUtils合約。

if (StringUtils.equal(portcheck,"signed")) {...}

如果您不想載入 StringUtils 契約,我發現也可以簡單地:keccak256(portcheck) == keccak256("signed").

誰能確認這也比評估兩個字元串的每個字元的函式花費更少的氣體?

(很抱歉,如果不贊成使用“已檢查”響應向 Q 添加答案…我只是注意到沒有提到此方法,並認為它可能會有所幫助!)

編輯:剛剛創建了一個快速油耗安全帶,看起來我的懷疑是正確的。keccak256 比較使用的氣體比字元比較少得多。

編輯:最初稱為 sha3,但現在已棄用此函式,取而代之的是 keccak256(sha3 是 keccak256 的別名

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