Solidity
getConversionRate() 返回 0
我試圖通過執行以下腳本讓 getConversionRate() 返回 100 的 ETH 值:
from brownie import Donation, config, network, MockV3Aggregator from scripts.helpful_scripts import ( LOCAL_BLOCKCHAIN_ENVIRONMENTS, deploy_mocks, get_account, ) def deploy_donation(): account = get_account() if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENTS: price_feed_address = config["networks"][network.show_active()][ "eth_usd_price_feed_address" ] else: deploy_mocks() price_feed_address = MockV3Aggregator[-1].address donation = Donation.deploy( price_feed_address, {"from": account}, ) print(f"Contract deployed to {donation.address}") get_price = donation.getPrice() print(f"The current price of ETH/USD is {get_price}") get_conversion_rate = donation.getConversionRate(100) print(get_conversion_rate) return donation def main(): deploy_donation()
對於這個智能合約:
// SPDX-LIcense-Identifier: MIT pragma solidity 0.6.6; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; contract Donation { using SafeMathChainlink for uint256; uint256 ethAmount; address payable owner; AggregatorV3Interface public priceFeed; constructor(address _priceFeed) public { priceFeed = AggregatorV3Interface(_priceFeed); owner = msg.sender; } function donate(uint256 _amount) public payable { ethAmount = getConversionRate(_amount); owner.transfer(ethAmount); } function getConversionRate(uint256 rawUSD) public view returns (uint256) { uint256 ethPrice = getPrice(); uint256 ethValue = (rawUSD / ethPrice) * 1000000000000000000; return ethValue; } function getPrice() public view returns (uint256) { (, int256 answer, , , ) = priceFeed.latestRoundData(); return uint256(answer * 10000000000); } }
請問我的腳本有什麼問題,我如何讓它返迴轉換後的值?
在 Solidity 中沒有分數。例如:
1/2
將四捨五入為 0。在您的腳本中,您計算
rawUSD / ethPrice
. 由於rawUSD
只有 100,並且ethPrice
可能更大,因此將其四捨五入為 0。這就是為什麼在 Solidity 中你應該總是先做乘法再除法。
因此,如果您將線路更改為:
uint256 ethValue = rawUSD * 1000000000000000000 / ethPrice;
你應該能夠得到一個結果。
*注意:我沒有檢查十進制計算的正確性,這可能是一個不同的問題。此外,您可以編寫
1e18
或1 ether
代替1000000000000000000
以使其更具可讀性。