当前位置:   article > 正文

Uniswap V1——合约源码分析_swap合约代码

swap合约代码

        下面会对Uniswap V1版本的链上合约源码进行解读分析,主要是看Uniswap的各种功能是如何实现的。V1版本使用的不是Solidity而是Vyper语言编写,语言本身不关键,主要看实现逻辑和核心思路。

        Uniswap V1版本比较简单,总共两份链上合约,分别是uniswap_exchange.vy代币兑换合约和uniswap_factory.vy工厂合约,其中兑换合约的功能就是实现基本的代币兑换操作,工厂合约的功能就是产生不同代币的代币兑换合约。

        要看懂代码的操作目的就得明白每个功能的设计思想,因此在看源码前推荐可以先去看Uniswap V1版本的白皮书

1 uniswap_exchange.vy代币兑换合约

        该合约主要实现基本的代币兑换操作,并且维护一个流动性池以保障代币兑换的正常进行,一个代币兑换合约可以看作是专职于该代币兑换的交易所。

1.1 ETH和ERC20代币的相互兑换

        先看用ERC20代币兑换ETH的实现。

  1.  # @notice Convert Tokens to ETH.
  2.  # @dev User specifies exact input and minimum output.
  3.  # @param tokens_sold Amount of Tokens sold. tokens_sold为要支付的代币数量
  4.  # @param min_eth Minimum ETH purchased. min_eth为要购买的ETH的最小值
  5.  # @param deadline Time after which this transaction can no longer be executed.
  6.  # @return Amount of ETH bought. 返回最终购买到的ETH数量
  7.  # 函数功能:指定输入的代币数量,根据代币数量兑换ETH并发送给消息调用者
  8.  @public
  9.  def tokenToEthSwapInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp) -> uint256(wei):
  10.      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender)
  11.  ​
  12.  # @notice Convert Tokens to ETH and transfers ETH to recipient.
  13.  # @dev User specifies exact input and minimum output.
  14.  # @param tokens_sold Amount of Tokens sold.
  15.  # @param min_eth Minimum ETH purchased.
  16.  # @param deadline Time after which this transaction can no longer be executed.
  17.  # @param recipient The address that receives output ETH.
  18.  # @return Amount of ETH bought.
  19.  # 函数功能:指定输入的代币数量,根据代币数量兑换ETH并发送给指定接收者
  20.  # 比tokenToEthSwapInput函数多了一个接收者,指定用来接收所兑换的ETH的地址
  21.  @public
  22.  def tokenToEthTransferInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, recipient: address) -> uint256(wei):
  23.      assert recipient != self and recipient != ZERO_ADDRESS
  24.      return self.tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient)
  25.  ​
  26.  # @notice Convert Tokens to ETH.
  27.  # @dev User specifies maximum input and exact output.
  28.  # @param eth_bought Amount of ETH purchased. #想要购买的ETH的数量
  29.  # @param max_tokens Maximum Tokens sold. #最大能接受的支付的代币数量
  30.  # @param deadline Time after which this transaction can no longer be executed.
  31.  # @return Amount of Tokens sold. #最终消耗的代币数量
  32.  # 函数功能:指定所想要兑换到的ETH数量并将ETH发送给消息调用者,函数根据要兑换的ETH计算扣除代币
  33.  @public
  34.  def tokenToEthSwapOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp) -> uint256:
  35.      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender)
  36.  ​
  37.  # @notice Convert Tokens to ETH and transfers ETH to recipient.
  38.  # @dev User specifies maximum input and exact output.
  39.  # @param eth_bought Amount of ETH purchased.
  40.  # @param max_tokens Maximum Tokens sold.
  41.  # @param deadline Time after which this transaction can no longer be executed.
  42.  # @param recipient The address that receives output ETH.
  43.  # @return Amount of Tokens sold.
  44.  # 函数功能:指定所想要兑换到的ETH数量并将ETH发送给指定接收者,函数根据要兑换的ETH计算扣除代币
  45.  @public
  46.  def tokenToEthTransferOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
  47.      assert recipient != self and recipient != ZERO_ADDRESS
  48.      return self.tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient)

