-
Notifications
You must be signed in to change notification settings - Fork 0
/
swap.js
84 lines (61 loc) · 1.74 KB
/
swap.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
function CreatePool(tokenA, tokenB, amountA, amountB) {
let pool = {
denomA: tokenA,
denomB: tokenB,
amountA: amountA,
amountB: amountB
}
let sent = STD.bank.sendTokens(CONTRACT.address, amountA + tokenA)
if (!sent) {
return false
}
sent = STD.bank.sendTokens(CONTRACT.address, amountB + tokenB)
if (!sent) {
return false
}
let count = STD.read("counter")
if (count) {
count = parseInt(count) + 1
} else {
count = 0
}
STD.write("counter", count)
STD.write(count, JSON.stringify(pool))
return true
}
function Swap(poolId, tokenIn, amountIn) {
let p = STD.read(poolId)
if (p == null || p == undefined) {
return false
}
let pool = JSON.parse(p)
let a = STD.NewDec(pool.amountA)
let b = STD.NewDec(pool.amountB)
let k = a.mul(b)
if (tokenIn == pool.denomA) {
let i = STD.NewDec(amountIn)
let m = k.div(a.add(i)).floor()
let refund = b.sub(m)
let pulled = STD.bank.withdrawTokens(CTX.sender, refund.toInt() + pool.denomB)
if (!pulled) {
return false
}
pool.amountA = a.add(i).toString()
pool.amountB = m.toString()
}
if (tokenIn == pool.denomB) {
let i = STD.NewDec(amountIn)
let m = k.div(b.add(i)).floor()
let refund = a.sub(m)
let pulled = STD.bank.withdrawTokens(CTX.sender, refund.toInt() + pool.denomA)
if (!pulled) {
return false
}
pool.amountB = b.add(i).toString()
pool.amountA = m.toString()
}
STD.write(poolId, JSON.stringify(pool))
return true
}
CONTRACT.functions.swap = Swap
CONTRACT.functions.create = CreatePool