carbon-js-sdk 0.2.14-dev.3 → 0.2.14-dev.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,6 @@ export interface RewardScheme {
10
10
  rewardAmountPerSecond: string;
11
11
  startTime?: Date;
12
12
  endTime?: Date;
13
- rewardReserveAmount: string;
14
13
  rewardPerShareLastUpdatedAt?: Date;
15
14
  rewardPerShare: string;
16
15
  }
@@ -21,7 +20,6 @@ export interface CreateRewardSchemeParams {
21
20
  rewardAmountPerSecond: string;
22
21
  startTime?: Date;
23
22
  endTime?: Date;
24
- reservesAmount: string;
25
23
  }
26
24
  export interface UpdateRewardSchemeParams {
27
25
  rewardSchemeId: Long;
@@ -17,7 +17,6 @@ const baseRewardScheme = {
17
17
  assetDenom: "",
18
18
  rewardType: "",
19
19
  rewardAmountPerSecond: "",
20
- rewardReserveAmount: "",
21
20
  rewardPerShare: "",
22
21
  };
23
22
  exports.RewardScheme = {
@@ -46,14 +45,11 @@ exports.RewardScheme = {
46
45
  if (message.endTime !== undefined) {
47
46
  timestamp_1.Timestamp.encode(toTimestamp(message.endTime), writer.uint32(66).fork()).ldelim();
48
47
  }
49
- if (message.rewardReserveAmount !== "") {
50
- writer.uint32(74).string(message.rewardReserveAmount);
51
- }
52
48
  if (message.rewardPerShareLastUpdatedAt !== undefined) {
53
- timestamp_1.Timestamp.encode(toTimestamp(message.rewardPerShareLastUpdatedAt), writer.uint32(82).fork()).ldelim();
49
+ timestamp_1.Timestamp.encode(toTimestamp(message.rewardPerShareLastUpdatedAt), writer.uint32(74).fork()).ldelim();
54
50
  }
55
51
  if (message.rewardPerShare !== "") {
56
- writer.uint32(90).string(message.rewardPerShare);
52
+ writer.uint32(82).string(message.rewardPerShare);
57
53
  }
58
54
  return writer;
59
55
  },
@@ -89,12 +85,9 @@ exports.RewardScheme = {
89
85
  message.endTime = fromTimestamp(timestamp_1.Timestamp.decode(reader, reader.uint32()));
90
86
  break;
91
87
  case 9:
92
- message.rewardReserveAmount = reader.string();
93
- break;
94
- case 10:
95
88
  message.rewardPerShareLastUpdatedAt = fromTimestamp(timestamp_1.Timestamp.decode(reader, reader.uint32()));
96
89
  break;
97
- case 11:
90
+ case 10:
98
91
  message.rewardPerShare = reader.string();
99
92
  break;
100
93
  default:
@@ -139,11 +132,6 @@ exports.RewardScheme = {
139
132
  object.endTime !== undefined && object.endTime !== null
140
133
  ? fromJsonTimestamp(object.endTime)
141
134
  : undefined;
142
- message.rewardReserveAmount =
143
- object.rewardReserveAmount !== undefined &&
144
- object.rewardReserveAmount !== null
145
- ? String(object.rewardReserveAmount)
146
- : "";
147
135
  message.rewardPerShareLastUpdatedAt =
148
136
  object.rewardPerShareLastUpdatedAt !== undefined &&
149
137
  object.rewardPerShareLastUpdatedAt !== null
@@ -170,8 +158,6 @@ exports.RewardScheme = {
170
158
  (obj.startTime = message.startTime.toISOString());
171
159
  message.endTime !== undefined &&
172
160
  (obj.endTime = message.endTime.toISOString());
173
- message.rewardReserveAmount !== undefined &&
174
- (obj.rewardReserveAmount = message.rewardReserveAmount);
175
161
  message.rewardPerShareLastUpdatedAt !== undefined &&
176
162
  (obj.rewardPerShareLastUpdatedAt =
177
163
  message.rewardPerShareLastUpdatedAt.toISOString());
@@ -180,7 +166,7 @@ exports.RewardScheme = {
180
166
  return obj;
181
167
  },
182
168
  fromPartial(object) {
183
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
169
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
184
170
  const message = Object.assign({}, baseRewardScheme);
185
171
  message.id =
186
172
  object.id !== undefined && object.id !== null
@@ -193,10 +179,9 @@ exports.RewardScheme = {
193
179
  message.rewardAmountPerSecond = (_e = object.rewardAmountPerSecond) !== null && _e !== void 0 ? _e : "";
194
180
  message.startTime = (_f = object.startTime) !== null && _f !== void 0 ? _f : undefined;
195
181
  message.endTime = (_g = object.endTime) !== null && _g !== void 0 ? _g : undefined;
196
- message.rewardReserveAmount = (_h = object.rewardReserveAmount) !== null && _h !== void 0 ? _h : "";
197
182
  message.rewardPerShareLastUpdatedAt =
198
- (_j = object.rewardPerShareLastUpdatedAt) !== null && _j !== void 0 ? _j : undefined;
199
- message.rewardPerShare = (_k = object.rewardPerShare) !== null && _k !== void 0 ? _k : "";
183
+ (_h = object.rewardPerShareLastUpdatedAt) !== null && _h !== void 0 ? _h : undefined;
184
+ message.rewardPerShare = (_j = object.rewardPerShare) !== null && _j !== void 0 ? _j : "";
200
185
  return message;
201
186
  },
202
187
  };
@@ -205,7 +190,6 @@ const baseCreateRewardSchemeParams = {
205
190
  assetDenom: "",
206
191
  rewardType: "",
207
192
  rewardAmountPerSecond: "",
208
- reservesAmount: "",
209
193
  };
210
194
  exports.CreateRewardSchemeParams = {
211
195
  encode(message, writer = minimal_1.default.Writer.create()) {
@@ -227,9 +211,6 @@ exports.CreateRewardSchemeParams = {
227
211
  if (message.endTime !== undefined) {
228
212
  timestamp_1.Timestamp.encode(toTimestamp(message.endTime), writer.uint32(50).fork()).ldelim();
229
213
  }
230
- if (message.reservesAmount !== "") {
231
- writer.uint32(58).string(message.reservesAmount);
232
- }
233
214
  return writer;
234
215
  },
235
216
  decode(input, length) {
@@ -257,9 +238,6 @@ exports.CreateRewardSchemeParams = {
257
238
  case 6:
258
239
  message.endTime = fromTimestamp(timestamp_1.Timestamp.decode(reader, reader.uint32()));
259
240
  break;
260
- case 7:
261
- message.reservesAmount = reader.string();
262
- break;
263
241
  default:
264
242
  reader.skipType(tag & 7);
265
243
  break;
@@ -294,10 +272,6 @@ exports.CreateRewardSchemeParams = {
294
272
  object.endTime !== undefined && object.endTime !== null
295
273
  ? fromJsonTimestamp(object.endTime)
296
274
  : undefined;
297
- message.reservesAmount =
298
- object.reservesAmount !== undefined && object.reservesAmount !== null
299
- ? String(object.reservesAmount)
300
- : "";
301
275
  return message;
302
276
  },
303
277
  toJSON(message) {
@@ -312,12 +286,10 @@ exports.CreateRewardSchemeParams = {
312
286
  (obj.startTime = message.startTime.toISOString());
313
287
  message.endTime !== undefined &&
314
288
  (obj.endTime = message.endTime.toISOString());
315
- message.reservesAmount !== undefined &&
316
- (obj.reservesAmount = message.reservesAmount);
317
289
  return obj;
318
290
  },
319
291
  fromPartial(object) {
320
- var _a, _b, _c, _d, _e, _f, _g;
292
+ var _a, _b, _c, _d, _e, _f;
321
293
  const message = Object.assign({}, baseCreateRewardSchemeParams);
322
294
  message.rewardDenom = (_a = object.rewardDenom) !== null && _a !== void 0 ? _a : "";
323
295
  message.assetDenom = (_b = object.assetDenom) !== null && _b !== void 0 ? _b : "";
@@ -325,7 +297,6 @@ exports.CreateRewardSchemeParams = {
325
297
  message.rewardAmountPerSecond = (_d = object.rewardAmountPerSecond) !== null && _d !== void 0 ? _d : "";
326
298
  message.startTime = (_e = object.startTime) !== null && _e !== void 0 ? _e : undefined;
327
299
  message.endTime = (_f = object.endTime) !== null && _f !== void 0 ? _f : undefined;
328
- message.reservesAmount = (_g = object.reservesAmount) !== null && _g !== void 0 ? _g : "";
329
300
  return message;
330
301
  },
331
302
  };
@@ -0,0 +1,22 @@
1
+ import Long from "long";
2
+ import _m0 from "protobufjs/minimal";
3
+ import { Duration } from "../google/protobuf/duration";
4
+ export declare const protobufPackage = "Switcheo.carbon.pricing";
5
+ /** Legacy Params from v.2.13.0. */
6
+ export interface ParamsV2130 {
7
+ smoothenBand: number;
8
+ impactBand: number;
9
+ staleIndexAllowance?: Duration;
10
+ }
11
+ export declare const ParamsV2130: {
12
+ encode(message: ParamsV2130, writer?: _m0.Writer): _m0.Writer;
13
+ decode(input: _m0.Reader | Uint8Array, length?: number | undefined): ParamsV2130;
14
+ fromJSON(object: any): ParamsV2130;
15
+ toJSON(message: ParamsV2130): unknown;
16
+ fromPartial(object: DeepPartial<ParamsV2130>): ParamsV2130;
17
+ };
18
+ declare type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
19
+ export declare type DeepPartial<T> = T extends Builtin ? T : T extends Long ? string | number | Long : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? {
20
+ [K in keyof T]?: DeepPartial<T[K]>;
21
+ } : Partial<T>;
22
+ export {};
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ParamsV2130 = exports.protobufPackage = void 0;
7
+ /* eslint-disable */
8
+ const long_1 = __importDefault(require("long"));
9
+ const minimal_1 = __importDefault(require("protobufjs/minimal"));
10
+ const duration_1 = require("../google/protobuf/duration");
11
+ exports.protobufPackage = "Switcheo.carbon.pricing";
12
+ const baseParamsV2130 = { smoothenBand: 0, impactBand: 0 };
13
+ exports.ParamsV2130 = {
14
+ encode(message, writer = minimal_1.default.Writer.create()) {
15
+ if (message.smoothenBand !== 0) {
16
+ writer.uint32(8).uint32(message.smoothenBand);
17
+ }
18
+ if (message.impactBand !== 0) {
19
+ writer.uint32(16).uint32(message.impactBand);
20
+ }
21
+ if (message.staleIndexAllowance !== undefined) {
22
+ duration_1.Duration.encode(message.staleIndexAllowance, writer.uint32(26).fork()).ldelim();
23
+ }
24
+ return writer;
25
+ },
26
+ decode(input, length) {
27
+ const reader = input instanceof minimal_1.default.Reader ? input : new minimal_1.default.Reader(input);
28
+ let end = length === undefined ? reader.len : reader.pos + length;
29
+ const message = Object.assign({}, baseParamsV2130);
30
+ while (reader.pos < end) {
31
+ const tag = reader.uint32();
32
+ switch (tag >>> 3) {
33
+ case 1:
34
+ message.smoothenBand = reader.uint32();
35
+ break;
36
+ case 2:
37
+ message.impactBand = reader.uint32();
38
+ break;
39
+ case 3:
40
+ message.staleIndexAllowance = duration_1.Duration.decode(reader, reader.uint32());
41
+ break;
42
+ default:
43
+ reader.skipType(tag & 7);
44
+ break;
45
+ }
46
+ }
47
+ return message;
48
+ },
49
+ fromJSON(object) {
50
+ const message = Object.assign({}, baseParamsV2130);
51
+ message.smoothenBand =
52
+ object.smoothenBand !== undefined && object.smoothenBand !== null
53
+ ? Number(object.smoothenBand)
54
+ : 0;
55
+ message.impactBand =
56
+ object.impactBand !== undefined && object.impactBand !== null
57
+ ? Number(object.impactBand)
58
+ : 0;
59
+ message.staleIndexAllowance =
60
+ object.staleIndexAllowance !== undefined &&
61
+ object.staleIndexAllowance !== null
62
+ ? duration_1.Duration.fromJSON(object.staleIndexAllowance)
63
+ : undefined;
64
+ return message;
65
+ },
66
+ toJSON(message) {
67
+ const obj = {};
68
+ message.smoothenBand !== undefined &&
69
+ (obj.smoothenBand = message.smoothenBand);
70
+ message.impactBand !== undefined && (obj.impactBand = message.impactBand);
71
+ message.staleIndexAllowance !== undefined &&
72
+ (obj.staleIndexAllowance = message.staleIndexAllowance
73
+ ? duration_1.Duration.toJSON(message.staleIndexAllowance)
74
+ : undefined);
75
+ return obj;
76
+ },
77
+ fromPartial(object) {
78
+ var _a, _b;
79
+ const message = Object.assign({}, baseParamsV2130);
80
+ message.smoothenBand = (_a = object.smoothenBand) !== null && _a !== void 0 ? _a : 0;
81
+ message.impactBand = (_b = object.impactBand) !== null && _b !== void 0 ? _b : 0;
82
+ message.staleIndexAllowance =
83
+ object.staleIndexAllowance !== undefined &&
84
+ object.staleIndexAllowance !== null
85
+ ? duration_1.Duration.fromPartial(object.staleIndexAllowance)
86
+ : undefined;
87
+ return message;
88
+ },
89
+ };
90
+ if (minimal_1.default.util.Long !== long_1.default) {
91
+ minimal_1.default.util.Long = long_1.default;
92
+ minimal_1.default.configure();
93
+ }
@@ -256,7 +256,6 @@ export declare namespace AdminModule {
256
256
  rewardAmountPerSecond: BigNumber;
257
257
  startTime?: Date;
258
258
  endTime?: Date;
259
- reservesAmount: BigNumber;
260
259
  }
261
260
  interface UpdateRewardSchemeParams {
262
261
  rewardSchemeId: number;
@@ -354,7 +353,6 @@ export declare function transformCreateRewardScheme(msg: AdminModule.CreateRewar
354
353
  rewardAmountPerSecond: string;
355
354
  startTime: Date | undefined;
356
355
  endTime: Date | undefined;
357
- reservesAmount: string;
358
356
  };
359
357
  export declare function transformUpdateRewardScheme(msg: AdminModule.UpdateRewardSchemeParams): {
360
358
  rewardSchemeId: Long.Long;
@@ -737,7 +737,6 @@ function transformCreateRewardScheme(msg) {
737
737
  rewardAmountPerSecond: msg.rewardAmountPerSecond.toString(10),
738
738
  startTime: msg.startTime,
739
739
  endTime: msg.endTime,
740
- reservesAmount: msg.reservesAmount.toString(10),
741
740
  };
742
741
  }
743
742
  exports.transformCreateRewardScheme = transformCreateRewardScheme;
@@ -5,7 +5,6 @@ import { Debt } from './../codec/cdp/query';
5
5
  import BaseModule from "./base";
6
6
  export declare class CDPModule extends BaseModule {
7
7
  private cdpModuleAddress;
8
- private collateralPoolAddress;
9
8
  supplyAsset(params: CDPModule.SupplyAssetParams, opts?: CarbonTx.SignTxOpts): Promise<import("@cosmjs/stargate").DeliverTxResponse>;
10
9
  withdrawAsset(params: CDPModule.WithdrawAssetParams, opts?: CarbonTx.SignTxOpts): Promise<import("@cosmjs/stargate").DeliverTxResponse>;
11
10
  lockCollateral(params: CDPModule.LockCollateralParams, opts?: CarbonTx.SignTxOpts): Promise<import("@cosmjs/stargate").DeliverTxResponse>;
@@ -31,24 +30,26 @@ export declare class CDPModule extends BaseModule {
31
30
  TotalDebtsUsd: BigNumber;
32
31
  TotalStablecoinDebtsUsd: BigNumber;
33
32
  HealthFactor: BigNumber;
34
- } | undefined>;
35
- getAssetBorrowableSupply(denom: string): Promise<BigNumber | undefined>;
36
- getCdpToActualRatio(cdpDenom: string): Promise<BigNumber | undefined>;
37
- getTotalAccountTokenDebtUsdVal(account: string, denom: string, debt?: Debt, debtInfo?: DebtInfo): Promise<void | BigNumber>;
33
+ }>;
34
+ getAssetBorrowableSupply(denom: string): Promise<BigNumber>;
35
+ getCdpToActualRatio(cdpDenom: string): Promise<BigNumber>;
36
+ getTotalAccountTokenDebtUsdVal(account: string, denom: string, debt?: Debt, debtInfo?: DebtInfo): Promise<BigNumber>;
38
37
  getModuleTotalDebtUsdVal(): Promise<BigNumber | undefined>;
39
- getModuleTotalCollateralUsdVal(): Promise<BigNumber | undefined>;
40
- getCdpTokenUsdVal(cdpDenom: string, amount: BigNumber): Promise<BigNumber | undefined>;
41
- getTokenUsdVal(denom: string, amount: BigNumber): Promise<BigNumber | undefined>;
42
- getTotalTokenDebt(denom: string, debtInfo?: DebtInfo): Promise<BigNumber | undefined>;
43
- getTotalAccountTokenDebt(account: string, denom: string, debt?: Debt, debtInfo?: DebtInfo): Promise<BigNumber | undefined>;
38
+ getModuleTotalCollateralUsdVal(): Promise<BigNumber>;
39
+ getCdpTokenUsdVal(cdpDenom: string, amount: BigNumber): Promise<BigNumber>;
40
+ getTokenUsdVal(denom: string, amount: BigNumber): Promise<BigNumber>;
41
+ getTotalTokenDebt(denom: string, debtInfo?: DebtInfo): Promise<BigNumber>;
42
+ getTotalAccountTokenDebt(account: string, denom: string, debt?: Debt, debtInfo?: DebtInfo): Promise<BigNumber>;
44
43
  getTotalAccountStablecoinDebt(account: string, debt?: CDPModule.StablecoinDebt, debtInfo?: StablecoinDebtInfo): Promise<BigNumber>;
45
- calculateAPY(denom: string, debtInfo?: DebtInfo, assetParams?: AssetParams, rateStrategyParams?: RateStrategyParams): Promise<BigNumber | undefined>;
44
+ calculateAPY(denom: string, debtInfo?: DebtInfo, assetParams?: AssetParams, rateStrategyParams?: RateStrategyParams): Promise<BigNumber>;
46
45
  calculateInterestForTimePeriod(apy: BigNumber, start: Date, end: Date): BigNumber;
47
46
  recalculateCIM(denom: string, debtInfo?: DebtInfo): Promise<BigNumber>;
48
47
  recalculateStablecoinCIM(debtInfo?: StablecoinDebtInfo): Promise<BigNumber>;
49
48
  getMaxCollateralForUnlock(account: string, cdpDenom: string): Promise<BigNumber | undefined>;
50
- getCdpTokenPrice(cdpDenom: string): Promise<BigNumber | undefined>;
51
- getUnderlyingDenom(cdpDenom: string): string | undefined;
49
+ getCdpModuleAddress(): string;
50
+ getCdpTokenPrice(cdpDenom: string): Promise<BigNumber>;
51
+ getUnderlyingDenom(cdpDenom: string): string;
52
+ getCollateralReceivableForLiquidation(debtDenom: string, debtAmount: BigNumber, cdpDenom: string): Promise<BigNumber>;
52
53
  }
53
54
  export declare namespace CDPModule {
54
55
  interface SupplyAssetParams {
@@ -23,12 +23,9 @@ const bignumber_js_1 = require("bignumber.js");
23
23
  const query_3 = require("./../codec/cdp/query");
24
24
  const base_1 = __importDefault(require("./base"));
25
25
  const constant_1 = require("../constant");
26
+ const TokenClient_1 = __importDefault(require("../clients/TokenClient"));
27
+ const address_1 = require("../util/address");
26
28
  class CDPModule extends base_1.default {
27
- constructor() {
28
- super(...arguments);
29
- this.cdpModuleAddress = "";
30
- this.collateralPoolAddress = "";
31
- }
32
29
  supplyAsset(params, opts) {
33
30
  return __awaiter(this, void 0, void 0, function* () {
34
31
  const wallet = this.getWallet();
@@ -322,20 +319,20 @@ class CDPModule extends base_1.default {
322
319
  for (let i = 0; i < collaterals.length; i++) {
323
320
  const amount = (0, number_1.bnOrZero)(collaterals[i].collateralAmount);
324
321
  if (amount.isZero()) {
325
- continue;
322
+ continue; // no collateral for denom
326
323
  }
327
324
  const denom = collaterals[i].denom;
328
325
  const debtInfo = debtInfos.find(d => d.denom === denom);
329
326
  if (!debtInfo) {
330
- return;
327
+ continue; // no debt for denom
331
328
  }
332
329
  const collateralUsdVal = yield this.getCdpTokenUsdVal(collaterals[i].cdpDenom, amount);
333
330
  if (!collateralUsdVal) {
334
- return;
331
+ continue;
335
332
  }
336
333
  const assetParam = assetParams.find(a => a.denom === denom);
337
334
  if (!assetParam) {
338
- return;
335
+ continue;
339
336
  }
340
337
  const ltv = (0, number_1.bnOrZero)(assetParam.loanToValue).div(number_1.BN_10000);
341
338
  const availableBorrowUsd = collateralUsdVal.times(ltv);
@@ -357,25 +354,25 @@ class CDPModule extends base_1.default {
357
354
  }
358
355
  const debtInfo = debtInfos.find(d => d.denom === denom);
359
356
  if (!debtInfo) {
360
- return;
357
+ continue;
361
358
  }
362
359
  const tokenDebtUsdVal = yield this.getTotalAccountTokenDebtUsdVal(account, denom, debts[i], debtInfo);
363
360
  if (!tokenDebtUsdVal) {
364
- return;
361
+ continue;
365
362
  }
366
363
  totalDebtsUsd = totalDebtsUsd.plus(tokenDebtUsdVal);
367
364
  }
368
365
  // add stablecoin debt
369
366
  const debtInfoRsp = yield sdk.query.cdp.StablecoinDebt(query_1.QueryStablecoinDebtRequest.fromPartial({}));
370
367
  const stablecoinDebtInfo = debtInfoRsp.stablecoinDebtInfo;
371
- if (!stablecoinDebtInfo) {
372
- return;
368
+ let stablecoinDebtUsd = number_1.BN_ZERO;
369
+ if (stablecoinDebtInfo) {
370
+ const accountStablecoin = yield sdk.query.cdp.AccountStablecoin({ address: account });
371
+ const stablecoinDecimals = (_a = yield this.sdkProvider.getTokenClient().getDecimals(stablecoinDebtInfo.denom)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
372
+ const stablecoinDebtAmount = (0, number_1.bnOrZero)(accountStablecoin.principalDebt).plus((0, number_1.bnOrZero)(accountStablecoin.interestDebt));
373
+ stablecoinDebtUsd = stablecoinDebtAmount.shiftedBy(-stablecoinDecimals);
374
+ totalDebtsUsd = totalDebtsUsd.plus(stablecoinDebtUsd);
373
375
  }
374
- const accountStablecoin = yield sdk.query.cdp.AccountStablecoin({ address: account });
375
- const stablecoinDecimals = (_a = yield this.sdkProvider.getTokenClient().getDecimals(stablecoinDebtInfo.denom)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
376
- const stablecoinDebtAmount = (0, number_1.bnOrZero)(accountStablecoin.principalDebt).plus((0, number_1.bnOrZero)(accountStablecoin.interestDebt));
377
- const stablecoinDebtUsd = stablecoinDebtAmount.shiftedBy(-stablecoinDecimals);
378
- totalDebtsUsd = totalDebtsUsd.plus(stablecoinDebtUsd);
379
376
  const healthFactor = currLiquidationThreshold.div(totalDebtsUsd);
380
377
  return {
381
378
  TotalCollateralsUsd: totalCollateralsUsd,
@@ -388,58 +385,38 @@ class CDPModule extends base_1.default {
388
385
  });
389
386
  }
390
387
  getAssetBorrowableSupply(denom) {
388
+ var _a;
391
389
  return __awaiter(this, void 0, void 0, function* () {
392
390
  const sdk = this.sdkProvider;
393
- if (!this.cdpModuleAddress) {
394
- const moduleAddressRsp = yield sdk.query.misc.ModuleAddress(codec_1.QueryModuleAddressRequest.fromPartial({ module: "cdp" }));
395
- this.cdpModuleAddress = moduleAddressRsp.address;
396
- }
397
- const balanceRsp = yield sdk.query.bank.Balance(query_2.QueryBalanceRequest.fromPartial({ address: this.cdpModuleAddress, denom }));
398
- if (!balanceRsp.balance) {
399
- return;
400
- }
401
- return (0, number_1.bnOrZero)(balanceRsp.balance.amount);
391
+ const cdpAddress = this.getCdpModuleAddress();
392
+ const balanceRsp = yield sdk.query.bank.Balance(query_2.QueryBalanceRequest.fromPartial({ address: cdpAddress, denom }));
393
+ return (0, number_1.bnOrZero)((_a = balanceRsp.balance) === null || _a === void 0 ? void 0 : _a.amount);
402
394
  });
403
395
  }
404
396
  getCdpToActualRatio(cdpDenom) {
405
397
  return __awaiter(this, void 0, void 0, function* () {
406
398
  const sdk = this.sdkProvider;
407
399
  const denom = this.getUnderlyingDenom(cdpDenom);
408
- if (!denom) {
409
- return;
410
- }
411
400
  const supplyRsp = yield sdk.query.bank.SupplyOf(query_2.QuerySupplyOfRequest.fromPartial({ denom: cdpDenom }));
412
401
  const cdpAmountRsp = supplyRsp.amount;
413
- if (!cdpAmountRsp) {
414
- return;
415
- }
402
+ if (!cdpAmountRsp)
403
+ throw new Error("unable to retrieve cdp token supply");
416
404
  const cdpAmount = (0, number_1.bnOrZero)(cdpAmountRsp.amount);
417
- if (!this.cdpModuleAddress) {
418
- const moduleAddressRsp = yield sdk.query.misc.ModuleAddress(codec_1.QueryModuleAddressRequest.fromPartial({ module: "cdp" }));
419
- this.cdpModuleAddress = moduleAddressRsp.address;
420
- }
421
- const balanceRsp = yield sdk.query.bank.Balance(query_2.QueryBalanceRequest.fromPartial({ address: this.cdpModuleAddress, denom }));
422
- if (!balanceRsp.balance) {
423
- return;
424
- }
425
- let actualAmount = (0, number_1.bnOrZero)(balanceRsp.balance.amount);
405
+ const cdpAddress = this.getCdpModuleAddress();
406
+ const balanceRsp = yield sdk.query.bank.Balance(query_2.QueryBalanceRequest.fromPartial({ address: cdpAddress, denom }));
407
+ if (!balanceRsp.balance)
408
+ throw new Error("unable to retrieve cdp module balance");
426
409
  const owedAmount = yield this.getTotalTokenDebt(denom);
427
- if (!owedAmount) {
428
- return;
429
- }
430
- actualAmount = actualAmount.plus(owedAmount);
431
- const ratio = cdpAmount.div(actualAmount);
432
- return ratio;
410
+ const actualAmount = (0, number_1.bnOrZero)(balanceRsp.balance.amount).plus(owedAmount);
411
+ if (!owedAmount)
412
+ throw new Error("unable to retrieve total token debt");
413
+ return cdpAmount.div(actualAmount);
433
414
  });
434
415
  }
435
416
  getTotalAccountTokenDebtUsdVal(account, denom, debt, debtInfo) {
436
417
  return __awaiter(this, void 0, void 0, function* () {
437
- const amount = yield this.getTotalAccountTokenDebt(account, denom, debt, debtInfo).catch((err) => console.log(err));
438
- if (!amount) {
439
- return;
440
- }
441
- const tokenDebtUsdVal = yield this.getTokenUsdVal(denom, amount).catch((err) => console.log(err));
442
- return tokenDebtUsdVal;
418
+ const amount = yield this.getTotalAccountTokenDebt(account, denom, debt, debtInfo);
419
+ return yield this.getTokenUsdVal(denom, amount);
443
420
  });
444
421
  }
445
422
  getModuleTotalDebtUsdVal() {
@@ -463,29 +440,28 @@ class CDPModule extends base_1.default {
463
440
  }
464
441
  // get stablecoin debt
465
442
  const stablecoinDebtRes = yield this.sdkProvider.query.cdp.StablecoinDebt({});
466
- const stablecoinDebtInfo = stablecoinDebtRes.stablecoinDebtInfo;
467
- if (!stablecoinDebtInfo) {
468
- return;
443
+ if (stablecoinDebtRes.stablecoinDebtInfo) {
444
+ const debtInfo = stablecoinDebtRes.stablecoinDebtInfo;
445
+ const debtAmt = (0, number_1.bnOrZero)(debtInfo.totalPrincipal).plus((0, number_1.bnOrZero)(debtInfo.totalAccumulatedInterest));
446
+ const stablecoinDecimals = (_a = yield sdk.getTokenClient().getDecimals(debtInfo.denom)) !== null && _a !== void 0 ? _a : 0;
447
+ const debtUsdVal = (debtAmt).shiftedBy(-stablecoinDecimals);
448
+ totalDebt = totalDebt.plus(debtUsdVal);
469
449
  }
470
- const debtAmt = (0, number_1.bnOrZero)(stablecoinDebtInfo.totalPrincipal).plus((0, number_1.bnOrZero)(stablecoinDebtInfo.totalAccumulatedInterest));
471
- const stablecoinDecimals = (_a = yield sdk.getTokenClient().getDecimals(stablecoinDebtInfo.denom)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
472
- const debtUsdVal = (debtAmt).shiftedBy(-stablecoinDecimals);
473
- totalDebt = totalDebt.plus(debtUsdVal);
474
450
  return totalDebt;
475
451
  });
476
452
  }
477
453
  getModuleTotalCollateralUsdVal() {
478
454
  return __awaiter(this, void 0, void 0, function* () {
479
- const moduleAddressRsp = yield this.sdkProvider.query.misc.ModuleAddress(codec_1.QueryModuleAddressRequest.fromPartial({ module: "collateral_pool" }));
480
- const cdpBalances = yield this.sdkProvider.query.bank.AllBalances({ address: moduleAddressRsp.address });
481
- let allCollateralsUsdValue = new bignumber_js_1.BigNumber(0);
482
- for (let i = 0; i < cdpBalances.balances.length; i++) {
483
- const denom = cdpBalances.balances[i].denom;
484
- const amount = new bignumber_js_1.BigNumber(cdpBalances.balances[i].amount);
485
- const collateralUsdValue = yield this.getCdpTokenUsdVal(denom, amount);
486
- if (!collateralUsdValue) {
487
- return;
455
+ const network = this.sdkProvider.getConfig().network;
456
+ const collateralPoolAddress = address_1.SWTHAddress.getModuleAddress("collateral_pool", network);
457
+ const cdpBalances = yield this.sdkProvider.query.bank.AllBalances({ address: collateralPoolAddress });
458
+ let allCollateralsUsdValue = number_1.BN_ZERO;
459
+ for (const balance of cdpBalances.balances) {
460
+ if (!TokenClient_1.default.isCdpToken(balance.denom)) {
461
+ continue;
488
462
  }
463
+ const amount = (0, number_1.bnOrZero)(balance.amount);
464
+ const collateralUsdValue = yield this.getCdpTokenUsdVal(balance.denom, amount);
489
465
  allCollateralsUsdValue = allCollateralsUsdValue.plus(collateralUsdValue);
490
466
  }
491
467
  return allCollateralsUsdValue;
@@ -494,13 +470,7 @@ class CDPModule extends base_1.default {
494
470
  getCdpTokenUsdVal(cdpDenom, amount) {
495
471
  return __awaiter(this, void 0, void 0, function* () {
496
472
  const denom = this.getUnderlyingDenom(cdpDenom);
497
- if (!denom) {
498
- return;
499
- }
500
473
  const ratio = yield this.getCdpToActualRatio(cdpDenom);
501
- if (!ratio) {
502
- return;
503
- }
504
474
  const actualTokenAmount = amount.div(ratio);
505
475
  return yield this.getTokenUsdVal(denom, actualTokenAmount);
506
476
  });
@@ -509,39 +479,30 @@ class CDPModule extends base_1.default {
509
479
  return __awaiter(this, void 0, void 0, function* () {
510
480
  const sdk = this.sdkProvider;
511
481
  const decimals = yield this.sdkProvider.getTokenClient().getDecimals(denom);
512
- if (!decimals) {
513
- return;
514
- }
515
- const price = yield sdk.query.pricing.TokenPrice(codec_1.QueryTokenPriceRequest.fromPartial({ denom }));
516
- if (!price.tokenPrice) {
517
- return;
518
- }
519
- const twap = (0, number_1.bnOrZero)(price.tokenPrice.twap).shiftedBy(18 * (-1));
520
- return amount.times(twap).shiftedBy(decimals * (-1));
482
+ if (decimals === undefined)
483
+ throw new Error("unable to retrieve token decimals for " + denom);
484
+ const priceResult = yield sdk.query.pricing.TokenPrice(codec_1.QueryTokenPriceRequest.fromPartial({ denom }));
485
+ if (!priceResult.tokenPrice)
486
+ throw new Error("unable to retrieve token price for " + denom);
487
+ const twap = (0, number_1.bnOrZero)(priceResult.tokenPrice.twap).shiftedBy(-18);
488
+ return amount.times(twap).shiftedBy(-decimals);
521
489
  });
522
490
  }
523
491
  getTotalTokenDebt(denom, debtInfo) {
492
+ var _a;
524
493
  return __awaiter(this, void 0, void 0, function* () {
525
494
  if (!debtInfo) {
526
495
  const debtInfoRsp = yield this.sdkProvider.query.cdp.TokenDebt(query_1.QueryTokenDebtRequest.fromPartial({ denom }));
527
496
  debtInfo = debtInfoRsp.debtInfo;
528
497
  }
529
- if (!debtInfo) {
530
- return;
531
- }
532
- const cim = yield this.recalculateCIM(denom, debtInfo);
533
- if (!cim) {
534
- return;
535
- }
498
+ if (!debtInfo)
499
+ throw new Error("unable to retrieve debt info");
536
500
  const principal = (0, number_1.bnOrZero)(debtInfo.totalPrincipal);
537
- const interest = (0, number_1.bnOrZero)(debtInfo.totalAccumulatedInterest);
501
+ const accumInterest = (0, number_1.bnOrZero)(debtInfo.totalAccumulatedInterest);
538
502
  const cdpParamsRsp = yield this.sdkProvider.query.cdp.Params(query_1.QueryParamsRequest.fromPartial({}));
539
- const cdpParams = cdpParamsRsp.params;
540
- if (!cdpParams) {
541
- return;
542
- }
543
- const interestFee = (0, number_1.bnOrZero)(cdpParams.interestFee).div(10000);
544
- return principal.plus(interest.times((0, number_1.bnOrZero)(1).minus(interestFee)));
503
+ const interestFee = (0, number_1.bnOrZero)((_a = cdpParamsRsp.params) === null || _a === void 0 ? void 0 : _a.interestFee);
504
+ const interest = accumInterest.times(number_1.BN_10000.minus(interestFee)).dividedToIntegerBy(number_1.BN_10000);
505
+ return principal.plus(interest);
545
506
  });
546
507
  }
547
508
  getTotalAccountTokenDebt(account, denom, debt, debtInfo) {
@@ -551,22 +512,19 @@ class CDPModule extends base_1.default {
551
512
  const debtInfoRsp = yield sdk.query.cdp.TokenDebt(query_1.QueryTokenDebtRequest.fromPartial({ denom }));
552
513
  debtInfo = debtInfoRsp.debtInfo;
553
514
  }
554
- if (!debtInfo) {
555
- return;
556
- }
515
+ if (!debtInfo)
516
+ return number_1.BN_ZERO;
557
517
  if (!debt) {
558
518
  const debtRes = yield sdk.query.cdp.AccountDebt({ address: account, denom: denom });
559
519
  debt = debtRes.debt;
560
520
  }
561
- if (!debt) {
562
- return;
563
- }
564
- const principalAmount = (0, number_1.bnOrZero)(debt.principalDebt);
565
- const initialCIM = (0, number_1.bnOrZero)(debt.initialCumulativeInterestMultiplier);
521
+ const principalAmount = (0, number_1.bnOrZero)(debt === null || debt === void 0 ? void 0 : debt.principalDebt);
522
+ const initialCIM = (0, number_1.bnOrZero)(debt === null || debt === void 0 ? void 0 : debt.initialCumulativeInterestMultiplier);
523
+ if (principalAmount.isZero() || initialCIM.isZero())
524
+ return number_1.BN_ZERO;
566
525
  const cim = yield this.recalculateCIM(denom, debtInfo);
567
- if (!cim) {
568
- return;
569
- }
526
+ if (!cim)
527
+ throw new Error("unable to retrieve account debt");
570
528
  // TODO: change to round up
571
529
  const totalAmountTokenDebt = principalAmount.times(cim).dividedToIntegerBy(initialCIM);
572
530
  return totalAmountTokenDebt;
@@ -580,24 +538,18 @@ class CDPModule extends base_1.default {
580
538
  const debtInfoResponse = yield sdk.query.cdp.StablecoinDebt(query_1.QueryStablecoinDebtRequest.fromPartial({}));
581
539
  debtInfo = debtInfoResponse.stablecoinDebtInfo;
582
540
  }
583
- if (!debtInfo) {
541
+ if (!debtInfo)
584
542
  return number_1.BN_ZERO;
585
- }
586
543
  if (!debt) {
587
544
  const debtResp = yield sdk.query.cdp.AccountStablecoin(query_1.QueryAccountStablecoinRequest.fromPartial({ address: account }));
588
545
  debt = debtResp;
589
546
  }
590
- if (!debt) {
591
- return number_1.BN_ZERO;
592
- }
593
547
  principalAmount = (0, number_1.bnOrZero)(debt.principalDebt);
594
548
  const initialCIM = (0, number_1.bnOrZero)(debt.initialCumulativeInterestMultiplier);
595
549
  const cim = yield this.recalculateStablecoinCIM(debtInfo);
596
- if (!cim) {
597
- return number_1.BN_ZERO;
598
- }
599
- const totalStablecoinDebtAmount = principalAmount.times(cim).dividedToIntegerBy(initialCIM);
600
- return totalStablecoinDebtAmount;
550
+ if (!cim)
551
+ throw new Error("unable to retrieve account debt");
552
+ return principalAmount.times(cim).dividedToIntegerBy(initialCIM);
601
553
  });
602
554
  }
603
555
  calculateAPY(denom, debtInfo, assetParams, rateStrategyParams) {
@@ -606,15 +558,14 @@ class CDPModule extends base_1.default {
606
558
  if (!debtInfo) {
607
559
  const debtInfoResponse = yield sdk.query.cdp.TokenDebt(query_1.QueryTokenDebtRequest.fromPartial({ denom }));
608
560
  debtInfo = debtInfoResponse.debtInfo;
609
- if (!debtInfo) {
610
- return;
611
- }
561
+ if (!debtInfo)
562
+ throw new Error("unable to retrieve debt info for " + denom);
612
563
  }
613
564
  if (!assetParams) {
614
565
  const assetResponse = yield sdk.query.cdp.Asset(query_1.QueryAssetRequest.fromPartial({ denom }));
615
566
  assetParams = assetResponse.assetParams;
616
567
  if (!assetParams) {
617
- return;
568
+ throw new Error("unable to retrieve asset param for " + denom);
618
569
  }
619
570
  }
620
571
  if (!rateStrategyParams) {
@@ -623,7 +574,7 @@ class CDPModule extends base_1.default {
623
574
  }));
624
575
  rateStrategyParams = rateStrategyParamsResponse.rateStrategyParams;
625
576
  if (!rateStrategyParams) {
626
- return;
577
+ throw new Error("unable to retrieve rate strategy for " + denom);
627
578
  }
628
579
  }
629
580
  const utilizationRate = (0, number_1.bnOrZero)(debtInfo.utilizationRate).shiftedBy(-18);
@@ -646,8 +597,7 @@ class CDPModule extends base_1.default {
646
597
  }
647
598
  const duration = (0, number_1.bnOrZero)(end.valueOf() - start.valueOf());
648
599
  const millisecondsAYear = (0, number_1.bnOrZero)(31536000000);
649
- const interest = duration.div(millisecondsAYear).times(apy);
650
- return interest;
600
+ return duration.div(millisecondsAYear).times(apy);
651
601
  }
652
602
  recalculateCIM(denom, debtInfo) {
653
603
  var _a;
@@ -693,12 +643,10 @@ class CDPModule extends base_1.default {
693
643
  });
694
644
  }
695
645
  getMaxCollateralForUnlock(account, cdpDenom) {
696
- var _a;
646
+ var _a, _b, _c, _d, _e;
697
647
  return __awaiter(this, void 0, void 0, function* () {
698
648
  const sdk = this.sdkProvider;
699
- const denom = yield this.getUnderlyingDenom(cdpDenom);
700
- if (!denom)
701
- return;
649
+ const denom = this.getUnderlyingDenom(cdpDenom);
702
650
  const assetParams = yield sdk.query.cdp.Asset({ denom: denom });
703
651
  if (!assetParams.assetParams)
704
652
  return;
@@ -707,54 +655,82 @@ class CDPModule extends base_1.default {
707
655
  unlockRatio = new bignumber_js_1.BigNumber(assetParams.assetParams.liquidationThreshold);
708
656
  }
709
657
  const accountData = yield this.getAccountData(account);
710
- if (!accountData)
711
- return;
712
- const tokenDecimals = yield sdk.getTokenClient().getDecimals(denom);
713
- if (!tokenDecimals)
714
- return;
658
+ const tokenDecimals = (_a = yield sdk.getTokenClient().getDecimals(denom)) !== null && _a !== void 0 ? _a : 0;
715
659
  const availableBorrowsUsd = accountData.AvailableBorrowsUsd.minus(accountData.TotalDebtsUsd);
716
- const unlockableUsd = availableBorrowsUsd.multipliedBy(10000).div(unlockRatio);
717
- const tokenPrice = yield sdk.query.pricing.TokenPrice({ denom: denom });
718
- if (!tokenPrice.tokenPrice)
719
- return;
720
- const tokenTwap = new bignumber_js_1.BigNumber(tokenPrice.tokenPrice.twap);
660
+ const unlockableUsd = availableBorrowsUsd.multipliedBy(number_1.BN_10000).div(unlockRatio);
661
+ const tokenPrice = yield sdk.query.pricing.TokenPrice({ denom });
662
+ const tokenTwap = (0, number_1.bnOrZero)((_b = tokenPrice.tokenPrice) === null || _b === void 0 ? void 0 : _b.twap);
663
+ if (tokenTwap.isZero())
664
+ throw new Error("unable to retrieve token price for " + denom);
721
665
  const tokenAmt = unlockableUsd.div(tokenTwap.shiftedBy(-18)).shiftedBy(tokenDecimals);
722
- const cdpToActualRatio = (_a = yield this.getCdpToActualRatio(cdpDenom)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
666
+ const cdpToActualRatio = (_c = yield this.getCdpToActualRatio(cdpDenom)) !== null && _c !== void 0 ? _c : number_1.BN_ZERO;
723
667
  const cdpTokenAmt = tokenAmt.multipliedBy(cdpToActualRatio);
724
668
  // take the min of cdpTokensUnlockableAmt and locked tokens
725
669
  const accountCollateral = yield sdk.query.cdp.AccountCollateral({
726
670
  address: account,
727
671
  cdpDenom: cdpDenom
728
672
  });
729
- if (!accountCollateral.collateral)
730
- return;
731
- const lockedAmount = new bignumber_js_1.BigNumber(accountCollateral.collateral.collateralAmount);
732
- if (lockedAmount.lt(cdpTokenAmt)) {
733
- return lockedAmount;
734
- }
735
- return cdpTokenAmt;
673
+ const lockedAmount = (0, number_1.bnOrZero)((_e = (_d = accountCollateral.collateral) === null || _d === void 0 ? void 0 : _d.collateralAmount) !== null && _e !== void 0 ? _e : "0");
674
+ return lockedAmount.lt(cdpTokenAmt) ? lockedAmount : cdpTokenAmt;
736
675
  });
737
676
  }
677
+ getCdpModuleAddress() {
678
+ if (!this.cdpModuleAddress) {
679
+ const network = this.sdkProvider.getConfig().network;
680
+ this.cdpModuleAddress = address_1.SWTHAddress.getModuleAddress("cdp", network);
681
+ }
682
+ return this.cdpModuleAddress;
683
+ }
738
684
  getCdpTokenPrice(cdpDenom) {
739
- var _a;
685
+ var _a, _b;
740
686
  return __awaiter(this, void 0, void 0, function* () {
741
687
  const sdk = this.sdkProvider;
742
- const denom = yield this.getUnderlyingDenom(cdpDenom);
743
- if (!denom) {
744
- return;
745
- }
688
+ const denom = this.getUnderlyingDenom(cdpDenom);
746
689
  const cdpToActualRatio = (_a = yield this.getCdpToActualRatio(cdpDenom)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
747
690
  const tokenPrice = yield sdk.query.pricing.TokenPrice({ denom: denom });
748
- if (!tokenPrice.tokenPrice) {
749
- return;
750
- }
751
- const tokenTwap = new bignumber_js_1.BigNumber(tokenPrice.tokenPrice.twap);
752
- return tokenTwap.multipliedBy(cdpToActualRatio).shiftedBy(-18);
691
+ const tokenTwap = (0, number_1.bnOrZero)((_b = tokenPrice.tokenPrice) === null || _b === void 0 ? void 0 : _b.twap).shiftedBy(-18);
692
+ return tokenTwap.multipliedBy(cdpToActualRatio);
753
693
  });
754
694
  }
755
695
  getUnderlyingDenom(cdpDenom) {
756
696
  var _a;
757
- return (_a = this.sdkProvider.getTokenClient().getCdpUnderlyingToken(cdpDenom)) === null || _a === void 0 ? void 0 : _a.denom;
697
+ const denom = (_a = this.sdkProvider.getTokenClient().getCdpUnderlyingToken(cdpDenom)) === null || _a === void 0 ? void 0 : _a.denom;
698
+ if (!denom)
699
+ throw new Error("underlying denom not found for " + cdpDenom);
700
+ return denom;
701
+ }
702
+ // given a debt repayment amount, we get the max collateral that a liquidator can receive
703
+ // this takes into account the liquidation bonus and fees that will be deducted from his profit
704
+ getCollateralReceivableForLiquidation(debtDenom, debtAmount, cdpDenom) {
705
+ var _a, _b;
706
+ return __awaiter(this, void 0, void 0, function* () {
707
+ const sdk = this.sdkProvider;
708
+ // get the discounted price for the cdp token
709
+ const asset = yield sdk.query.cdp.Asset({
710
+ denom: debtDenom
711
+ });
712
+ if (!asset.assetParams)
713
+ throw new Error("unable to retrieve asset param for " + debtDenom);
714
+ const bonus = (0, number_1.bnOrZero)(asset.assetParams.liquidationBonus).div(number_1.BN_10000);
715
+ const cdpTokenPrice = yield this.getCdpTokenPrice(cdpDenom);
716
+ const cdpTokenDiscountedPrice = cdpTokenPrice.multipliedBy(number_1.BN_ONE.minus(bonus));
717
+ // get cdp tokens (discounted) that can be gained from the debt amount
718
+ const debtValue = (_a = yield this.getTokenUsdVal(debtDenom, debtAmount)) !== null && _a !== void 0 ? _a : number_1.BN_ZERO;
719
+ const underlyingDenom = yield this.getUnderlyingDenom(cdpDenom);
720
+ const cdpTokenDecimals = (_b = yield sdk.getTokenClient().getDecimals(underlyingDenom)) !== null && _b !== void 0 ? _b : 0;
721
+ const cdpAmountWithDiscount = debtValue.div(cdpTokenDiscountedPrice).shiftedBy(cdpTokenDecimals);
722
+ // get cdp tokens (not discounted) that can be gained from the debt amount
723
+ const cdpAmountWithoutDiscount = debtValue.div(cdpTokenPrice).shiftedBy(cdpTokenDecimals);
724
+ // get fee amount
725
+ const cdpAmountProfit = cdpAmountWithDiscount.minus(cdpAmountWithoutDiscount);
726
+ const params = yield sdk.query.cdp.Params({});
727
+ if (!params.params)
728
+ throw new Error("unable to retrieve cdp params");
729
+ const feePercentage = (0, number_1.bnOrZero)(params.params.liquidationFee).div(number_1.BN_10000);
730
+ const feeAmount = cdpAmountProfit.multipliedBy(feePercentage);
731
+ // return collateral that can be received by liquidator
732
+ return cdpAmountWithDiscount.minus(feeAmount);
733
+ });
758
734
  }
759
735
  }
760
736
  exports.CDPModule = CDPModule;
@@ -3,5 +3,3 @@ import BaseModule from "./base";
3
3
  export declare class FeeModule extends BaseModule {
4
4
  getDepositWithdrawalFees(denom: string): Promise<GetFeeQuoteResponse>;
5
5
  }
6
- onse>;
7
- }
@@ -71,6 +71,3 @@ export declare namespace LiquidityPoolModule {
71
71
  address: string;
72
72
  }
73
73
  }
74
-
75
- }
76
- }
@@ -10,6 +10,3 @@ export declare namespace OracleModule {
10
10
  data: string;
11
11
  }
12
12
  }
13
-
14
- }
15
- }
@@ -36,5 +36,3 @@ class OracleModule extends base_1.default {
36
36
  }
37
37
  exports.OracleModule = OracleModule;
38
38
  ;
39
- = OracleModule;
40
- ;
@@ -58,6 +58,3 @@ export declare namespace OrderModule {
58
58
  Ioc = "ioc"
59
59
  }
60
60
  }
61
-
62
- }
63
- }
@@ -182,5 +182,3 @@ exports.OrderModule = OrderModule;
182
182
  })(TimeInForce = OrderModule.TimeInForce || (OrderModule.TimeInForce = {}));
183
183
  })(OrderModule = exports.OrderModule || (exports.OrderModule = {}));
184
184
  ;
185
- orts.OrderModule = {}));
186
- ;
@@ -11,6 +11,3 @@ export declare namespace PositionModule {
11
11
  margin: BigNumber;
12
12
  }
13
13
  }
14
-
15
- }
16
- }
@@ -51,5 +51,3 @@ class PositionModule extends base_1.default {
51
51
  }
52
52
  exports.PositionModule = PositionModule;
53
53
  ;
54
- PositionModule;
55
- ;
@@ -9,6 +9,3 @@ export declare namespace ProfileModule {
9
9
  twitter?: string;
10
10
  }
11
11
  }
12
-
13
- }
14
- }
@@ -34,5 +34,3 @@ class ProfileModule extends base_1.default {
34
34
  }
35
35
  exports.ProfileModule = ProfileModule;
36
36
  ;
37
- ProfileModule;
38
- ;
@@ -16,6 +16,3 @@ export declare namespace SubAccountModule {
16
16
  subAddress: string;
17
17
  }
18
18
  }