ERC20代币兑换ETH的函数入口

        用ERC20代币兑换ETH的入口有4个,如上所示。上面4个函数按照ETH接收者来划分可以分成Swap和Transfer,Swap代表消息调用者用自己的代币为自己兑换ETH,ETH会发送给消息调用者自身,Transfer表示消息调用者用自己的代币为别人兑换ETH,ETH会被发送给指定recipient;按照兑换数量计算方式来划分可以分成Input和Output,Input是根据自己花费的代币计算能够兑换得到的ETH,Output则是根据自己想要兑换的ETH数量计算自己会花费的代币数量。不同的划分直接体现在入口函数名字上,比如tokenToEthSwapInput函数就代表要用代币兑换ETH,为自己兑换,并且根据自己花费的代币计算我所能得到的ETH。

        tokenToEthSwapInput和tokenToEthTransferInput都调用了函数tokenToEthInput进行ETH的兑换,区别是ETH的接收者不同,tokenToEthSwapOutput和tokenToEthTransferOutput的结构与前两者类似,不同的是输入换成了eth_bought,也就是想要兑换的ETH的目标数量,并且调用的函数是tokenToEthOutput。

        因此接下来我们需要分析tokenToEthInput和tokenToEthOutput。

  1.  @private
  2.  def tokenToEthInput(tokens_sold: uint256, min_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
  3.      #判断输入数据的合理性,且当前时间还没超过限定的时间戳
  4.      assert deadline >= block.timestamp and (tokens_sold > 0 and min_eth > 0)
  5.      #获取当前兑换合约对应代币的储备量
  6.      token_reserve: uint256 = self.token.balanceOf(self)
  7.      #调用getInputPrice函数获取可以兑换到的eth数量(as_unitless_number用于去除wei单位)
  8.      eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
  9.      #调用as_wei_value函数将单位转换成wei
  10.      wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')
  11.      assert wei_bought >= min_eth #兑换的eth不能低于设定最小值
  12.      send(recipient, wei_bought) #调用send函数向recipient转移兑换得到的eth
  13.      #调用代币合约的transferFrom函数从购买者收取应当支付的代币
  14.      assert self.token.transferFrom(buyer, self, tokens_sold)
  15.      log.EthPurchase(buyer, tokens_sold, wei_bought) #日志
  16.      return wei_bought

tokenToEthInput函数实现

        tokenToEthInput通过token.balanceOf获得代币兑换合约当前的代币ERC20代币存储量,然后用getInputPrice获得可兑换到的ETH的数量,接着用as_wei_value将单位转换成wei后用send函数将eth发送给接收者,最后再调用transferForm从buyer手中收取应当支付的代币。

        我们需要关注的点有两个,分别是①token是在哪里被初始化的,②getInputPrice实现。下面看token的初始化。

  1.  # @dev This function acts as a contract constructor which is not currently supported in contracts deployed
  2.  # using create_with_code_of(). It is called once by the factory during contract creation.
  3.  @public
  4.  def setup(token_addr: address):
  5.      # 当没有绑定工厂,则所支持兑换的代币还未绑定,并且传入的address不为0时该函数才能被调用
  6.      assert (self.factory == ZERO_ADDRESS and self.token == ZERO_ADDRESS) and token_addr != ZERO_ADDRESS
  7.      self.factory = msg.sender #记录创建该工厂的
  8.      self.token = token_addr #初始化代币地址
  9.      self.name = 0x556e697377617020563100000000000000000000000000000000000000000000
  10.      self.symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000
  11.      self.decimals = 18

setup函数实现

        self.token是在setup函数中被初始化的,直接将传入参数token_addr赋值给self.token。

  1.  # @dev Pricing function for converting between ETH and Tokens.
  2.  # @param input_amount Amount of ETH or Tokens being sold.
  3.  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
  4.  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
  5.  # @return Amount of ETH or Tokens bought.
  6.  @private
  7.  @constant
  8.  def getInputPrice(input_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
  9.      assert input_reserve > 0 and output_reserve > 0 #需要两币的储备都大于0
  10.      input_amount_with_fee: uint256 = input_amount * 997 #抽取千分之3手续费
  11.      numerator: uint256 = input_amount_with_fee * output_reserve
  12.      denominator: uint256 = (input_reserve * 1000) + input_amount_with_fee
  13.      return numerator / denominator

getInputPrice函数实现

        getInputPrice用于计算最终所兑换出来的币(ETH或代币)的数量,输入为两个币的储备量和用于兑换的币的数量,输出为能够兑换出来的币的数量。计算公式如下:

 

getInputPrice兑换出的数量计算公式(抽取手续费前)

        至于为什么这么算这里不多做解释,可以去看我之前翻译的白皮书。但是由于UniswapV1会收取0.3%的手续费,因此input_amount要乘以0.997最终计算的公式如下:

 

getInputPrice兑换出的数量计算公式(抽取手续费后)

        将上述公式套入ERC20代币兑换ETH的例子里,则公式中的output为所兑换出的ETH的数量,input_amount为所花费的代币数量,input_reserve为代币的储备量,output_amount为ETH的储备量。

        看完tokenToEthInput接着看tokenToEthOutput的实现。

  1.  @private
  2.  def tokenToEthOutput(eth_bought: uint256(wei), max_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
  3.      assert deadline >= block.timestamp and eth_bought > 0
  4.      token_reserve: uint256 = self.token.balanceOf(self) #获取代币储备量
  5.      # 通过getOutputPrice计算所需要花费的代币数量
  6.      tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
  7.      # tokens sold is always > 0
  8.      assert max_tokens >= tokens_sold
  9.      send(recipient, eth_bought) #向接收者发送所兑换得到的ETH
  10.      assert self.token.transferFrom(buyer, self, tokens_sold) #从购买者收取代币
  11.      log.EthPurchase(buyer, tokens_sold, eth_bought)
  12.      return tokens_sold

tokenToEthOutput函数实现

        tokenToEthOutput通过getOutputPrice计算兑换eth_bought数量的ETH所需要花费的代币数量。

  1.  # @dev Pricing function for converting between ETH and Tokens.
  2.  # @param output_amount Amount of ETH or Tokens being bought.
  3.  # @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves.
  4.  # @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves.
  5.  # @return Amount of ETH or Tokens sold.
  6.  @private
  7.  @constant
  8.  def getOutputPrice(output_amount: uint256, input_reserve: uint256, output_reserve: uint256) -> uint256:
  9.      assert input_reserve > 0 and output_reserve > 0
  10.      numerator: uint256 = input_reserve * output_amount * 1000
  11.      denominator: uint256 = (output_reserve - output_amount) * 997
  12.      return numerator / denominator + 1

getOutputPrice函数实现

        与getInputPrice函数一样,计算的过程中需要收取0.3%手续费,因此计算公式如下:

 

getOutputPrice兑换出的数量计算公式(抽取手续费后)

        看完公式再对比代码实现之后我们会发现getOutputPrice函数在计算完价格之后最后还加了个1,这是因为uint256的除法会产生浮点数,向下取整后小数会被舍去,因此兑换者实际需要支付的代币数量会比理论上少一点。为了避免每次交易后交易所产生亏损(会导致流动性池内资金越来越少),因此在最后的计算结果手动加1向上取整,不过因为结算单位是wei,所以向上取整给用户带来的损失可以忽略不计。

        接着看ETH兑换ERC20代币的实现,由于实现方式和ERC20代币兑换ETH一致,因此特殊的地方会在代码的注释里说明,不再过多介绍。

  1.  # @notice Convert ETH to Tokens.
  2.  # @dev User specifies exact input (msg.value).
  3.  # @dev User cannot specify minimum output or deadline.
  4.  # 用ETH兑换代币的默认函数,用户只需要指定输入的ETH的数量
  5.  @public
  6.  @payable
  7.  def __default__():
  8.      self.ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender)
  9.  ​
  10.  # @notice Convert ETH to Tokens.
  11.  # @dev User specifies exact input (msg.value) and minimum output.所以接收的代币最小值
  12.  # @param min_tokens Minimum Tokens bought.
  13.  # @param deadline Time after which this transaction can no longer be executed.
  14.  # @return Amount of Tokens bought.
  15.  # ETH通过msg.value的方式发送给代币合约,代币合约根据所接收到的ETH计算所需支付的代币
  16.  @public
  17.  @payable
  18.  def ethToTokenSwapInput(min_tokens: uint256, deadline: timestamp) -> uint256:
  19.      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender)
  20.  ​
  21.  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
  22.  # @dev User specifies exact input (msg.value) and minimum output
  23.  # @param min_tokens Minimum Tokens bought.
  24.  # @param deadline Time after which this transaction can no longer be executed.
  25.  # @param recipient The address that receives output Tokens.
  26.  # @return Amount of Tokens bought.
  27.  @public
  28.  @payable
  29.  def ethToTokenTransferInput(min_tokens: uint256, deadline: timestamp, recipient: address) -> uint256:
  30.      assert recipient != self and recipient != ZERO_ADDRESS
  31.      return self.ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient)
  32.  ​
  33.  # @notice Convert ETH to Tokens.
  34.  # @dev User specifies maximum input (msg.value) and exact output.
  35.  # @param tokens_bought Amount of tokens bought.
  36.  # @param deadline Time after which this transaction can no longer be executed.
  37.  # @return Amount of ETH sold.
  38.  @public
  39.  @payable
  40.  def ethToTokenSwapOutput(tokens_bought: uint256, deadline: timestamp) -> uint256(wei):
  41.      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender)
  42.  ​
  43.  # @notice Convert ETH to Tokens and transfers Tokens to recipient.
  44.  # @dev User specifies maximum input (msg.value) and exact output.
  45.  # @param tokens_bought Amount of tokens bought.
  46.  # @param deadline Time after which this transaction can no longer be executed.
  47.  # @param recipient The address that receives output Tokens.
  48.  # @return Amount of ETH sold.
  49.  @public
  50.  @payable
  51.  def ethToTokenTransferOutput(tokens_bought: uint256, deadline: timestamp, recipient: address) -> uint256(wei):
  52.      assert recipient != self and recipient != ZERO_ADDRESS
  53.      return self.ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient)
  54.  ​
  55.  @private
  56.  def ethToTokenInput(eth_sold: uint256(wei), min_tokens: uint256, deadline: timestamp, buyer: address, recipient: address) -> uint256:
  57.      assert deadline >= block.timestamp and (eth_sold > 0 and min_tokens > 0)
  58.      token_reserve: uint256 = self.token.balanceOf(self) #获取代币储备量
  59.      #用getInputPrice获得所购买得到的代币数量
  60.      #因为交易是先转账再执行合约,所以获得ETH储备量的时候需要先减去该买者已经发送的ETH
  61.      tokens_bought: uint256 = self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance - eth_sold), token_reserve)
  62.      assert tokens_bought >= min_tokens
  63.      assert self.token.transfer(recipient, tokens_bought)#向接收者发送代币
  64.      log.TokenPurchase(buyer, eth_sold, tokens_bought)
  65.      return tokens_bought
  66.  ​
  67.  @private
  68.  def ethToTokenOutput(tokens_bought: uint256, max_eth: uint256(wei), deadline: timestamp, buyer: address, recipient: address) -> uint256(wei):
  69.      assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth > 0)
  70.      token_reserve: uint256 = self.token.balanceOf(self) #获取代币储备
  71.      #用getOutputPrice获得所需支付的ETH数量
  72.      #因为交易是先转账再执行合约代码,所以调用该合约时ETH已经转到兑换合约中,
  73.      #而入口函数会直接将msg.value作为max_eth传入,所以ETH储备量为self.balance-max_eth
  74.      eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance - max_eth), token_reserve)
  75.      # Throws if eth_sold > max_eth
  76.      # 计算需要退还给用户的ETH
  77.      eth_refund: uint256(wei) = max_eth - as_wei_value(eth_sold, 'wei')
  78.      if eth_refund > 0:
  79.          send(buyer, eth_refund)#如果需要退还的ETH大于0,转账。
  80.      assert self.token.transfer(recipient, tokens_bought)#向用户发送代币
  81.      log.TokenPurchase(buyer, as_wei_value(eth_sold, 'wei'), tokens_bought)
  82.      return as_wei_value(eth_sold, 'wei')

ETH兑换ERC20代币相关函数实现

1.2 ERC20代币和ERC20代币的相互兑换

        Uniswap V1中ERC20代币的相互兑换主要是以ETH为中介进行,也就是说其中一种ERC20代币兑换成ETH,再由ETH兑换成目标ERC20代币

  1.  # @notice Convert Tokens (self.token) to Tokens (token_addr).
  2.  # @dev User specifies exact input and minimum output.
  3.  # @param tokens_sold Amount of Tokens sold.支付的代币数量
  4.  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.购买的代币的最小值
  5.  # @param min_eth_bought Minimum ETH purchased as intermediary.作为中介的ETH的最小值
  6.  # @param deadline Time after which this transaction can no longer be executed.
  7.  # @param token_addr The address of the token being purchased.目标代币的ERC20合约地址
  8.  # @return Amount of Tokens (token_addr) bought.最终购买的代币数量
  9.  # 根据输入的代币数量兑换相应数量的目标代币
  10.  @public
  11.  def tokenToTokenSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
  12.      # 获得目标代币的兑换合约地址
  13.      exchange_addr: address = self.factory.getExchange(token_addr)
  14.      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
  15.  ​
  16.  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
  17.  #         Tokens (token_addr) to recipient.
  18.  # @dev User specifies exact input and minimum output.
  19.  # @param tokens_sold Amount of Tokens sold.支付的代币数量
  20.  # @param min_tokens_bought Minimum Tokens (token_addr) purchased.购买的代币的最小值
  21.  # @param min_eth_bought Minimum ETH purchased as intermediary.作为中介的ETH的最小值
  22.  # @param deadline Time after which this transaction can no longer be executed.
  23.  # @param recipient The address that receives output ETH.目标代币的接收者地址
  24.  # @param token_addr The address of the token being purchased.目标代币的ERC20合约地址
  25.  # @return Amount of Tokens (token_addr) bought.最终购买的代币数量
  26.  # 根据输入的代币数量兑换相应数量的目标代币,并将目标代币发送给指定接收者
  27.  @public
  28.  def tokenToTokenTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
  29.      exchange_addr: address = self.factory.getExchange(token_addr)
  30.      return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
  31.  ​
  32.  # @notice Convert Tokens (self.token) to Tokens (token_addr).
  33.  # @dev User specifies maximum input and exact output.
  34.  # @param tokens_bought Amount of Tokens (token_addr) bought.所要购买的代币数量
  35.  # @param max_tokens_sold Maximum Tokens (self.token) sold. 所要支付的代币的最大值
  36.  # @param max_eth_sold Maximum ETH purchased as intermediary.作为中介的ETH的最大值
  37.  # @param deadline Time after which this transaction can no longer be executed.
  38.  # @param token_addr The address of the token being purchased.目标代币的ERC20合约地址
  39.  # @return Amount of Tokens (self.token) sold.最终所需要支付的代币数量
  40.  # 根据所要购买的目标代币数量支付相应数量的持有代币
  41.  @public
  42.  def tokenToTokenSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, token_addr: address) -> uint256:
  43.      exchange_addr: address = self.factory.getExchange(token_addr)
  44.      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
  45.  ​
  46.  # @notice Convert Tokens (self.token) to Tokens (token_addr) and transfers
  47.  #         Tokens (token_addr) to recipient.
  48.  # @dev User specifies maximum input and exact output.
  49.  # @param tokens_bought Amount of Tokens (token_addr) bought.所要购买的代币数量
  50.  # @param max_tokens_sold Maximum Tokens (self.token) sold.所要支付的代币的最大值
  51.  # @param max_eth_sold Maximum ETH purchased as intermediary.作为中介的ETH的最大值
  52.  # @param deadline Time after which this transaction can no longer be executed.
  53.  # @param recipient The address that receives output ETH.目标代币的接收者地址
  54.  # @param token_addr The address of the token being purchased.目标代币的ERC20合约地址
  55.  # @return Amount of Tokens (self.token) sold.最终所需要支付的代币数量
  56.  # 根据所要购买的目标代币数量支付相应数量的持有代币,并将所兑换的目标代币发送给指定接收者
  57.  @public
  58.  def tokenToTokenTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, token_addr: address) -> uint256:
  59.      exchange_addr: address = self.factory.getExchange(token_addr)
  60.      return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)

