源代码:https://github.com/ethersphere/swap-swear-and-swindle

Swarm目前只跑在Goerli测试网,核心的合约为ERC20SimpleSwap,源代码在master分支,对于后续功能合约 full Swap, Swear and Swindle相关代码在experimental分支

逻辑简述

目前Swarm的Goerli测试网部署的合约逻辑为
用户通过执行SimpleSwapFactory合约,部署ERC20SimpleSwap合约,并与发行的gBZZ代币交互

用户与Swarm交互

测试用户

0x10210572d6b4924Af7Ef946136295e9b209E1FA0

部署ERC20SimpleSwap合约

用户地址通过执行SimpleSwapFactory合约的deploySimpleSwap方法,完成部署ERC20SimpleSwap合约,通过查看交易的eventlog,部署的Chequebook合约地址为0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212

deploySimpleSwap合约代码

function deploySimpleSwap(address issuer, uint defaultHardDepositTimeoutDuration)
  public returns (address) {
    address contractAddress = address(new ERC20SimpleSwap(issuer, ERC20Address, defaultHardDepositTimeoutDuration));
    deployedContracts[contractAddress] = true;
    emit SimpleSwapDeployed(contractAddress);
    return contractAddress;
  }

deploySimpleSwap执行同时完成了ERC20SimpleSwap的构造初始化

constructor(address _issuer, address _token, uint _defaultHardDepositTimeout) public {
    issuer = _issuer;
    token = ERC20(_token);
    defaultHardDepositTimeout = _defaultHardDepositTimeout;
  }

同时初始化了交互Token gBZZ代币

订金(为支票薄提供资金)

通过执行API进行为支票薄提供资金
http://localhost:1635/chequebook/deposit?amount=1000000000
执行的逻辑为用户地址0x10210572d6b4924af7ef946136295e9b209e1fa0向自己的Chequebook合约地址0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212转对应数量的gBZZ,也可以理解成充值抵押

测试交易

https://goerli.etherscan.io/tx/0x81080bdc2ee4ede8898f003c4b74c9dcabdd6467e443f9ab8669f0c62434aaee

提现

将自己Chequebook合约中的gBZZ体现到用户地址
执行逻辑为执行自己的Chequebook合约地址0x68f7ea9f3fae55e3e55fee0f0761b7df570fd212中的withdraw方法。

合约代码

function withdraw(uint amount) public {
    /* 只有发行人可以做到这一点 */
    require(msg.sender == issuer, "not issuer");
    /* 确保我们不从保证金中提取任何东西 */
    require(amount <= liquidBalance(), "liquidBalance not sufficient");
    require(token.transfer(issuer, amount), "transfer failed");
  }

测试交易

https://goerli.etherscan.io/tx/0x967fabac2da76d868a9f80d8a64baacbe2cb585519388a4494593705ef050421

分析ERC20SimpleSwap合约

// SPDX-License-Identifier: BSD-3-Clause
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";


