/
market.ts
196 lines (173 loc) · 6.19 KB
/
market.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
import { Contract, Signer, ContractTransactionResponse } from 'ethers';
import { IOHLCV } from 'candlestick-convert';
import { CurrencyInfo, MarketInfo, Skew, Value } from '../types';
import { CurrencySymbol, Direction, OracleType, Timeframe } from '../enums';
import { Currency } from './currency';
import { Oracle } from './oracle';
import { OpenMarketsOracle } from './vendors/oracles/openMarketsOracle';
import { bigIntToValue } from '../utils/bigIntToValue';
import { numberToBigInt } from '../utils/numberToBigInt';
import * as MarketABI from './abi/market.json';
export class Market {
private contract: Contract;
private signer: Signer;
private metadata?: any;
private oracle?: Oracle;
constructor(_contract: Contract, _signer: Signer) {
this.contract = _contract;
this.signer = _signer;
}
static async initialize(_address: string, _signer: Signer): Promise<Market> {
if (__DEV__) {
console.log(`Initialize Market: ${_address}`);
}
const contract = new Contract(_address, MarketABI.abi as any, _signer);
return new Market(contract, _signer);
}
// ---- MARKET INFO ---------------------------------------------------------
public async getInfo(): Promise<MarketInfo> {
const metadata = await this.getMetadata();
const currencyInfo = await this.getCurrencyInfo(metadata.currency);
const info: MarketInfo = {
name: metadata.name,
address: await this.getAddress(),
description: metadata.description,
image: metadata.image,
metric: metadata.metric,
referenceValue: await this.getReferenceValue(currencyInfo),
skew: await this.getSkew(),
};
return info;
}
public async getMetadata(force: boolean = false): Promise<any> {
if (this.metadata && !force) {
return this.metadata;
}
const url = await this.contract.metadataURI();
if (__DEV__) {
console.log(`Market Metadata URL: ${url}`);
}
const response = await fetch(url);
const json = await response.json();
this.metadata = json;
return json;
}
public async getAddress(): Promise<string> {
return await this.contract.getAddress();
}
public async getSkew(): Promise<Skew> {
const positionValues = await this.contract.calculatePositionValues();
const currencyInfo = await this.getCurrencyInfo(CurrencySymbol.USD);
const long: Value = bigIntToValue(positionValues[0], currencyInfo);
const short: Value = bigIntToValue(positionValues[1], currencyInfo);
return {
currency: currencyInfo,
long: long.amount,
short: short.amount,
};
}
// ---- ORACLE --------------------------------------------------------------
public async getReferenceValue(_currencyInfo: CurrencyInfo): Promise<Value> {
return bigIntToValue(await this.contract.getIndexValue(), _currencyInfo);
}
public async getOracle(): Promise<Oracle> {
if (this.oracle) {
return this.oracle;
}
const metadata = await this.getMetadata();
if (metadata.oracle.type !== OracleType.OMO) {
throw new Error('Only OMO oracles are supported');
}
const oracle = await OpenMarketsOracle.initialize(
metadata.oracle,
this.signer
);
this.oracle = oracle;
return oracle;
}
public async getTicks(): Promise<any> {
const oracle = await this.getOracle();
return await oracle.getTicks();
}
public async getOHLCV(_timeframe: Timeframe): Promise<IOHLCV[]> {
const oracle = await this.getOracle();
return await oracle.getOHLCV(_timeframe);
}
// ---- CURRENCY INFO -------------------------------------------------------
public async getCurrencyInfo(
_address: string | CurrencySymbol
): Promise<CurrencyInfo> {
if (_address === 'usd') {
// TODO: Remove this hack when metadata has decimals
return {
name: 'US Dollar',
symbol: CurrencySymbol.USD,
decimals: BigInt(0),
};
} else if (_address === CurrencySymbol.USD) {
return {
name: 'US Dollar',
symbol: CurrencySymbol.USD,
decimals: BigInt(8),
};
}
const currency = await Currency.initialize(_address, this.signer);
return await currency.getInfo();
}
// ---- POSITIONS -----------------------------------------------------------
public async getPositionValue(_positionId: number): Promise<Value> {
const currencyInfo = await this.getCurrencyInfo(CurrencySymbol.USD);
return bigIntToValue(
await this.contract.getPositionValue(_positionId),
currencyInfo
);
}
public async closePosition(
_positionId: number
): Promise<ContractTransactionResponse> {
if (await !this.contract.isPositionEditable(_positionId)) {
throw new Error('Position is not editable.');
}
if (await !this.contract.isPositionLiquidated(_positionId)) {
throw new Error('Position has been liquidated.');
}
const tx = await this.contract.closePosition(_positionId);
return await tx.wait();
}
public async openPosition(
_direction: Direction,
_currency: Currency,
_amount: number
): Promise<ContractTransactionResponse[]> {
const txApproveReceipt = await _currency.approveSpending(
await this.getAddress(),
_amount
);
const currencyInfo = await _currency.getInfo();
const amount = numberToBigInt(_amount, currencyInfo);
const tx = await this.contract.openPosition(
_direction,
currencyInfo.address,
amount
);
const txOpenPositionReceipt = await tx.wait();
return [txApproveReceipt, txOpenPositionReceipt];
}
// public async increasePosition(
// _positionId: number,
// _amount: BigInt
// ): Promise<ContractTransactionResponse> {
// // TODO: Get the currency used to open the position
// // TODO: Account for spending approvals
// if (await !this.contract.isPositionEditable(_positionId)) {
// throw new Error('Position is not editable.');
// }
// const tx = await this.contract.increasePosition(_positionId, _amount);
// return await tx.wait();
// }
// ---- VALUE TRANSFERS -----------------------------------------------------
public async commitValueTransfer(): Promise<ContractTransactionResponse> {
const tx = await this.contract.commitValueTransfer();
return await tx.wait();
}
}