-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathflat_functions.ts
More file actions
50 lines (42 loc) · 1.75 KB
/
flat_functions.ts
File metadata and controls
50 lines (42 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const price_num = 1n;
const price_denom = 1n;
let util = function (x: bigint, y : bigint) : bigint[] {
return [(x + y) ** 8n - (x - y) ** 8n, 8n * ((x - y) ** 7n + (x + y) ** 7n)]
}
type NewtonParam = {x : bigint ; y : bigint ; dx : bigint ; dy : bigint ; u : bigint ; n : bigint}
let newton = function (p : NewtonParam) : bigint {
if (p.n == 0n)
return p.dy
else {
let [new_u, new_du_dy] = util(p.x + p.dx, p.y - p.dy);
// new_u - p.u > 0 because dy remains an underestimate
let dy = p.dy + (new_u - p.u) / new_du_dy;
// dy is an underestimate because we start at 0 and the utility curve is convex
p.dy = dy
p.n -= 1n;
return newton(p);
}
}
let tokensBought = function( cashPool : bigint, tokenPool : bigint, cashShold : bigint) : bigint {
let x = cashPool * price_num;
let y = tokenPool * price_denom;
// 4 round is enough for most cases and underestimates the true payoff, so the user
// can always break up a trade for better terms *)
let [u, _] = util(x, y);
var p : NewtonParam = {x : x, y : y, dx : cashShold * price_num, dy : 0n, u : u, n : 5n};
return newton(p) / price_denom
}
let cashBought = function(cashPool : bigint, tokenPool : bigint, tokenSold : bigint) : bigint {
let x = tokenPool * price_denom;
let y = cashPool * price_num;
let [u, _] = util(x, y);
let p : NewtonParam = {x : x, y : y, dx : tokenSold * price_denom, dy : 0n, u : u, n : 5})
return newton(p) / price_num
}
let marginalPrice = function(cashPool : bigint, tokenPool : bigint) {
let x = cashPool * price_num;
let y = tokenPool * price_denom;
let num = (x + y) ** 7n + (x - y) ** 7n;
let den = (x + y) ** 7n - (x - y) ** 7n;
return [num, den]
}