/**
@title支票簿合同,无豁免
@author The Swarm作者
@notice支票簿合同允许支票簿的发行者将支票发送到无限数量的交易对手。
此外,可以通过hardDeposits保证偿付能力
@dev作为发行人,如果发送的支票的累积价值高于所有存款的累积价值,则不应该发送任何支票
作为受益人,我们应始终考虑支票弹跳的可能性(当未分配hardDeposits时)
*/
contract ERC20SimpleSwap {
  using SafeMath for uint;

  event ChequeCashed(
    address indexed beneficiary,
    address indexed recipient,
    address indexed caller,
    uint totalPayout,
    uint cumulativePayout,
    uint callerPayout
  );
  event ChequeBounced();
  event HardDepositAmountChanged(address indexed beneficiary, uint amount);
  event HardDepositDecreasePrepared(address indexed beneficiary, uint decreaseAmount);
  event HardDepositTimeoutChanged(address indexed beneficiary, uint timeout);
  event Withdraw(uint amount);

  uint public defaultHardDepositTimeout;
  /* 跟踪每个受益人的硬存款(偿付能力的链上保证)的结构*/
  struct HardDeposit {
    uint amount; /* 分配的硬存款金额 */
    uint decreaseAmount; /* 减少量从请求减少时的金额中减去 */
    uint timeout; /* 发行者必须等待超时秒数才能减少hardDeposit,0表示应用defaultHardDepositTimeout */
    uint canBeDecreasedAt; /* 可以减少硬质沉积的时间点 */
  }

  struct EIP712Domain {
    string name;
    string version;
    uint256 chainId;
  }

  bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
    "EIP712Domain(string name,string version,uint256 chainId)"
  );
  bytes32 public constant CHEQUE_TYPEHASH = keccak256(
    "Cheque(address chequebook,address beneficiary,uint256 cumulativePayout)"
  );
  bytes32 public constant CASHOUT_TYPEHASH = keccak256(
    "Cashout(address chequebook,address sender,uint256 requestPayout,address recipient,uint256 callerPayout)"
  );
  bytes32 public constant CUSTOMDECREASETIMEOUT_TYPEHASH = keccak256(
    "CustomDecreaseTimeout(address chequebook,address beneficiary,uint256 decreaseTimeout)"
  );

  // 该合同使用的EIP712域
  function domain() internal pure returns (EIP712Domain memory) {
    uint256 chainId;
    assembly {
      chainId := chainid()
    }
    return EIP712Domain({
      name: "Chequebook",
      version: "1.0",
      chainId: chainId
    });
  }

  // 计算EIP712域分隔符。 这不能恒定,因为它取决于chainId
  function domainSeparator(EIP712Domain memory eip712Domain) internal pure returns (bytes32) {
    return keccak256(abi.encode(
        EIP712DOMAIN_TYPEHASH,
        keccak256(bytes(eip712Domain.name)),
        keccak256(bytes(eip712Domain.version)),
        eip712Domain.chainId
    ));
  }

  // 使用EIP712签名方案恢复签名
  function recoverEIP712(bytes32 hash, bytes memory sig) internal pure returns (address) {
    bytes32 digest = keccak256(abi.encodePacked(
        "\x19\x01",
        domainSeparator(domain()),
        hash
    ));
    return ECDSA.recover(digest, sig);
  }

  /* 此支票簿针对其写支票的令牌 */
  ERC20 public token;
  /* 将每个受益人与已支付给他们的款项相关联 */
  mapping (address => uint) public paidOut;
  /* 支付总额 */
  uint public totalPaidOut;
  /* 将每个受益人与他们的HardDeposit相关联 */
  mapping (address => HardDeposit) public hardDeposits;
  /* 所有硬存款的总和 */
  uint public totalHardDeposit;
  /* 合同的签发人,在施工中 */
  address public issuer;
  /* 指示支票是否在过去退回 */
  bool public bounced;

  /**
  @notice设置颁发者,令牌和defaultHardDepositTimeout。 只能被调用一次。
   @param _issuer此支票簿的支票的发行者(需要作为“将支票簿设置为付款”的参数)。
   _issuer必须是外部拥有的帐户,或者它必须支持调用函数cashCheque
   @param _token此支票簿使用的令牌
   @param _defaultHardDepositTimeout持续时间(以秒为单位),默认情况下将用于减少hardDeposit分配
  */
  function init(address _issuer, address _token, uint _defaultHardDepositTimeout) public {
    require(_issuer != address(0), "invalid issuer");
    require(issuer == address(0), "already initialized");
    issuer = _issuer;
    token = ERC20(_token);
    defaultHardDepositTimeout = _defaultHardDepositTimeout;
  }

  /// @return 支票簿的余额
  function balance() public view returns(uint) {
    return token.balanceOf(address(this));
  }
  /// @return 余额中没有硬存款支付的部分
  function liquidBalance() public view returns(uint) {
    return balance().sub(totalHardDeposit);
  }

  /// @return 余额中可用于特定受益人的部分
  function liquidBalanceFor(address beneficiary) public view returns(uint) {
    return liquidBalance().add(hardDeposits[beneficiary].amount);
  }
  /**
  @dev内部函数负责检查issuerSignature,更新hardDeposit余额并进行转账。
   由CashCheque和CashChequeBeneficary调用
   @param受益人支票分配给的受益人。 受益人必须是外部拥有的帐户
   @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
   @paramcumulativePayout分配给受益人的累计支票数量
   @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  */
  function _cashChequeInternal(
    address beneficiary,
    address recipient,
    uint cumulativePayout,
    uint callerPayout,
    bytes memory issuerSig
  ) internal {
    /* 发行人必须通过作为主叫方或通过签名明确批准累计支付 */
    if (msg.sender != issuer) {
      require(issuer == recoverEIP712(chequeHash(address(this), beneficiary, cumulativePayout), issuerSig),
      "invalid issuer signature");
    }
    /* requestPayout是请求进行付款处理的金额 */
    uint requestPayout = cumulativePayout.sub(paidOut[beneficiary]);
    /* 计算实际支出 */
    uint totalPayout = Math.min(requestPayout, liquidBalanceFor(beneficiary));
    /* 计算硬存款使用量 */
    uint hardDepositUsage = Math.min(totalPayout, hardDeposits[beneficiary].amount);
    require(totalPayout >= callerPayout, "SimpleSwap: cannot pay caller");
    /* 如果有一些使用的硬存款,请更新hardDeposits */
    if (hardDepositUsage != 0) {
      hardDeposits[beneficiary].amount = hardDeposits[beneficiary].amount.sub(hardDepositUsage);

      totalHardDeposit = totalHardDeposit.sub(hardDepositUsage);
    }
    /* 增加存储的payedOut金额以避免双倍支付 */
    paidOut[beneficiary] = paidOut[beneficiary].add(totalPayout);
    totalPaidOut = totalPaidOut.add(totalPayout);

    /* 让全世界知道发行人对未兑现支票的承诺过高 */
    if (requestPayout != totalPayout) {
      bounced = true;
      emit ChequeBounced();
    }

    if (callerPayout != 0) {
    /* 如果指定,则转接到呼叫者 */
      require(token.transfer(msg.sender, callerPayout), "transfer failed");
      /* 进行实际付款 */
      require(token.transfer(recipient, totalPayout.sub(callerPayout)), "transfer failed");
    } else {
      /* 进行实际付款 */
      require(token.transfer(recipient, totalPayout), "transfer failed");
    }

    emit ChequeCashed(beneficiary, recipient, msg.sender, totalPayout, cumulativePayout, callerPayout);
  }
  /**
  @notice兑现非受益人的受益人支票,并通过发送方与发件人奖励这样做
  @dev受益人必须能够生成签名(作为外部拥有的帐户)才能使用此功能
  @param受益人支票分配给的受益人。受益人必须是外部拥有的帐户
  @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
  @paramcumulativePayout分配给受益人的累计支票数量
  @param受益人Sig受益人必须已经明确批准才能由发件人兑现累计付款并发送给callerPayout
  @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  @param callerPayout当受益人还没有以太币时,他可以在callerPayout的帮助下激励其他人兑现支票
  @param issuerSig如果发行人不是发件人,则发行人必须已在累计付款上明确授予受益人
  */
  function cashCheque(
    address beneficiary,
    address recipient,
    uint cumulativePayout,
    bytes memory beneficiarySig,
    uint256 callerPayout,
    bytes memory issuerSig
  ) public {
    require(
      beneficiary == recoverEIP712(
        cashOutHash(
          address(this),
          msg.sender,
          cumulativePayout,
          recipient,
          callerPayout
        ), beneficiarySig
      ), "invalid beneficiary signature");
    _cashChequeInternal(beneficiary, recipient, cumulativePayout, callerPayout, issuerSig);
  }

  /**
  @注意兑现支票作为受益人
   @param接收者会收到累计付款与已付给受益人减去调用者的款项之间的差额
   @param的累计付款要求付款
   @param issuerSig发行者必须已对收款人的累计付款给予明确批准
  */
  function cashChequeBeneficiary(address recipient, uint cumulativePayout, bytes memory issuerSig) public {
    _cashChequeInternal(msg.sender, recipient, cumulativePayout, 0, issuerSig);
  }

  /**
  @注意准备减少硬沉积
   @dev减少hardDeposit必须分两步完成,以使受益人兑现任何未兑现的支票(并利用相关的硬存款)
   @param受益人,应减少其硬存款
   @param reduction存款应减少的金额
  */
  function prepareDecreaseHardDeposit(address beneficiary, uint decreaseAmount) public {
    require(msg.sender == issuer, "SimpleSwap: not issuer");
    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    /* 如果减少的幅度超过存款,则不能减少 */
    require(decreaseAmount <= hardDeposit.amount, "hard deposit not sufficient");
    // 如果从未设置hardDeposit.timeout,则应用defaultHardDepositTimeout
    uint timeout = hardDeposit.timeout == 0 ? defaultHardDepositTimeout : hardDeposit.timeout;
    hardDeposit.canBeDecreasedAt = block.timestamp + timeout;
    hardDeposit.decreaseAmount = decreaseAmount;
    emit HardDepositDecreasePrepared(beneficiary, decreaseAmount);
  }

  /**
  @notice自调用prepareDecreaseHard存款以来等待了必要的时间后,减少了硬存款
  @param受益人,应减少其硬存款
  */
  function decreaseHardDeposit(address beneficiary) public {
    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    require(block.timestamp >= hardDeposit.canBeDecreasedAt && hardDeposit.canBeDecreasedAt != 0, "deposit not yet timed out");
    /* this throws if decreaseAmount > amount */
    //TODO: 如果prepareDecreaseHardDeposit和reducedHardDeposit之间有现金兑现,那么reducingHardDeposit将抛出并且无法减少硬存款。
    hardDeposit.amount = hardDeposit.amount.sub(hardDeposit.decreaseAmount);
    /* 重置canBeDecreasedAt以避免两次减少 */
    hardDeposit.canBeDecreasedAt = 0;
    /* 保持totalDeposit同步 */
    totalHardDeposit = totalHardDeposit.sub(hardDeposit.decreaseAmount);
    emit HardDepositAmountChanged(beneficiary, hardDeposit.amount);
  }

  /**
  @注意增加硬保证金
   @param受益人,应减少其硬存款
   @param金额新的硬存款
  */
  function increaseHardDeposit(address beneficiary, uint amount) public {
    require(msg.sender == issuer, "SimpleSwap: not issuer");
    /* 确保保证金不超过全球余额 */
    require(totalHardDeposit.add(amount) <= balance(), "hard deposit exceeds balance");

    HardDeposit storage hardDeposit = hardDeposits[beneficiary];
    hardDeposit.amount = hardDeposit.amount.add(amount);
    // 我们没有明确设置hardDepositTimout,因为零意味着使用默认的HardDeposit超时
    totalHardDeposit = totalHardDeposit.add(amount);
    /* 禁用任何未决的减少 */
    hardDeposit.canBeDecreasedAt = 0;
    emit HardDepositAmountChanged(beneficiary, hardDeposit.amount);
  }

  /**
 @notice允许为每个受益人设置自定义的hardDepositDecreaseTimeout
   @dev,当必须保证偿付能力的时间长于defaultHardDepositDecreaseTimeout时,这是必需的
   @param收款人的硬存款减少的受益人必须更改超时
   @param hardDepositTimeout受益人新的hardDeposit.timeout
   @param受益人Sig受益人必须通过在新的reduceTimeout上签名来明确批准
  */
  function setCustomHardDepositTimeout(
    address beneficiary,
    uint hardDepositTimeout,
    bytes memory beneficiarySig
  ) public {
    require(msg.sender == issuer, "not issuer");
    require(
      beneficiary == recoverEIP712(customDecreaseTimeoutHash(address(this), beneficiary, hardDepositTimeout), beneficiarySig),
      "invalid beneficiary signature"
    );
    hardDeposits[beneficiary].timeout = hardDepositTimeout;
    emit HardDepositTimeoutChanged(beneficiary, hardDepositTimeout);
  }

  /// @notice提取以太币
   /// @param要提取的金额
   // solhint-disable-next-line no-simple-event-func-name
  function withdraw(uint amount) public {
    /* 只有发行人可以做到这一点 */
    require(msg.sender == issuer, "not issuer");
    /* 确保我们不从保证金中提取任何东西 */
    require(amount <= liquidBalance(), "liquidBalance not sufficient");
    require(token.transfer(issuer, amount), "transfer failed");
  }

  function chequeHash(address chequebook, address beneficiary, uint cumulativePayout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CHEQUE_TYPEHASH,
      chequebook,
      beneficiary,
      cumulativePayout
    ));
  }  

  function cashOutHash(address chequebook, address sender, uint requestPayout, address recipient, uint callerPayout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CASHOUT_TYPEHASH,
      chequebook,
      sender,
      requestPayout,
      recipient,
      callerPayout
    ));
  }

  function customDecreaseTimeoutHash(address chequebook, address beneficiary, uint decreaseTimeout)
  internal pure returns (bytes32) {
    return keccak256(abi.encode(
      CUSTOMDECREASETIMEOUT_TYPEHASH,
      chequebook,
      beneficiary,
      decreaseTimeout
    ));
  }
}

Cash Cheque Beneficiary

https://goerli.etherscan.io/tx/0x6e255bcd2eb2a84d2a80e25368413f805a036d3cea18d43c81e96f0158a3084c