Created
January 19, 2022 05:54
-
-
Save laalaguer/86ea7c292fbad158b48abf0c67e68179 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
class Uniswap: | |
def __init__(self, xs): | |
self.xs = xs | |
self.lastK = sqrt(xs[0] * xs[1]) | |
def swap(self, i, dx): | |
d = self.xs[0] * self.xs[1] | |
y = self.xs[0] if i == 1 else self.xs[1] | |
ny = d / (self.xs[i] + dx * 0.997) | |
self.xs[i] = self.xs[i] + dx | |
dy = y - ny | |
self.xs[0 if i == 1 else 1] = ny | |
return self.xs, dy | |
def getFee(self): | |
K = sqrt(self.xs[0] * self.xs[1]) | |
p = (K - self.lastK) / (K + self.lastK) | |
return [p * self.xs[0], p * self.xs[1]] | |
def collectFee(self): | |
K = sqrt(self.xs[0] * self.xs[1]) | |
p = (K - self.lastK) / (K + self.lastK) | |
self.xs = [x * (1 - p) for x in self.xs] | |
self.lastK = sqrt(self.xs[0] * self.xs[1]) | |
u = Uniswap([40, 80]) | |
print(u.swap(1, 1)) | |
print(u.getFee()) | |
u.collectFee() | |
print(u.getFee()) | |
print(u.swap(1, 0.8)) | |
print(u.getFee()) | |
u.collectFee() | |
print() | |
u = Uniswap([40, 60]) | |
print(u.swap(0, 1)) | |
print(u.getFee()) | |
u.collectFee() | |
print(u.swap(0, 0.2)) | |
print(u.getFee()) | |
u.collectFee() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment