This is the second in a series of blog posts about DeFi. The first post is here.

In the last post, we implemented the buy method of our Automated Market Maker (AMM) like this:

  # Counterparty pays `amount` eth for some tokens
  def buy(amount)
    ether = amount.to_f

    @ether_reserve += ether
    new_token_reserve = @konst / @ether_reserve

    tokens_bought = @token_reserve - new_token_reserve
    @token_reserve = new_token_reserve

    return tokens_bought
  end

Our sell method is the same, but with ether and tokens swapped around:

  # Counterparty sells `amount` tokens for some eth
  def sell(amount)
    tokens_sold = amount.to_f

    @token_reserve += tokens_sold
    new_ether_reserve = @konst / @token_reserve

    ether = @ether_reserve - new_ether_reserve
    @ether_reserve = new_ether_reserve

    return ether
  end

We can refactor this into a single trade method, like this:

  def trade(amount, input_reserve, output_reserve)
    new_input_reserve = input_reserve + amount
    new_output_reserve = @konst / new_input_reserve
    proceeds = output_reserve - new_output_reserve
    return [proceeds, new_input_reserve, new_output_reserve]
  end

So, our buy and sell methods now look like this:

  # Counterparty pays `amount` eth for some tokens
  def buy(amount)
    ether = amount.to_f
    tokens_bought, @ether_reserve, @token_reserve = trade(ether, @ether_reserve, @token_reserve)
    return tokens_bought
  end

  # Counterparty sells `amount` tokens for some eth
  def sell(amount)
    tokens = amount.to_f
    ether, @token_reserve, @ether_reserve = trade(tokens, @token_reserve, @ether_reserve)
    return ether
  end

You can see the full code here.

In the next post, we’ll enable counterparties to trade ether for tokens on our market.

2 thoughts on “Refactoring the Ruby Automated Market Maker

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s