19
-
20
- }
21
- }
@@ -59,5 +59,3 @@ class SubAccountModule extends base_1.default {
59
59
  }
60
60
  exports.SubAccountModule = SubAccountModule;
61
61
  ;
62
- bAccountModule;
63
- ;
@@ -62,6 +62,7 @@ declare type SWTHAddressType = AddressBuilder<SWTHAddressOptions> & {
62
62
  getAddressBytes(bech32Address: string, networkConfig: Network): Uint8Array;
63
63
  keyDerivationPath(index?: number, change?: number, account?: number): number[];
64
64
  encode(hash: string | Buffer, opts?: SWTHAddressOptions): string;
65
+ getModuleAddress(moduleKey: string, network?: Network): string;
65
66
  };
66
67
  export declare const SWTHAddress: SWTHAddressType;
67
68
  declare type NEOAddressType = AddressBuilder<AddressOptions> & {
@@ -18,6 +18,9 @@ var __importStar = (this && this.__importStar) || function (mod) {
18
18
  __setModuleDefault(result, mod);
19
19
  return result;
20
20
  };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
21
24
  Object.defineProperty(exports, "__esModule", { value: true });
22
25
  exports.ETHAddress = exports.N3Address = exports.NEOAddress = exports.SWTHAddress = exports.wifEncodePrivateKey = exports.randomMnemonic = exports.BIP44Path = exports.stringOrBufferToBuffer = void 0;
23
26
  const constant_1 = require("../constant");
@@ -26,6 +29,7 @@ const Base58Check = __importStar(require("base58check"));
26
29
  const bech32 = __importStar(require("bech32"));
27
30
  const BIP32 = __importStar(require("bip32"));
28
31
  const BIP39 = __importStar(require("bip39"));
32
+ const crypto_js_1 = __importDefault(require("crypto-js"));
29
33
  const ethers_1 = require("ethers");
30
34
  const secp256k1 = __importStar(require("secp256k1"));
31
35
  const secp256r1 = __importStar(require("secp256r1"));
@@ -189,6 +193,10 @@ exports.SWTHAddress = {
189
193
  }
190
194
  return new Uint8Array(bech32.fromWords(words));
191
195
  },
196
+ getModuleAddress: (moduleKey, network = constant_1.Network.MainNet) => {
197
+ const addressHash = crypto_js_1.default.SHA256(moduleKey).toString(crypto_js_1.default.enc.Hex);
198
+ return exports.SWTHAddress.encode(addressHash, { network });
199
+ },
192
200
  };
193
201
  exports.NEOAddress = {
194
202
  coinType: () => {
@@ -93,8 +93,8 @@ const generateChannelId = (params) => {
93
93
  return [channel, denom].join(':');
94
94
  }
95
95
  case types_1.WSChannel.cdp_reward_schemes: {
96
- const { channel, address } = params;
97
- return [channel, address].join(':');
96
+ const { channel } = params;
97
+ return [channel].join(':');
98
98
  }
99
99
  case types_1.WSChannel.cdp_reward_debts: {
100
100
  const { channel, address } = params;
@@ -106,50 +106,50 @@ const generateChannelId = (params) => {
106
106
  };
107
107
  exports.generateChannelId = generateChannelId;
108
108
  const parseChannelId = (rawChannelId) => {
109
- const [channel, market, resolution, address, id] = rawChannelId.split(':');
109
+ const [channel, param0, param1] = rawChannelId.split(':');
110
110
  switch (channel) {
111
111
  case types_1.WSChannel.candlesticks:
112
112
  return {
113
113
  channel,
114
- market,
115
- resolution,
114
+ market: param0,
115
+ resolution: param1,
116
116
  };
117
117
  case types_1.WSChannel.books:
118
118
  return {
119
119
  channel,
120
- market,
120
+ market: param0,
121
121
  };
122
122
  case types_1.WSChannel.recent_trades:
123
123
  return {
124
124
  channel,
125
- market,
125
+ market: param0,
126
126
  };
127
127
  case types_1.WSChannel.orders:
128
128
  return {
129
129
  channel,
130
- address,
130
+ address: param0,
131
131
  };
132
132
  case types_1.WSChannel.orders_by_market:
133
133
  return {
134
134
  channel,
135
- market,
136
- address,
135
+ market: param0,
136
+ address: param1,
137
137
  };
138
138
  case types_1.WSChannel.balances:
139
139
  return {
140
140
  channel,
141
- address,
141
+ address: param0,
142
142
  };
143
143
  case types_1.WSChannel.account_trades:
144
144
  return {
145
145
  channel,
146
- address,
146
+ address: param0,
147
147
  };
148
148
  case types_1.WSChannel.account_trades_by_market:
149
149
  return {
150
150
  channel,
151
- market,
152
- address,
151
+ market: param0,
152
+ address: param1,
153
153
  };
154
154
  case types_1.WSChannel.market_stats:
155
155
  return {
@@ -158,29 +158,29 @@ const parseChannelId = (rawChannelId) => {
158
158
  case types_1.WSChannel.market_stats_by_market:
159
159
  return {
160
160
  channel,
161
- market,
161
+ market: param0,
162
162
  };
163
163
  case types_1.WSChannel.leverages:
164
164
  return {
165
165
  channel,
166
- address,
166
+ address: param0,
167
167
  };
168
168
  case types_1.WSChannel.leverages_by_market:
169
169
  return {
170
170
  channel,
171
- market,
172
- address,
171
+ market: param0,
172
+ address: param1,
173
173
  };
174
174
  case types_1.WSChannel.positions:
175
175
  return {
176
176
  channel,
177
- address,
177
+ address: param0,
178
178
  };
179
179
  case types_1.WSChannel.positions_by_market:
180
180
  return {
181
181
  channel,
182
- market,
183
- address,
182
+ market: param0,
183
+ address: param1,
184
184
  };
185
185
  case types_1.WSChannel.pools:
186
186
  return {
@@ -189,22 +189,22 @@ const parseChannelId = (rawChannelId) => {
189
189
  case types_1.WSChannel.pools_by_id:
190
190
  return {
191
191
  channel,
192
- id,
192
+ id: param0,
193
193
  };
194
194
  case types_1.WSChannel.commitments:
195
195
  return {
196
196
  channel,
197
- address,
197
+ address: param0,
198
198
  };
199
199
  case types_1.WSChannel.cdp_borrows:
200
200
  return {
201
201
  channel,
202
- address,
202
+ address: param0,
203
203
  };
204
204
  case types_1.WSChannel.cdp_collaterals:
205
205
  return {
206
206
  channel,
207
- address,
207
+ address: param0,
208
208
  };
209
209
  case types_1.WSChannel.cdp_liquidate_collaterals:
210
210
  return {
@@ -215,18 +215,18 @@ const parseChannelId = (rawChannelId) => {
215
215
  channel,
216
216
  };
217
217
  case types_1.WSChannel.cdp_token_debt:
218
- const denom = market;
219
218
  return {
220
219
  channel,
221
- denom,
220
+ denom: param0,
222
221
  };
223
222
  case types_1.WSChannel.cdp_reward_schemes:
224
223
  return {
225
- address,
224
+ channel,
226
225
  };
227
226
  case types_1.WSChannel.cdp_reward_debts:
228
227
  return {
229
- address,
228
+ channel,
229
+ address: param0,
230
230
  };
231
231
  default:
232
232
  throw new Error('Error parsing channelId');
@@ -203,7 +203,6 @@ export interface WsSubscribeTokenDebt extends WsSubscribeParams {
203
203
  denom: string;
204
204
  }
205
205
  export interface WsSubscribeRewardSchemes extends WsSubscribeParams {
206
- address?: string;
207
206
  }
208
207
  export interface WsSubscribeRewardDebts extends WsSubscribeParams {
209
208
  address?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "carbon-js-sdk",
3
- "version": "0.2.14-dev.3+035463ebd45e",
3
+ "version": "0.2.14-dev.5+de5603ab13a1",
4
4
  "description": "TypeScript SDK for Carbon blockchain",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",