Solidity

如何在幣安智能鏈上使用 msg.value 計算 Jager?

  • November 1, 2021

這裡非常快速且可能很簡單的問題。我正在嘗試編寫一個接受 BNB 並將一些代幣返回給發件人的眾籌合約。我的交易一直失敗,因為它說發送的 BNB 大於我的最大購買上限 100 BNB。我已經發送越來越少量的 BNB 無濟於事,它們都被 require 語句恢復:require(_jagerAmount <= purchaseCap)。搜尋後,我現在知道 msg.sender 採用 18 位小數,因為它是為乙太幣而不是 BNB 設置的。我的問題是,如何正確設置這些函式以獲取 BNB 以及如何計算 msg.value 齲齒的 18 位小數?

uint256 purchaseCap = (100 * 10**8);

// Receive function to recieve BNB.
receive() external payable {
   buyTokens(msg.sender);
}


function buyTokens(address _beneficiary) public payable {
   uint256 jagerAmount = msg.value;
   _validatePurchase(_beneficiary, jagerAmount);
   _processPurchase(_beneficiary, jagerAmount);
   _transferBNB(payable(msg.sender), msg.value);
}


// Validation of an incoming purchase. Uses require statements to revert state when conditions are not met.
function _validatePurchase(address _beneficiary, uint256 _jagerAmount) internal view {
   require(block.timestamp &gt;= startTime && block.timestamp &lt;= endTime, "Crowdsale: current time is either before or after Crowdsale period.");
   require(_hasClosed == false, "Crowdsale: sale is no longer open");
   require(_beneficiary != address(0), "Crowdsale: beneficiary can not be Zero Address.");
   require(_jagerAmount != 0, "Crowdsale: amount of BNB must be greater than 0.");
   require(_jagerAmount &lt;= purchaseCap, "Crowdsale: amount of BNB sent must lower than 100");
   require((balances[_beneficiary] + _jagerAmount) &lt;= purchaseCap, "Crowdsale: amount of BNB entered exceeds buyers purchase cap.");
}

對於那些以後可能會偶然發現並有相同問題的人來說,答案相當簡單。

儘管 BNB 只有 8 位小數,但幣安智能鍊是乙太坊的複製,因此出於所有意圖和目的,BNB 應被視為具有 18 位小數(如乙太坊)。Msg.value 將有 18 位小數,因此在計算眾籌合約內的費率或金額時,乘以或除以 10**18。

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