ERC20代币兑换ERC20代币的函数入口

        ERC20代币兑换ERC20代币的函数入口和ERC20代币兑换ETH的函数入口类似,不同的是ERC20代币兑换ERC20代币的函数入口在调用进行兑换的业务函数前会先用创建自身的工厂合约实现的getExchange函数来获取目标代币所在的兑换合约地址,然后再向目标兑换合约地址发送兑换请求,将在本合约兑换得到的ETH兑换成目标代币。

        函数入口调用到的函数就两种,分别是根据输入代币计算输出代币的tokenToTokenInput,以及根据输出代币计算输入代币的tokenToTokenOutput。

        下面先看tokenToTokenInput。

  1. @private
  2. def tokenToTokenInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
  3. assert (deadline >= block.timestamp and tokens_sold > 0) and (min_tokens_bought > 0 and min_eth_bought > 0)
  4. assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
  5. token_reserve: uint256 = self.token.balanceOf(self) #获得支付代币的储备量
  6. #用getInputPrice计算所能兑换到的ETH
  7. eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
  8. wei_bought: uint256(wei) = as_wei_value(eth_bought, 'wei')#将单位转换成wei
  9. assert wei_bought >= min_eth_bought
  10. assert self.token.transferFrom(buyer, self, tokens_sold)#收取支付代币
  11. # 调用目标兑换合约地址的ethToTokenTransferInput函数,将ETH兑换成目标代币
  12. tokens_bought: uint256 = Exchange(exchange_addr).ethToTokenTransferInput(min_tokens_bought, deadline, recipient, value=wei_bought)
  13. log.EthPurchase(buyer, tokens_sold, wei_bought)
  14. return tokens_bought

