forked from XRPLBounties/Proof-of-Attendance-API
-
Notifications
You must be signed in to change notification settings - Fork 2
/
attendify.js
462 lines (450 loc) · 18.1 KB
/
attendify.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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
const { NFTokenMintFlags, NFTokenCreateOfferFlags } = require("xrpl");
const xrpl = require("xrpl");
const verifySignature = require("verify-xrpl-signature").verifySignature;
require("dotenv").config();
const {
ERR_ATTENDIFY,
ERR_IPFS,
ERR_NOT_FOUND,
ERR_PARAMS,
ERR_XRPL,
} = require("./utils");
const fs = require("fs");
/**
* Attendify is API library for proof of attendance infrastructure on XRPL
* It allows for creation of new claim events, checking whether claim is possible,
* claiming, verifying NFT ownership, and fetching list of participants for a particular event
* @author JustAnotherDevv
* @version 1.2.4
*/
class Attendify {
/**
* Initializes a new instance of the Attendify class
*/
constructor() {
// Initializes the next event ID to 0
this.nextEventId = 0;
// Map with temporary numbers used to prove wallet ownership for verification
this.signatureMap = new Map();
}
/**
*
* @param {string} walletAddress - The address of the participant's wallet
* @returns true if account was found on selected network or false if it wasn't
*/
async checkIfAccountExists(walletAddress) {
try {
const client = new xrpl.Client(process.env.SELECTED_NETWORK);
await client.connect();
const tx = await client.getBalances(walletAddress);
await client.disconnect();
console.log(tx);
return true;
} catch (error) {
console.error(error);
return false;
}
}
/**
* Adds a participant to an event or creates event array for participants
* Saves the JSON with participants to local JSON file
* @param {string} walletAddress - The address of the participant's wallet
* @param {number} eventId - The ID of the event
* @returns {boolean} - `true` if the participant was added successfully, `false` otherwise
*/
async addParticipant(walletAddress, eventId) {
try {
if (eventId == undefined) throw new Error(`${ERR_PARAMS}`);
let data = await fs.promises.readFile("participants.json", "utf-8");
console.log(typeof data);
let participantsJson;
if (data == "") {
participantsJson = { data: [[]] };
} else {
participantsJson = JSON.parse(data);
if (participantsJson.data[eventId]) {
// Check if user wallet is already participant for selected event
const userParticipantData = participantsJson.data[eventId].find(
(obj) => {
return obj.user === walletAddress;
}
);
if (userParticipantData != undefined) return true;
}
}
if (walletAddress == undefined) {
// Pushes an empty array to the participants.json file if no wallet address is provided
participantsJson.data.push([]);
} else if (participantsJson.data[eventId] == undefined) {
// Adds the participant to the event's list of participants and creates and empty array for participants from chosen event
participantsJson.data.push([
{
user: walletAddress,
},
]);
} else {
// Adds the user wallet to the event's list of participants if it's not already there
participantsJson.data[eventId].push({
user: walletAddress,
});
}
await fs.promises.writeFile(
"participants.json",
JSON.stringify(participantsJson)
);
return true;
} catch (error) {
console.error(error);
return error;
}
}
/**
* Creates new XRPL wallet and funds it
* @returns {object} - Object with new wallet that was created and funded
*/
async getNewAccount() {
try {
const client = new xrpl.Client(process.env.SELECTED_NETWORK);
await client.connect();
const fund_result = await client.fundWallet();
const newWallet = fund_result.wallet;
await client.disconnect();
return newWallet;
} catch (error) {
console.error(error);
return error;
}
}
/**
* Checks for all NFTs owned by a particular address
* @param {string} address - The wallet address to check
* @param {string} [taxon] - An optional parameter used to filter the NFTs by taxon
* @returns {object[]} - An array of NFTs owned by the given address. If no NFTs are found, returns an empty array
*/
async getBatchNFTokens(address, taxon) {
try {
if (!address) throw new Error(`${ERR_PARAMS}`);
if ((await this.checkIfAccountExists(address)) == false)
throw new Error(`Account from request was not found om XRPL`);
const client = new xrpl.Client(process.env.SELECTED_NETWORK);
await client.connect();
let nfts = await client.request({
method: "account_nfts",
account: address,
});
let accountNfts = nfts.result.account_nfts;
//console.log("Found ", accountNfts.length, " NFTs in account ", address);
while (true) {
if (nfts["result"]["marker"] === undefined) {
break;
} else {
nfts = await client.request({
method: "account_nfts",
account: address,
marker: nfts["result"]["marker"],
});
accountNfts = accountNfts.concat(nfts.result.account_nfts);
}
}
client.disconnect();
if (taxon) return accountNfts.filter((a) => a.NFTokenTaxon == taxon);
return accountNfts;
} catch (error) {
console.error(error);
return error;
}
}
/**
* Creates a sell offer for NFT from selected event
* The offer has to be accepted by the buyer once it was returned
* * In current design checks to see whether or not there are still any NFTs
* * to claim are done outside of this class in related API route
* @ToDo Whitelist system to only allow claiming from certain adresses
* @ToDo Deadline system where NFTs can only be claimed before the event ends
* @ToDo Return previously created offer for user that's already event participant
* @param {string} buyer - wallet address of user trying to claim NFT
* @param {string} minterSeed - seed of wallet storing NFTs from selected event
* @param {string} TokenID - ID for NFT that should be claimed
* @returns {object} - The metadata of the sell offer for a given NFT from selected event
* @throws {Error} - If any of the required parameters are missing or if there is an issue creating the sell offer
*/
async createSellOfferForClaim(buyer, minterSeed, TokenID) {
try {
if (!buyer || !minterSeed || !TokenID) throw new Error(`${ERR_PARAMS}`);
if ((await this.checkIfAccountExists(buyer)) == false)
throw new Error(`Account from request was not found om XRPL`);
const seller = xrpl.Wallet.fromSeed(minterSeed);
const client = new xrpl.Client(process.env.SELECTED_NETWORK);
await client.connect();
// Preparing transaction data
let transactionBlob = {
TransactionType: "NFTokenCreateOffer",
Account: seller.classicAddress,
NFTokenID: TokenID,
Amount: "0",
Flags: NFTokenCreateOfferFlags.tfSellNFToken,
};
transactionBlob.Destination = buyer;
// Submitting transaction to XRPL
const tx = await client.submitAndWait(transactionBlob, {
wallet: seller,
});
let nftSellOffers = await client.request({
method: "nft_sell_offers",
nft_id: TokenID,
});
if (nftSellOffers == null) throw new Error(`${ERR_XRPL}`);
// Getting details of sell offer for buyer wallet address
let offerToAccept = nftSellOffers.result.offers.find((obj) => {
return obj.destination === buyer;
});
client.disconnect();
const curentEventId = (await xrpl.parseNFTokenID(TokenID)).Taxon;
await this.addParticipant(buyer, curentEventId);
return offerToAccept;
} catch (error) {
console.error(error);
throw new Error(error);
// return error;
}
}
/**
* Retrieves a list of all tickets owned by a particular address
* @param {string} walletAddress - The wallet address to check
* @param {object} client - The XRPL client to use for the request
* @returns {object[]} - An array of tickets owned by the given address. If no tickets are found, returns an empty array
*/
async getAccountTickets(walletAddress, client) {
let res = await client.request({
command: "account_objects",
account: walletAddress,
type: "ticket",
});
let resTickets = res.result.account_objects;
while (true) {
console.log("marker, ", res["result"]["marker"]);
if (res["result"]["marker"] === undefined) {
return resTickets;
}
res = await client.request({
method: "account_objects",
account: walletAddress,
type: "ticket",
marker: res["result"]["marker"],
});
console.log(res.result.account_objects.length);
return resTickets.concat(res.result.account_objects);
}
}
/**
* Mints NFTs for created event and saves IPFS hash with data about event to Uri field
* @param {string} walletAddress - Account of user requesting creation of event
* @param {integer} nftokenCount - Amount of NFTs that should be minted for event
* @param {string} url - IPFS hash with metadata for NFT
* @param {string} title - Name of event
* @param {string} minterSeed - The seed of the wallet that will be minting the NFTs
* @param {number} curentEventId - The event ID of the NFTs. Defaults to the next event ID in the sequence
* @returns {object} - An object containing the metadata related to new event for which NFTs were minted
* @throws {Error} - If any of the required parameters are missing or if there is an issue minting the NFTs
*/
async batchMint(
walletAddress,
nftokenCount,
url,
title,
minterSeed,
curentEventId = this.nextEventId
) {
try {
if (!walletAddress || !nftokenCount || !url || !title)
throw new Error(`${ERR_PARAMS}`);
if ((await this.checkIfAccountExists(walletAddress)) == false)
throw new Error(`Account from request was not found om XRPL`);
const client = new xrpl.Client(process.env.SELECTED_NETWORK);
await client.connect();
const vaultWallet = xrpl.Wallet.fromSeed(minterSeed);
let remainingTokensBeforeTicketing = nftokenCount;
for (let currentTickets; remainingTokensBeforeTicketing != 0; ) {
let maxTickets =
250 -
(await this.getAccountTickets(vaultWallet.address, client)).length;
console.log("Max tickets", maxTickets);
if (maxTickets == 0)
throw new Error(
`The minter has maximum allowed number of tickets at the moment. Please try again later, remove tickets that are not needed or use different minter account.`
);
const balanceForTickets = parseInt(
((await client.getXrpBalance(vaultWallet.address)) - 1) / 2
);
if (balanceForTickets < maxTickets) maxTickets = balanceForTickets;
if (remainingTokensBeforeTicketing > maxTickets) {
currentTickets = maxTickets;
} else {
currentTickets = remainingTokensBeforeTicketing;
}
// Get account information, particularly the Sequence number.
const account_info = await client.request({
command: "account_info",
account: vaultWallet.address,
});
let my_sequence = account_info.result.account_data.Sequence;
// Create the transaction hash.
const ticketTransaction = await client.autofill({
TransactionType: "TicketCreate",
Account: vaultWallet.address,
TicketCount: currentTickets,
Sequence: my_sequence,
});
// Sign the transaction.
const signedTransaction = vaultWallet.sign(ticketTransaction);
// Submit the transaction and wait for the result.
const tx = await client.submitAndWait(signedTransaction.tx_blob);
let resTickets = await this.getAccountTickets(
vaultWallet.address,
client
);
// Populate the tickets array variable.
let tickets = [];
for (let i = 0; i < currentTickets; i++) {
//console.log({ index: i, res: resTickets[i] });
tickets[i] = resTickets[i].TicketSequence;
}
// Mint NFTokens
for (let i = 0; i < currentTickets; i++) {
console.log(
"minting ",
i + 1 + (nftokenCount - remainingTokensBeforeTicketing),
"/",
nftokenCount,
" NFTs"
);
const transactionBlob = {
TransactionType: "NFTokenMint",
Account: vaultWallet.classicAddress,
URI: xrpl.convertStringToHex(url),
Flags: NFTokenMintFlags.tfTransferable,
/*{
tfBurnable: true,
tfTransferable: true,
},*/
TransferFee: parseInt(0),
Sequence: 0,
TicketSequence: tickets[i],
LastLedgerSequence: null,
NFTokenTaxon: curentEventId,
};
// Submit signed blob.
const tx = await client.submit(transactionBlob, {
wallet: vaultWallet,
});
}
remainingTokensBeforeTicketing -= currentTickets;
}
client.disconnect();
this.nextEventId++;
await this.addParticipant(undefined, curentEventId);
return {
eventId: curentEventId,
account: vaultWallet.classicAddress,
owner: walletAddress,
URI: url,
title: title,
claimable: nftokenCount,
};
} catch (error) {
console.error(error);
throw new Error(error);
// return error;
}
}
/**
* Verifies whether or not walletAddress account is owner of NFT from event with eventId that was issued by wallet that matches minter parameter. This step only works if user has interacted with the app previously by generating unique id that has to be included in the signed tx memo and turned into hex value
* * Wallet from signature has to match walletAddress
* @param {string} walletAddress - Address of wallet for the user wanting to verify
* @param {string} signature - Signature that should be signed by the same account as walletAddress. This could be done either using XUMM or `sign` function from xrpl library. The mock transaction from signature has to contain memo with number generated for walletAddress. See test.js for example implementation of this
* @param {string} minter - The address of the wallet that minted the NFT
* @param {number} eventId - The event ID of the NFT
* @returns {boolean} Indicats whether the walletAddress owns any NFT from particular event
*/
async verifyOwnership(walletAddress, signature, minter, eventId) {
try {
if (!walletAddress || !signature || !minter || !eventId)
throw new Error(`${ERR_PARAMS}`);
if ((await this.checkIfAccountExists(walletAddress)) == false)
throw new Error(`Account from request was not found om XRPL`);
const verifySignatureResult = verifySignature(signature);
const DECODED_SIGNATURE = xrpl.decode(signature);
if (verifySignatureResult.signatureValid != true)
throw new Error(`Signature is not valid.`);
if (verifySignatureResult.signedBy != walletAddress)
throw new Error(
`Signature wasn't signed by provided wallet address '${walletAddress}'. Please provide correct signature and try again.`
);
if (!DECODED_SIGNATURE.Memos)
throw new Error(
`Signed tx must include memo with ID obtained at the start of verification process.`
);
const TX_MEMO = xrpl.convertHexToString(
DECODED_SIGNATURE.Memos[0].Memo.MemoData
);
const EXPECTED_MEMO_ID = this.signatureMap.get(walletAddress);
if (!EXPECTED_MEMO_ID)
throw new Error(
`Wallet address '${walletAddress}' doesn't have the verification ID generated for it yet. Please start the verification process by calling 'startVerification' and including the returned value as part of the memo in your signed transaction when calling this function.`
);
if (TX_MEMO != EXPECTED_MEMO_ID)
throw new Error(
`Memo '${TX_MEMO}' from signature does not match expected ID for the provided wallet address '${walletAddress}'.`
);
// Getting user NFTs and checking whether any NFT was issued by minter address
const accountNfts = await this.getBatchNFTokens(walletAddress, eventId);
if (accountNfts.length == 0) return false;
for (let i = 0; i != accountNfts.length; i++) {
if (accountNfts[i].Issuer == minter) {
this.signatureMap.set(walletAddress, null);
return true;
}
if (i == accountNfts.length - 1) return false;
}
} catch (error) {
console.error(error);
return error;
}
}
/**
* Looks up the list of users that started process of claiming the NFT
* @ToDo Add permissions to configure who can access the list of participants
* @param {string} minter - The wallet address of the event creator
* @param {string} eventId - ID of selected claim event
* @returns {array[]} An array of objects with data for users that requested to participate in event
* @throws {Error} If the `minter` or `eventId` parameters are not provided.
* @throws {Error} If the event does not exist
*/
async attendeesLookup(minter, eventId) {
try {
if (!minter || !eventId) throw new Error(`${ERR_PARAMS}`);
// Find selected event
let data = await fs.promises.readFile("participants.json", "utf-8");
let participantsJson = JSON.parse(data.toString());
console.log(data);
const attendees = participantsJson.data[eventId];
// Check if claim event exists and if it has any attendees already
if (!attendees)
throw new Error(
`Claim event with id ${eventId} from minter with address ${minter} does not exist.`
);
if (attendees.length == 0)
throw new Error(
`Claim event with id ${eventId} from minter with address ${minter} does not have any attendees yet.`
);
// Retrieve and return participants from claimable array
return attendees;
} catch (error) {
console.error(error);
return error;
}
}
}
module.exports = {
Attendify,
};