-
Notifications
You must be signed in to change notification settings - Fork 7
/
contracts.ts
214 lines (196 loc) · 7.19 KB
/
contracts.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
import {
ContractLockOptions,
Contracts,
ExtrinsicResult,
GetDedicatedNodePriceOptions,
SetDedicatedNodeExtraFeesOptions,
} from "@threefold/tfchain_client";
import { Decimal } from "decimal.js";
import { ContractStates } from "../../modules";
import { Graphql } from "../graphql/client";
export interface ListContractByTwinIdOptions {
graphqlURL: string;
twinId: number;
stateList?: ContractStates[];
}
export interface ListContractByAddressOptions {
graphqlURL: string;
accountId: string;
stateList?: ContractStates[];
}
export interface ListMyContractOptions {
graphqlURL: string;
stateList?: ContractStates[];
}
export interface GetConsumptionOptions {
graphqlURL: string;
id: number;
}
export interface CancelMyContractOptions {
graphqlURL: string;
}
class TFContracts extends Contracts {
async listContractsByTwinId(options: ListContractByTwinIdOptions) {
options.stateList = options.stateList || [ContractStates.Created, ContractStates.GracePeriod];
const state = `[${options.stateList.join(", ")}]`;
const gqlClient = new Graphql(options.graphqlURL);
const opts = `(where: {twinID_eq: ${options.twinId}, state_in: ${state}}, orderBy: twinID_ASC)`;
try {
const nameContractsCount = await gqlClient.getItemTotalCount("nameContracts", opts);
const nodeContractsCount = await gqlClient.getItemTotalCount("nodeContracts", opts);
const rentContractsCount = await gqlClient.getItemTotalCount("rentContracts", opts);
const body = `query getContracts($nameContractsCount: Int!, $nodeContractsCount: Int!, $rentContractsCount: Int!){
nameContracts(where: {twinID_eq: ${options.twinId}, state_in: ${state}}, limit: $nameContractsCount) {
contractID
state
name
createdAt
}
nodeContracts(where: {twinID_eq: ${options.twinId}, state_in: ${state}}, limit: $nodeContractsCount) {
contractID
deploymentData
state
createdAt
nodeID
}
rentContracts(where: {twinID_eq: ${options.twinId}, state_in: ${state}}, limit: $rentContractsCount) {
contractID
state
createdAt
nodeID
}
}`;
const response = await gqlClient.query(body, {
nodeContractsCount: nodeContractsCount,
nameContractsCount: nameContractsCount,
rentContractsCount: rentContractsCount,
});
return response["data"];
} catch (err) {
throw Error(`Error listing contracts by twin id ${options.twinId}: ${err}`);
}
}
/**
* Get contract consumption per hour in TFT.
*
* @param {GetConsumptionOptions} options
* @returns {Promise<number>}
*/
async getConsumption(options: GetConsumptionOptions): Promise<number> {
const gqlClient = new Graphql(options.graphqlURL);
const body = `query getConsumption($contractId: BigInt!){
contractBillReports(where: {contractID_eq: $contractId}, limit: 2 , orderBy: timestamp_DESC) {
amountBilled
timestamp
}
nodeContracts(where: {contractID_eq: $contractId}) {
createdAt
}
nameContracts(where: {contractID_eq: $contractId}) {
createdAt
}
rentContracts(where: {contractID_eq: $contractId}) {
createdAt
}
}`;
try {
const response = await gqlClient.query(body, { contractId: options.id });
const billReports = response["data"]["contractBillReports"];
if (billReports.length === 0) {
return 0;
} else {
let duration: number;
const amountBilled = new Decimal(billReports[0]["amountBilled"]);
if (billReports.length === 2) {
duration = (billReports[0]["timestamp"] - billReports[1]["timestamp"]) / 3600; // one hour
} else {
const nodeContracts = response["data"]["nodeContracts"];
const nameContracts = response["data"]["nameContracts"];
const rentContracts = response["data"]["rentContracts"];
let createdAt: number;
for (const contracts of [nodeContracts, nameContracts, rentContracts]) {
if (contracts.length === 1) {
createdAt = contracts[0]["createdAt"];
duration = (billReports[0]["timestamp"] - createdAt) / 3600;
break;
}
}
}
if (!duration) {
duration = 1;
}
return amountBilled
.div(duration)
.div(10 ** 7)
.toNumber();
}
} catch (err) {
throw Error(`Error getting consumption for contract ${options.id}: ${err}`);
}
}
async listContractsByAddress(options: ListContractByAddressOptions) {
const twinId = await this.client.twins.getTwinIdByAccountId({ accountId: options.accountId });
return await this.listContractsByTwinId({
graphqlURL: options.graphqlURL,
twinId: twinId,
stateList: options.stateList,
});
}
async listMyContracts(options: ListMyContractOptions) {
const twinId = await this.client.twins.getMyTwinId();
return await this.listContractsByTwinId({
graphqlURL: options.graphqlURL,
twinId: twinId,
stateList: options.stateList,
});
}
async contractLock(options: ContractLockOptions) {
const res = await super.contractLock(options);
const amountLocked = new Decimal(res.amountLocked);
res.amountLocked = amountLocked.div(10 ** 7).toNumber();
return res;
}
/**
* WARNING: Please be careful when executing this method, it will delete all your contracts.
* @param {CancelMyContractOptions} options
* @returns {Promise<Record<string, number>[]>}
*/
async cancelMyContracts(options: CancelMyContractOptions): Promise<Record<string, number>[]> {
const allContracts = await this.listMyContracts(options);
const contracts = [
...allContracts["nameContracts"],
...allContracts["nodeContracts"],
...allContracts["rentContracts"],
];
const ids: number[] = [];
for (const contract of contracts) {
ids.push(contract["contractID"]);
}
await this.batchCancelContracts(ids);
return contracts;
}
async batchCancelContracts(ids: number[]): Promise<number[]> {
const extrinsics = [];
for (const id of ids) {
extrinsics.push(await this.cancel({ id }));
}
await this.client.applyAllExtrinsics(extrinsics);
return ids;
}
async getDedicatedNodeExtraFee(options: GetDedicatedNodePriceOptions): Promise<number> {
// converting fees from milli to usd before getting
const fee = new Decimal(await super.getDedicatedNodeExtraFee(options));
const feeUSD = fee.div(10 ** 3).toNumber();
return feeUSD;
}
async setDedicatedNodeExtraFee(options: SetDedicatedNodeExtraFeesOptions) {
// converting fees from usd to milli before setting
const fee = new Decimal(options.extraFee);
const feeUSD = fee.mul(10 ** 3).toNumber();
return await super.setDedicatedNodeExtraFee({
nodeId: options.nodeId,
extraFee: feeUSD,
});
}
}
export { TFContracts };