tokenToTokenInput函数实现

        tokenToTokenInput在将支付代币兑换成ETH后,就将ETH发送到目标代币的兑换合约地址并调用其ethToTokenTransferInput函数来将ETH兑换成目标代币。

        接着看tokenToTokenOutput。

  1. @private
  2. def tokenToTokenOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, buyer: address, recipient: address, exchange_addr: address) -> uint256:
  3. assert deadline >= block.timestamp and (tokens_bought > 0 and max_eth_sold > 0)
  4. assert exchange_addr != self and exchange_addr != ZERO_ADDRESS
  5. # 调用目标兑换合约的getEthToTokenOutputPrice来根据目标代币数量计算所需的中介ETH的数量
  6. eth_bought: uint256(wei) = Exchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought)
  7. token_reserve: uint256 = self.token.balanceOf(self)#获得支付代币的储备量
  8. # 根据得到的eth_bought代入getOutputPrice计算所需支付的代币数量
  9. tokens_sold: uint256 = self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))
  10. # tokens sold is always > 0
  11. assert max_tokens_sold >= tokens_sold and max_eth_sold >= eth_bought
  12. assert self.token.transferFrom(buyer, self, tokens_sold)#收取支付代币
  13. # 调用目标兑换合约地址的ethToTokenTransferOutput函数,将ETH兑换成目标代币
  14. eth_sold: uint256(wei) = Exchange(exchange_addr).ethToTokenTransferOutput(tokens_bought, deadline, recipient, value=eth_bought)
  15. log.EthPurchase(buyer, tokens_sold, eth_bought)
  16. return tokens_sold

tokenToTokenOutput函数实现

        tokenToTokenOutput的实现与tokenToEthOutput类似,不同的在于由于支付代币的兑换合约不知道所需兑换到的中介ETH数量是多少,因此需要先调用getEthToTokenOutputPrice来计算兑换出目标数量的目标代币需要多少中介ETH。

  1. # @notice Public price function for ETH to Token trades with an exact output.
  2. # @param tokens_bought Amount of Tokens bought.
  3. # @return Amount of ETH needed to buy output Tokens.
  4. # 根据所需兑换的代币数量计算需要支付的ETH数量
  5. @public
  6. @constant
  7. def getEthToTokenOutputPrice(tokens_bought: uint256) -> uint256(wei):
  8. assert tokens_bought > 0
  9. token_reserve: uint256 = self.token.balanceOf(self) #获取本合约的代币储备量
  10. #计算所需支付的ETH
  11. eth_sold: uint256 = self.getOutputPrice(tokens_bought, as_unitless_number(self.balance), token_reserve)
  12. return as_wei_value(eth_sold, 'wei')

getEthToTokenOutputPrice函数实现

        getEthToTokenOutputPrice函数和ethToTokenSwapOutput相比就是同样都用getOutputPrice获取支付代币的数量,但是getEthToTokenOutputPrice不执行转账操作,因此可以用它来提前获取支付代币数量。

        类似的只计算不转账的功能函数还有3个,如下所示:

  1. # @notice Public price function for ETH to Token trades with an exact input.
  2. # @param eth_sold Amount of ETH sold.
  3. # @return Amount of Tokens that can be bought with input ETH.
  4. # 根据支付的ETH计算可以购买到的代币数量
  5. @public
  6. @constant
  7. def getEthToTokenInputPrice(eth_sold: uint256(wei)) -> uint256:
  8. assert eth_sold > 0
  9. token_reserve: uint256 = self.token.balanceOf(self)
  10. return self.getInputPrice(as_unitless_number(eth_sold), as_unitless_number(self.balance), token_reserve)
  11. # @notice Public price function for Token to ETH trades with an exact input.
  12. # @param tokens_sold Amount of Tokens sold.
  13. # @return Amount of ETH that can be bought with input Tokens.
  14. # 根据支付的代币数量计算可以购买到的ETH数量
  15. @public
  16. @constant
  17. def getTokenToEthInputPrice(tokens_sold: uint256) -> uint256(wei):
  18. assert tokens_sold > 0
  19. token_reserve: uint256 = self.token.balanceOf(self)
  20. eth_bought: uint256 = self.getInputPrice(tokens_sold, token_reserve, as_unitless_number(self.balance))
  21. return as_wei_value(eth_bought, 'wei')
  22. # @notice Public price function for Token to ETH trades with an exact output.
  23. # @param eth_bought Amount of output ETH.
  24. # @return Amount of Tokens needed to buy output ETH.
  25. # 根据所要购买的ETH数量计算所需要支付的代币数量
  26. @public
  27. @constant
  28. def getTokenToEthOutputPrice(eth_bought: uint256(wei)) -> uint256:
  29. assert eth_bought > 0
  30. token_reserve: uint256 = self.token.balanceOf(self)
  31. return self.getOutputPrice(as_unitless_number(eth_bought), token_reserve, as_unitless_number(self.balance))

