Solidity
為什麼這行程式碼會阻止智能合約的部署?
我正在編寫一個智能合約,它將集成 ChainLink 的去中心化預言機,但是我遇到了一個問題,阻止我在 Remix IDE 上部署智能合約。問題是我想
price
在另一個尚未編寫的函式中引用,並且我需要price
作為 unsigned integer 全域訪問current_price
。但是如果我想在 Remix 上部署以下智能合約,我會收到錯誤消息“由於異常而導致執行失敗。Reverted’,這uint current_price = uint(getThePrice());
是導致此錯誤的最後一行程式碼。即使我將最後一行簡化為current_price = getThePrice();
我仍然得到同樣的錯誤。這是什麼原因以及如何克服這個問題?pragma solidity ^0.8.4; import "https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; contract Price { receive() external payable { } address payable owner; AggregatorV3Interface internal priceFeed; /** * Network: Kovan * Aggregator: ETH/USD * Address: 0x9326BFA02ADD2366b30bacB125260Af641031331 */ constructor() public payable { priceFeed = AggregatorV3Interface(address(0x9326BFA02ADD2366b30bacB125260Af641031331)); } function getThePrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); return price; } uint current_price = uint(getThePrice()); }
您可以在合約的開頭聲明該變數以及其他全域變數:
current_price
contract Price { address payable owner; AggregatorV3Interface internal priceFeed; uint current_price; ...
然後在建構子中設置:
constructor() public payable { priceFeed = AggregatorV3Interface(address(0x9326BFA02ADD2366b30bacB125260Af641031331)); current_price = uint(getThePrice()); }