Solidity
如何從 JavaScript 前端設置 Solidity 合約狀態變數的值?
我正在嘗試從前端 javascript 程式碼為以下契約公共狀態變數設置值。但它似乎不起作用。
合約公共狀態變數:
// Current state of the auction. address public highestBidder; uint public highestBid;
在下面的 Javascript 程式碼中,我從 UI 中獲取地址和金額的值並分配給最高出價和最高出價。但它似乎不起作用。我該怎麼做呢?
// Submit bid details, triggered by the "Bid" button SimpleAuction.prototype.startAuction = function() { console.log("inside startAuction"); var that = this; console.log("inside startAuction"); // Gets form input values var address = $("#enter-address").val(); var amount = $("#enter-amount").val(); console.log(amount); // Validates address using utility function if (!isValidAddress(address)) { console.log("Invalid address"); return; } that.highestBidder = address; // Validate amount using utility function if (!isValidAmount(amount)) { console.log("Invalid amount"); return; } that.highestBid = amount;
這段程式碼解決了這個問題。在 JS 的 bid() 函式中將地址和金額作為交易對像傳遞
// Submit bid details, triggered by the "Bid" button SimpleAuction.prototype.startAuction = function() { console.log("inside startAuction"); var that = this; console.log("inside startAuction"); // Gets form input values var address = $("#enter-address").val(); var amount = $("#enter-amount").val(); console.log(amount); // Validates address using utility function if (!isValidAddress(address)) { console.log("Invalid address"); return; } // Validate amount using utility function if (!isValidAmount(amount)) { console.log("Invalid amount"); return; } // Calls the public `bid` function from the smart contract this.instance.bid( { from: address, value: amount, gas: 100000, gasPrice: 100000, gasLimit: 100000 }, function(error, txHash) { if (error) { console.log(error); } // If success, wait for confirmation of transaction, // then clear form values else { that.waitForReceipt(txHash, function(receipt) { if (receipt.status) { $("#enter-address").val(""); $("#enter-amount").val(""); } else { console.log("error"); } }); } } ); };
您正在嘗試更新契約的狀態,在這種情況下,您必須簽署交易。看看這裡
sendTransaction
的 web3方法。當您查看該方法時,您會注意到參數包含字元串,它是您的智能合約方法的函式 ABI。您可以使用 encodeABI 獲取函式abi。transactionObject``data
然後在您的智能合約中,僅通過以下方式創建變數
address public highestBidder;
並不意味著可以更新此狀態變數。您必須創建一個 setter 方法或將 setter 方法邏輯包含到另一個方法中,例如:function setHighestBidder(address _highestBidder) { highestBidder = _highestBidder; }