fangmd / blogsource

6 stars 0 forks source link

solidity basic #79

Open fangmd opened 1 year ago

fangmd commented 1 year ago

Fallback function

合约被执行的时候会调用的回调函数

  1. 接收函数

当合约的 send, sendTransaction, transfer 被调用的时候会触发

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;

// This contract keeps all Ether sent to it with no way
// to get it back.
contract Sink {
    event Received(address, uint);
    receive() external payable {
        emit Received(msg.sender, msg.value);
    }
}
fangmd commented 1 year ago

contract 基本操作

  1. 获取合约地址
contract.address
fangmd commented 1 year ago

已经知道源码的情况下,自己的合约调用其他已经部署的合约

pragma solidity ^0.8.0;

import "./4.CoinFlip.sol";

contract AttackCoinFlip {
    CoinFlip public rawCoinFlip;
    uint256 FACTOR =
        57896044618658097711785492504343953926634992332820282019728792003956564819968;

    constructor(address _rawCoinFlipAddress) {
        rawCoinFlip = CoinFlip(_rawCoinFlipAddress);
    }

    function flip() public {
        uint256 blockValue = uint256(blockhash(block.number - 1));

        uint256 coinFlip = blockValue / FACTOR;
        bool side = coinFlip == 1 ? true : false;

        rawCoinFlip.flip(side);
    }
}
fangmd commented 1 year ago

合约全局对象 tx

  1. tx.origin: 交易发起源

Tx Origin Attacks

fangmd commented 1 year ago

delegate

使用代理的方式把其他合约的逻辑使用在自己合约中

fallback() external {
    (bool result,) = address(delegate).delegatecall(msg.data);
    if (result) {
      this;
    }
  }
fangmd commented 1 year ago

web3

  1. 字符串存到 solidity bytes32 格式,数据转换:
web3.utils.toAscii(hexString)
web3.utils.toHex(string)
web3.eth.getStorageAt(contractAddress, position)
fangmd commented 1 year ago

转账

  1. transfer
payable(king).transfer(msg.value); // 给 king 账号转eth
  1. call 低级函数
(bool sent, ) = msg.sender.call{value: balance}(""); // 给 msg.sender 转eth