用于代币或ETH数量计算的辅助功能函数实现

        上面3个函数在兑换合约的其它地方没有被使用到,被用于外部调用。

        1.2开头提到的ERC20代币兑换ERC20代币的4个函数入口仅支持由同一个工厂部署的兑换合约之间进行ERC20代币的兑换,但是Uniswap V1实际上也支持不同工厂部署的代币兑换合约之间进行兑换,入口函数如下:

  1. # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
  2. # @dev Allows trades through contracts that were not deployed from the same factory.
  3. # @dev User specifies exact input and minimum output.
  4. # @param tokens_sold Amount of Tokens sold.
  5. # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
  6. # @param min_eth_bought Minimum ETH purchased as intermediary.
  7. # @param deadline Time after which this transaction can no longer be executed.
  8. # @param exchange_addr The address of the exchange for the token being purchased.
  9. # @return Amount of Tokens (exchange_addr.token) bought.
  10. @public
  11. def tokenToExchangeSwapInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
  12. return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr)
  13. # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
  14. # Tokens (exchange_addr.token) to recipient.
  15. # @dev Allows trades through contracts that were not deployed from the same factory.
  16. # @dev User specifies exact input and minimum output.
  17. # @param tokens_sold Amount of Tokens sold.
  18. # @param min_tokens_bought Minimum Tokens (token_addr) purchased.
  19. # @param min_eth_bought Minimum ETH purchased as intermediary.
  20. # @param deadline Time after which this transaction can no longer be executed.
  21. # @param recipient The address that receives output ETH.
  22. # @param exchange_addr The address of the exchange for the token being purchased.
  23. # @return Amount of Tokens (exchange_addr.token) bought.
  24. @public
  25. def tokenToExchangeTransferInput(tokens_sold: uint256, min_tokens_bought: uint256, min_eth_bought: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
  26. assert recipient != self
  27. return self.tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr)
  28. # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token).
  29. # @dev Allows trades through contracts that were not deployed from the same factory.
  30. # @dev User specifies maximum input and exact output.
  31. # @param tokens_bought Amount of Tokens (token_addr) bought.
  32. # @param max_tokens_sold Maximum Tokens (self.token) sold.
  33. # @param max_eth_sold Maximum ETH purchased as intermediary.
  34. # @param deadline Time after which this transaction can no longer be executed.
  35. # @param exchange_addr The address of the exchange for the token being purchased.
  36. # @return Amount of Tokens (self.token) sold.
  37. @public
  38. def tokenToExchangeSwapOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, exchange_addr: address) -> uint256:
  39. return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr)
  40. # @notice Convert Tokens (self.token) to Tokens (exchange_addr.token) and transfers
  41. # Tokens (exchange_addr.token) to recipient.
  42. # @dev Allows trades through contracts that were not deployed from the same factory.
  43. # @dev User specifies maximum input and exact output.
  44. # @param tokens_bought Amount of Tokens (token_addr) bought.
  45. # @param max_tokens_sold Maximum Tokens (self.token) sold.
  46. # @param max_eth_sold Maximum ETH purchased as intermediary.
  47. # @param deadline Time after which this transaction can no longer be executed.
  48. # @param recipient The address that receives output ETH.
  49. # @param token_addr The address of the token being purchased.
  50. # @return Amount of Tokens (self.token) sold.
  51. @public
  52. def tokenToExchangeTransferOutput(tokens_bought: uint256, max_tokens_sold: uint256, max_eth_sold: uint256(wei), deadline: timestamp, recipient: address, exchange_addr: address) -> uint256:
  53. assert recipient != self
  54. return self.tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr)

跨工厂代币兑换函数入口

        不作过多解释,和1.2开头的函数入口的区别就是不再通过getExchange获得代币兑换合约(因为部署兑换合约的工厂不同,所以无法直接获得),而是直接将别的工厂部署的代币兑换合约地址作为传入参数。

1.3 交易池流动性相关

        Uniswap V1通过向流动性添加者发放流动性代币来记录流动性添加者在该交兑换合约的交易池内所持有的份额,流动性代币也是一种ERC20代币,不同的兑换合约之间的流动性代币不互通。(关于流动性池和流动性代币的相关概念在白皮书里)

  1. #流动性代币名称
  2. name: public(bytes32) # Uniswap V1
  3. #流动性代币符号
  4. symbol: public(bytes32) # UNI-V1
  5. #精度
  6. decimals: public(uint256) # 18
  7. #流动性代币总供应量
  8. totalSupply: public(uint256) # total number of UNI in existence
  9. #余额映射
  10. balances: uint256[address] # UNI balance of an address
  11. #余额使用授权列表
  12. allowances: (uint256[address])[address] # UNI allowance of one address on another
  13. # @dev This function acts as a contract constructor which is not currently supported in contracts deployed
  14. # using create_with_code_of(). It is called once by the factory during contract creation.
  15. @public
  16. def setup(token_addr: address):
  17. assert (self.factory == ZERO_ADDRESS and self.token == ZERO_ADDRESS) and token_addr != ZERO_ADDRESS
  18. self.factory = msg.sender
  19. self.token = token_addr
  20. self.name = 0x556e697377617020563100000000000000000000000000000000000000000000
  21. self.symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000
  22. self.decimals = 18

