-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
412 lines (364 loc) · 11.5 KB
/
index.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import { Decimal } from "decimal.js";
import { Asset, asset_to_number, Sym as Symbol, Sym, asset } from "eos-common";
export type EosAccount = string;
export interface TokenSymbol {
contract: EosAccount;
symbol: Symbol;
}
export interface BaseRelay {
contract: EosAccount;
smartToken: TokenSymbol;
isMultiContract: boolean;
}
export interface DryRelay extends BaseRelay {
reserves: TokenSymbol[];
}
export interface v1Relay extends DryRelay {
isMultiContract: false;
}
export interface HydratedRelay extends BaseRelay {
reserves: TokenAmount[];
fee: number;
}
export interface TokenAmount {
contract: EosAccount;
amount: Asset;
}
export interface ConvertPath {
account: string;
symbol: string;
multiContractSymbol?: string;
}
export interface ChoppedRelay {
contract: string;
reserves: TokenSymbol[];
}
export const compareString = (stringOne: string, stringTwo: string) => {
const strings = [stringOne, stringTwo];
if (!strings.every(str => typeof str == "string"))
throw new Error(
`String one: ${stringOne} String two: ${stringTwo} one of them are falsy or not a string`
);
return stringOne.toLowerCase() == stringTwo.toLowerCase();
};
export function calculateReturn(
balanceFrom: Asset,
balanceTo: Asset,
amount: Asset
) {
if (!balanceFrom.symbol.isEqual(amount.symbol))
throw new Error("From symbol does not match amount symbol");
if (amount.amount >= balanceFrom.amount)
throw new Error("Impossible to buy the entire reserve or more");
Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN });
const balanceFromNumber = new Decimal(asset_to_number(balanceFrom));
const balanceToNumber = new Decimal(asset_to_number(balanceTo));
const amountNumber = new Decimal(asset_to_number(amount));
const reward = amountNumber
.div(balanceFromNumber.plus(amountNumber))
.times(balanceToNumber);
const rewardAsset = new Asset(
reward
.times(Math.pow(10, balanceTo.symbol.precision()))
.toDecimalPlaces(0, Decimal.ROUND_DOWN)
.toNumber(),
balanceTo.symbol
);
const slippage = asset_to_number(amount) / asset_to_number(balanceFrom);
return { reward: rewardAsset, slippage };
}
export function calculateCost(
balanceFrom: Asset,
balanceTo: Asset,
amountDesired: Asset
) {
if (!balanceTo.symbol.isEqual(amountDesired.symbol))
throw new Error("From symbol does not match amount symbol");
if (amountDesired.amount >= balanceTo.amount)
throw new Error("Impossible to buy the entire reserve or more");
const balanceFromNumber = new Decimal(asset_to_number(balanceFrom));
const balanceToNumber = new Decimal(asset_to_number(balanceTo));
const amountNumber = new Decimal(asset_to_number(amountDesired));
const oneNumber = new Decimal(1);
Decimal.set({ precision: 15, rounding: Decimal.ROUND_UP });
const reward = balanceFromNumber
.div(oneNumber.minus(amountNumber.div(balanceToNumber)))
.minus(balanceFromNumber);
const rewardAsset = new Asset(
reward
.times(Math.pow(10, balanceFrom.symbol.precision()))
.toDecimalPlaces(0, Decimal.ROUND_FLOOR)
.toNumber(),
balanceFrom.symbol
);
const slippage = asset_to_number(amountDesired) / asset_to_number(balanceTo);
return { reward: rewardAsset, slippage };
}
export function concatAffiliate(
memo: string,
affiliateAccount: string,
percentNumber: number | string
) {
return memo.concat(`,${affiliateAccount},${percentNumber}`);
}
export function composeMemo(
converters: ConvertPath[],
minReturn: string,
destAccount: string,
version = 1,
feeAccount?: string,
feePercent?: number
): string {
const receiver = converters
.map(({ account, symbol, multiContractSymbol }) => {
return `${account}${
multiContractSymbol ? `:${multiContractSymbol}` : ""
} ${symbol}`;
})
.join(" ");
const base = `${version},${receiver},${minReturn},${destAccount}`;
if (feeAccount && feePercent) {
return concatAffiliate(base, feeAccount, feePercent);
}
return base;
}
export function relaysToConvertPaths(
from: Symbol,
relays: DryRelay[]
): ConvertPath[] {
return relays
.map(relay =>
relay.reserves.map(token => {
const base = {
account: relay.contract,
symbol: token.symbol.code().to_string()
};
return relay.isMultiContract
? {
...base,
multiContractSymbol: relay.smartToken.symbol.code().to_string()
}
: base;
})
)
.reduce((prev, curr) => prev.concat(curr))
.filter(converter => converter.symbol !== from.code().to_string())
.reduce((accum: ConvertPath[], item: ConvertPath) => {
return accum.find(
(converter: ConvertPath) => converter.symbol == item.symbol
)
? accum
: [...accum, item];
}, []);
}
const tokenToSymbolName = (token: TokenSymbol) =>
token.symbol.code().to_string();
const symbolToSymbolName = (symbol: Sym) => symbol.code().to_string();
export function relayHasBothSymbols(
symbol1: Symbol,
symbol2: Symbol
): (choppedRelay: ChoppedRelay) => boolean {
return function(relay: ChoppedRelay) {
return relay.reserves.every(
token =>
tokenToSymbolName(token) == symbolToSymbolName(symbol1) ||
tokenToSymbolName(token) == symbolToSymbolName(symbol2)
);
};
}
const zip = (arr1: any[], arr2: any[]) => {
if (arr1.length !== arr2.length)
throw new Error("These arrays aren't the same");
return arr1.map((item, index) => [item, arr2[index]]);
};
const reservesAreSame = (one: TokenSymbol, two: TokenSymbol): boolean => {
return one.contract == two.contract && one.symbol == two.symbol;
};
const relaysAreSame = (one: ChoppedRelay, two: ChoppedRelay): boolean => {
const zippedReserves = zip(one.reserves, two.reserves);
const matchingReserves = zippedReserves.every(([reserve, opposingReserve]) =>
reservesAreSame(reserve, opposingReserve)
);
const matchingContract = one.contract == two.contract;
return matchingContract && matchingReserves;
};
export function removeChoppedRelay(
relays: ChoppedRelay[],
departingRelay: ChoppedRelay
): ChoppedRelay[] {
const res = relays.filter(relay => !relaysAreSame(relay, departingRelay));
if (res.length + 1 !== relays.length)
throw new Error("Failed to remove chopped relay");
return res;
}
export const chopRelay = (item: DryRelay): ChoppedRelay[] => {
return [
{
contract: item.contract,
reserves: [item.reserves[0], item.smartToken]
},
{
contract: item.contract,
reserves: [item.reserves[1], item.smartToken]
}
];
};
export const chopRelays = (relays: DryRelay[]) => {
return relays.reduce((accum: ChoppedRelay[], item: DryRelay) => {
const [relay1, relay2] = chopRelay(item);
return [...accum, relay1, relay2];
}, []);
};
export function getOppositeSymbol(relay: ChoppedRelay, symbol: Symbol): Symbol {
const oppositeToken = relay.reserves.find(
token => !token.symbol.isEqual(symbol)
)!!;
return oppositeToken.symbol;
}
function relayOffersSymbols(symbol1: Symbol, symbol2: Symbol) {
return function(relay: DryRelay) {
const inReserves = relay.reserves.every(
token => token.symbol.isEqual(symbol1) || token.symbol.isEqual(symbol2)
);
if (inReserves) return inReserves;
const inReserve = relay.reserves.some(
token => token.symbol.isEqual(symbol1) || token.symbol.isEqual(symbol2)
);
const inSmartToken =
relay.smartToken.symbol.isEqual(symbol1) ||
relay.smartToken.symbol.isEqual(symbol2);
return inReserve && inSmartToken;
};
}
export function unChopRelays(
choppedRelays: ChoppedRelay[],
relays: DryRelay[]
) {
return choppedRelays.reduce(
(accum: DryRelay[], choppedRelay: ChoppedRelay) => {
const relayOfInterest = relayOffersSymbols(
choppedRelay.reserves[0].symbol,
choppedRelay.reserves[1].symbol
);
const alreadyExistingRelay = accum.find(relayOfInterest);
return alreadyExistingRelay
? accum
: [...accum, relays.find(relayOfInterest)!];
},
[]
);
}
export function chargeFee(
asset: Asset,
decimalFee: number,
magnitude: number = 1
): Asset {
Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN });
const assetAmount = new Decimal(asset_to_number(asset));
const one = new Decimal(1);
const totalFee = assetAmount.times(
one.minus(Decimal.pow(one.minus(decimalFee), magnitude))
);
const newAmount = assetAmount.minus(totalFee);
return new Asset(
newAmount
.times(Math.pow(10, asset.symbol.precision()))
.toDecimalPlaces(0, Decimal.ROUND_FLOOR)
.toNumber(),
asset.symbol
);
}
export function addFee(
asset: Asset,
decimalFee: number,
magnitude: number = 1
): Asset {
Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN });
const assetAmount = new Decimal(asset_to_number(asset));
const one = new Decimal(1);
const totalFee = assetAmount.times(
one.minus(Decimal.pow(one.minus(decimalFee), magnitude))
);
const newAmount = assetAmount.plus(totalFee);
return new Asset(
newAmount
.times(Math.pow(10, asset.symbol.precision()))
.toDecimalPlaces(0, Decimal.ROUND_FLOOR)
.toNumber(),
asset.symbol
);
}
const sortReservesByAsset = (asset: Asset, reserves: TokenAmount[]) => {
if (!reserves.some(reserve => reserve.amount.symbol.isEqual(asset.symbol)))
throw new Error("Asset does not exist in these reserves");
return reserves.sort((a, b) =>
a.amount.symbol.isEqual(asset.symbol) ? -1 : 1
);
};
const highestNumber = (number1: number, number2: number) =>
number1 > number2 ? number1 : number2;
export const findReturn = (amount: Asset, relaysPath: HydratedRelay[]) =>
relaysPath.reduce(
({ amount, highestSlippage }, relay) => {
const [fromReserve, toReserve] = sortReservesByAsset(
amount,
relay.reserves
);
const { reward, slippage } = calculateReturn(
fromReserve.amount,
toReserve.amount,
amount
);
return {
amount: chargeFee(reward, relay.fee, 2),
highestSlippage: highestNumber(highestSlippage, slippage)
};
},
{ amount, highestSlippage: 0 }
);
export const findCost = (amount: Asset, relaysPath: HydratedRelay[]) =>
relaysPath.reverse().reduce(
({ amount, highestSlippage }, relay) => {
const [toReserve, fromReserve] = sortReservesByAsset(
amount,
relay.reserves
);
const { reward, slippage } = calculateCost(
fromReserve.amount,
toReserve.amount,
amount
);
return {
amount: addFee(reward, relay.fee, 2),
highestSlippage: highestNumber(highestSlippage, slippage)
};
},
{ amount, highestSlippage: 0 }
);
export function fund(
smartTokens: Asset,
reserveBalance: Asset,
smartSupply: Asset
) {
Decimal.set({ precision: 18, rounding: Decimal.ROUND_HALF_EVEN });
const cost = new Decimal(reserveBalance.amount.toString())
.times(smartTokens.amount.toString())
.div(smartSupply.amount.toString());
const assetAmount = cost.ceil().toNumber();
return asset(assetAmount, reserveBalance.symbol);
}
export function calculateFundReturn(
reserveTokens: Asset,
reserveBalance: Asset,
smartSupply: Asset
) {
Decimal.set({ precision: 18, rounding: Decimal.ROUND_HALF_EVEN });
const one = new Decimal(1);
// y(s+1) + 1 / r
const reward = new Decimal(reserveTokens.amount.toString())
.times(new Decimal(smartSupply.amount.toString()))
.plus(one)
.div(reserveBalance.amount.toString());
const rewardAmount = reward.floor().toNumber();
return asset(rewardAmount, smartSupply.symbol);
}