This repository has been archived by the owner on Jun 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tcrService.js
318 lines (292 loc) · 12.5 KB
/
tcrService.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
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
const { ApiPromise } = require('@polkadot/api');
const { Keyring } = require('@polkadot/keyring');
const { stringToU8a } = require('@polkadot/util');
const dataService = require('./dataService');
// connects to the substrate node
export async function connect() {
const api = await _createApiWithTypes();
// Retrieve the chain & node information information via rpc calls
const [chain, name, version] = await Promise.all([
api.rpc.system.chain(),
api.rpc.system.name(),
api.rpc.system.version()
]);
const connected = `You are connected to chain ${chain} using ${name} v${version}`;
console.log(connected);
return { chain, name, version };
}
// gets TCR parameters from the chain storage
export async function getTcrDetails() {
const api = await _createApiWithTypes();
const [asl, csl, md] = await Promise.all([
api.query.tcr.applyStageLen(),
api.query.tcr.commitStageLen(),
api.query.tcr.minDeposit()
]);
// the Moment type is returned as the full Date object
// converting it to seconds
const aslSeconds = Math.floor(new Date(asl).getTime() / 1000);
const cslSeconds = Math.floor(new Date(csl).getTime() / 1000);
// converting the Balance type to value string
const mdTokens = JSON.stringify(md);
console.log(aslSeconds, cslSeconds, mdTokens);
return { aslSeconds, cslSeconds, mdTokens };
}
// gets all listings from the off-chain storage
export async function getAllListings() {
return dataService.getAllListings();
}
// apply for a new listing
export async function applyListing(name, deposit) {
return new Promise(async (resolve, reject) => {
const api = await ApiPromise.create();
const keys = _getKeysFromSeed();
const nonce = await api.query.system.accountNonce(keys.address);
console.log('Sending...', name, deposit);
// create, sign and send transaction
api.tx.tcr
// create transaction
.propose(name, deposit)
// Sign and send the transcation
.sign(keys, { nonce })
.send(({ events = [], status }) => {
if (status.isFinalized) {
console.log(status.asFinalized.toHex());
events.forEach(async ({ phase, event: { data, method, section } }) => {
console.log('\t', phase.toString(), `: ${section}.${method}`, data.toString());
// check if the tcr proposed event was emitted by Substrate runtime
if (section.toString() === "tcr" && method.toString() === "Proposed") {
// insert metadata in off-chain store
const datajson = JSON.parse(data.toString());
const listingInstance = {
name: name,
owner: datajson[0],
hash: datajson[1],
deposit: datajson[2],
isWhitelisted: false,
challengeId: 0,
rejected: false
}
await dataService.insertListing(listingInstance);
// resolve the promise with listing data
resolve(listingInstance);
}
});
}
})
.catch(err => reject(err));
});
}
// gets the token balance for an account
// this is the TCR token balance and not the Substrate balances module balance
export async function getBalance(seed, callback) {
const keys = _getKeysFromSeed(seed);
const api = await ApiPromise.create();
api.query.token.balanceOf(keys.address, (balance) => {
let bal = JSON.stringify(balance);
callback(bal);
});
}
// challenge a listing
export async function challengeListing(hash, deposit) {
return new Promise(async (resolve, reject) => {
const api = await _createApiWithTypes();
const keys = _getKeysFromSeed();
const nonce = await api.query.system.accountNonce(keys.address);
const listing = await api.query.tcr.listings(hash);
const listingJson = JSON.parse(listing.toString());
// create, sign and send transaction
api.tx.tcr
// create transaction
.challenge(listingJson.id, deposit)
.sign(keys, { nonce })
.send(({ events = [], status }) => {
if (status.isFinalized) {
console.log(status.asFinalized.toHex());
events.forEach(async ({ phase, event: { data, method, section } }) => {
// check if the tcr proposed event was emitted by Substrate runtime
if (section.toString() === "tcr" && method.toString() === "Challenged") {
const datajson = JSON.parse(data.toString());
// update local listing with challenge id
const localListing = dataService.getListing(hash);
localListing.challengeId = datajson[2];
dataService.updateListing(localListing);
// resolve the promise with challenge data
resolve({
tx: status.asFinalized.toHex(),
data: datajson
});
}
});
}
})
.catch(err => reject(err));
});
}
// vote on a challenged listing
export async function voteListing(hash, voteValue, deposit) {
return new Promise(async (resolve, reject) => {
const api = await _createApiWithTypes();
const keys = _getKeysFromSeed();
const nonce = await api.query.system.accountNonce(keys.address);
const listing = await api.query.tcr.listings(hash);
const listingJson = JSON.parse(listing.toString());
// check if listing is currently challenged
if (listingJson.challenge_id > 0) {
// create, sign and send transaction
api.tx.tcr
// create transaction
.vote(listingJson.challenge_id, voteValue, deposit)
.sign(keys, { nonce })
.send(({ events = [], status }) => {
if (status.isFinalized) {
console.log(status.asFinalized.toHex());
events.forEach(async ({ phase, event: { data, method, section } }) => {
// check if the tcr proposed event was emitted by Substrate runtime
if (section.toString() === "tcr" &&
method.toString() === "Voted") {
const datajson = JSON.parse(data.toString());
// resolve with event data
resolve({
tx: status.asFinalized.toHex(),
data: datajson
});
}
});
}
})
.catch(err => reject(err));
} else {
reject(new Error("Listing is not currently challenged."));
}
});
}
// resolve a listing
export async function resolveListing(hash) {
return new Promise(async (resolve, reject) => {
const api = await _createApiWithTypes();
const keys = _getKeysFromSeed();
const nonce = await api.query.system.accountNonce(keys.address);
const listing = await api.query.tcr.listings(hash);
const listingJson = JSON.parse(listing.toString());
// create, sign and send transaction
api.tx.tcr
// create transaction
.resolve(listingJson.id)
.sign(keys, { nonce })
.send(({ events = [], status }) => {
if (status.isFinalized) {
console.log(status.asFinalized.toHex());
events.forEach(async ({ phase, event: { data, method, section } }) => {
if (section.toString() === "tcr" &&
method.toString() === "Accepted") {
// if accepted, updated listing status
const datajson = JSON.parse(data.toString());
const localListing = dataService.getListing(hash);
localListing.isWhitelisted = true;
dataService.updateListing(localListing);
// resolve with event data
resolve({
tx: status.asFinalized.toHex(),
data: datajson
});
}
if (section.toString() === "tcr" &&
method.toString() === "Rejected") {
// if accepted, updated listing status
const datajson = JSON.parse(data.toString());
const localListing = dataService.getListing(hash);
localListing.rejected = true;
dataService.updateListing(localListing);
// resolve with event data
resolve({
tx: status.asFinalized.toHex(),
data: datajson
});
}
});
}
})
.catch(err => reject(err));
});
}
// claim reward for a resolved challenge
export async function claimReward(challengeId) {
return new Promise(async (resolve, reject) => {
const api = await _createApiWithTypes();
const keys = _getKeysFromSeed();
const nonce = await api.query.system.accountNonce(keys.address);
// create, sign and send transaction
api.tx.tcr
// create transaction
.claimReward(challengeId)
.sign(keys, { nonce })
.send(({ events = [], status }) => {
if (status.isFinalized) {
console.log(status.asFinalized.toHex());
events.forEach(async ({ phase, event: { data, method, section } }) => {
if (section.toString() === "tcr" &&
method.toString() === "Claimed") {
const datajson = JSON.parse(data.toString());
// resolve with event data
resolve({
tx: status.asFinalized.toHex(),
data: datajson
});
}
});
}
})
.catch(err => reject(err));
});
}
// create an API promise object with custom types
async function _createApiWithTypes() {
return await ApiPromise.create({
types: {
Listing: {
"id": "u32",
"data": "Vec<u8>",
"deposit": "Balance",
"owner": "AccountId",
"application_expiry": "Moment",
"whitelisted": "bool",
"challenge_id": "u32"
},
Challenge: {
"listing_hash": "Hash",
"deposit": "Balance",
"owner": "AccountId",
"voting_ends": "Moment",
"resolved": "bool",
"reward_pool": "Balance",
"total_tokens": "Balance"
},
Poll: {
"listing_hash": "Hash",
"votes_for": "Balance",
"votes_against": "Balance",
"passed": "bool"
},
Vote: {
"value": "bool",
"deposit": "Balance",
"claimed": "bool"
},
TokenBalance: "u128"
}
});
}
// get keypair from passed or locally stored seed
function _getKeysFromSeed(seed) {
let _seed = seed;
if (!seed) {
_seed = localStorage.getItem("seed");
}
if (!_seed) {
throw new Error("Seed not found.");
}
const keyring = new Keyring({ type: 'sr25519' });
const paddedSeed = _seed.padEnd(32);
return keyring.addFromSeed(stringToU8a(paddedSeed));
}