流动性代币相关定义和初始化

        从上面的实现来看实质上流动性代币就是一种ERC20代币,并且在setup函数中对部分参数进行初始化。

        下面先看看添加流动性的函数实现。

  1. # @notice Deposit ETH and Tokens (self.token) at current ratio to mint UNI tokens.
  2. # @dev min_liquidity does nothing when total UNI supply is 0.
  3. # @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. 用户能接受的最少流动性代币
  4. # @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. 用户想要提供的代币数量最大值。
  5. # @param deadline Time after which this transaction can no longer be executed.
  6. # @return The amount of UNI minted. 所铸造的流动性代币数量
  7. # 根据流动性池中ETH和代币的比例等比例添加两种币,并获得等比例份额的流动性代币
  8. @public
  9. @payable
  10. def addLiquidity(min_liquidity: uint256, max_tokens: uint256, deadline: timestamp) -> uint256:
  11. assert deadline > block.timestamp and (max_tokens > 0 and msg.value > 0)
  12. total_liquidity: uint256 = self.totalSupply #获得流动性代币总供应量
  13. if total_liquidity > 0: #非该池子第一次添加流动性
  14. assert min_liquidity > 0 #添加的流动性最小也要大于0
  15. eth_reserve: uint256(wei) = self.balance - msg.value #获得ETH储备量
  16. token_reserve: uint256 = self.token.balanceOf(self) #获得代币储备量
  17. #根据投入的ETH数量计算需要投入的代币数量
  18. #最后+1是手动向上取整,防止默认的向下取整减少流动性池应收的代币数量,进而逐渐稀释份额
  19. token_amount: uint256 = msg.value * token_reserve / eth_reserve + 1
  20. #计算需要铸造的流动性代币数量
  21. #这里不向上取整是为了保证铸造的流动性代币价值<代币价值以防止流动性代币价值的稀释
  22. liquidity_minted: uint256 = msg.value * total_liquidity / eth_reserve
  23. assert max_tokens >= token_amount and liquidity_minted >= min_liquidity
  24. self.balances[msg.sender] += liquidity_minted#铸造流动性代币并发放给提供者
  25. self.totalSupply = total_liquidity + liquidity_minted#更新流动性代币总供应量
  26. assert self.token.transferFrom(msg.sender, self, token_amount)#收取代币
  27. log.AddLiquidity(msg.sender, msg.value, token_amount)
  28. log.Transfer(ZERO_ADDRESS, msg.sender, liquidity_minted)
  29. return liquidity_minted
  30. else: #该池子第一次添加流动性时
  31. assert (self.factory != ZERO_ADDRESS and self.token != ZERO_ADDRESS) and msg.value >= 1000000000
  32. #检查兑换合约地址和代币地址是否正确且对应
  33. assert self.factory.getExchange(self.token) == self
  34. token_amount: uint256 = max_tokens#直接将用户的代币全部投入池子
  35. #获取当前兑换合约的ETH余额数量,因为第一个人可以自行决定所要投入的代币和ETH,因此拥有定价权
  36. initial_liquidity: uint256 = as_unitless_number(self.balance)
  37. self.totalSupply = initial_liquidity#将ETH余额数量赋予给总供应量
  38. self.balances[msg.sender] = initial_liquidity#为第一个添加流动性的人发放流动性代币
  39. #收取添加的代币
  40. assert self.token.transferFrom(msg.sender, self, token_amount)
  41. log.AddLiquidity(msg.sender, msg.value, token_amount)
  42. log.Transfer(ZERO_ADDRESS, msg.sender, initial_liquidity)
  43. return initial_liquidity

addLiquidity添加流动性

        添加流动性主要分两种情况,第一种情况是该池子第一次添加流动性时,兑换合约会直接铸造与合约ETH余额数量相等的流动性代币并发放给流动性添加者,并且第一次添加流动性时合约不对代币的添加数量做限制,也就意味着第一个流动性添加者有该代币的定价权,但是无法干预后续代币的价格变动。

        第二种情况就是常规的流动性添加,兑换合约根据流动性添加者添加的ETH等比例收取代币,并根据添加的ETH所占比例铸造流动性代币并发放给添加者。

        接着看移除流动性。

  1. # @dev Burn UNI tokens to withdraw ETH and Tokens at current ratio.
  2. # @param amount Amount of UNI burned.要销毁的流动性代币数量
  3. # @param min_eth Minimum ETH withdrawn.提现的ETH最小值
  4. # @param min_tokens Minimum Tokens withdrawn.提现的代币最小值
  5. # @param deadline Time after which this transaction can no longer be executed.
  6. # @return The amount of ETH and Tokens withdrawn.最终体现的ETH和代币最小值
  7. @public
  8. def removeLiquidity(amount: uint256, min_eth: uint256(wei), min_tokens: uint256, deadline: timestamp) -> (uint256(wei), uint256):
  9. assert (amount > 0 and deadline > block.timestamp) and (min_eth > 0 and min_tokens > 0)
  10. total_liquidity: uint256 = self.totalSupply #获取当前流动性代币总供应量
  11. assert total_liquidity > 0 #总供应量要大于0
  12. token_reserve: uint256 = self.token.balanceOf(self) #获取代币储备
  13. #根据移除的流动性占比等比例计算能提现的ETH余额,交易所不亏损所以不向上取整
  14. eth_amount: uint256(wei) = amount * self.balance / total_liquidity
  15. #等比例计算能提现的token余额
  16. token_amount: uint256 = amount * token_reserve / total_liquidity
  17. assert eth_amount >= min_eth and token_amount >= min_tokens #ETH和代币数量要大于预期
  18. self.balances[msg.sender] -= amount #扣除流动性移除者流动性代币
  19. self.totalSupply = total_liquidity - amount #销毁流动性代币
  20. send(msg.sender, eth_amount) #向移除者发送ETH
  21. assert self.token.transfer(msg.sender, token_amount) #向移除者发送代币
  22. log.RemoveLiquidity(msg.sender, eth_amount, token_amount)
  23. log.Transfer(msg.sender, ZERO_ADDRESS, amount)
  24. return eth_amount, token_amount

removeLiquidity添加流动性

        移除流动性的操作也比较简单,等比例计算完之后向移除者转账并销毁流动性代币即可。

1.4 其它函数实现

        代币兑换合约的主要功能就是上面提到的代币兑换和流动性操作,除此之外还有一些其它函数。

  1. # @return Address of Token that is sold on this exchange.
  2. # 获得代币地址
  3. @public
  4. @constant
  5. def tokenAddress() -> address:
  6. return self.token
  7. # @return Address of factory that created this exchange.
  8. # 获得创建自身合约的工厂地址
  9. @public
  10. @constant
  11. def factoryAddress() -> address(Factory):
  12. return self.factory
  13. # ERC20 compatibility for exchange liquidity modified from
  14. # https://github.com/ethereum/vyper/blob/master/examples/tokens/ERC20.vy
  15. # 获取自身的流动性代币余额
  16. @public
  17. @constant
  18. def balanceOf(_owner : address) -> uint256:
  19. return self.balances[_owner]
  20. # 发送流动性代币
  21. @public
  22. def transfer(_to : address, _value : uint256) -> bool:
  23. self.balances[msg.sender] -= _value
  24. self.balances[_to] += _value
  25. log.Transfer(msg.sender, _to, _value)
  26. return True
  27. # 授权进行流动性代币转账
  28. @public
  29. def transferFrom(_from : address, _to : address, _value : uint256) -> bool:
  30. self.balances[_from] -= _value
  31. self.balances[_to] += _value
  32. self.allowances[_from][msg.sender] -= _value
  33. log.Transfer(_from, _to, _value)
  34. return True
  35. # 流动性代币使用授权
  36. @public
  37. def approve(_spender : address, _value : uint256) -> bool:
  38. self.allowances[msg.sender][_spender] = _value
  39. log.Approval(msg.sender, _spender, _value)
  40. return True
  41. # 授权额度
  42. @public
  43. @constant
  44. def allowance(_owner : address, _spender : address) -> uint256:
  45. return self.allowances[_owner][_spender]

兑换合约其它函数实现

        可以看到基本都一些基于流动性代币的标准ERC20代币功能实现。

2 uniswap_factory.vy代币兑换合约

        该合约主要实现兑换合约的部署,或者换句话说该工程主要用来部署不同代币的流动性池,实现如下:

  1. contract Exchange(): #代币兑换合约接口
  2. def setup(token_addr: address): modifying
  3. NewExchange: event({token: indexed(address), exchange: indexed(address)})
  4. exchangeTemplate: public(address) #兑换合约模板地址
  5. tokenCount: public(uint256) #已部署的代币兑换合约数量
  6. token_to_exchange: address[address] #代币地址-兑换合约地址的映射
  7. exchange_to_token: address[address] #代币兑换合约-代币地址的映射
  8. id_to_token: address[uint256] #代币id到代币地址的映射
  9. #初始化兑换合约地址模板,只能运行一次,当合约模板存在时无法再调用
  10. @public
  11. def initializeFactory(template: address):
  12. assert self.exchangeTemplate == ZERO_ADDRESS
  13. assert template != ZERO_ADDRESS
  14. self.exchangeTemplate = template
  15. #创建代币兑换合约,传入代币地址
  16. @public
  17. def createExchange(token: address) -> address:
  18. assert token != ZERO_ADDRESS #代币地址不能是0地址
  19. assert self.exchangeTemplate != ZERO_ADDRESS #合约模板不能为空
  20. assert self.token_to_exchange[token] == ZERO_ADDRESS #该代币需要未创建过兑换合约
  21. exchange: address = create_with_code_of(self.exchangeTemplate) #创建对比兑换合约
  22. Exchange(exchange).setup(token) #初始化代币兑换合约
  23. self.token_to_exchange[token] = exchange #记录代币兑换合约地址
  24. self.exchange_to_token[exchange] = token #记录代币地址
  25. token_id: uint256 = self.tokenCount + 1 #已部署的兑换合约数量+1并作为代币id
  26. self.tokenCount = token_id
  27. self.id_to_token[token_id] = token
  28. log.NewExchange(token, exchange)
  29. return exchange
  30. #根据代币地址找到代币兑换合约地址
  31. @public
  32. @constant
  33. def getExchange(token: address) -> address:
  34. return self.token_to_exchange[token]
  35. #根据兑换合约地址找到代币地址
  36. @public
  37. @constant
  38. def getToken(exchange: address) -> address:
  39. return self.exchange_to_token[exchange]
  40. #根据代币id找到代币地址
  41. @public
  42. @constant
  43. def getTokenWithId(token_id: uint256) -> address:
  44. return self.id_to_token[token_id]

Uniswap V1工厂合约实现

        整个工厂合约的代码实现非常简单,唯一需要提的点就是工厂合约会通过create_with_code_of函数创建新的代币兑换合约。该函数的功能就是根据传入的合约地址找到已经部署上链的合约代码,然后将代码进行拷贝并部署,最后返回新合约的地址。

资料来源

v1-contracts/contracts at master · Uniswap/v1-contracts (github.com)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/641395
推荐阅读
相关标签
  

闽ICP备14008679号