-
Notifications
You must be signed in to change notification settings - Fork 0
/
kollek-api.js
442 lines (423 loc) · 15.5 KB
/
kollek-api.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
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));
const xrpl = require('xrpl')
const verify = require('verify-xrpl-signature').verifySignature
const config = {
network: 'wss://xls20-sandbox.rippletest.net:51233',
netrpc: 'https://xls20-sandbox.rippletest.net:51234'
}
/**
* Kollek is an API used to mint, claim and verify NFTs in the XRPL ledger
* @version 1.0.0
* @author Kuyawa
*/
class Kollek {
/**
* @param {string} key - Minter account secret key
* @throws {string} Key is required
*/
constructor(key){
if(!key){ throw 'Minter key is required'; return; }
this.minterKey = key
}
/**
* Mints event master ticket and all tickets.
* If issuer is provided, will mint ticket for that account.
* Issuer must approve minter beforehand.
* Event info is required, at least id, name, date and uri.
*
* @param {object} event - Event object with all info
* @param {string} issuer - NFT issuer that will collect royalties
* @throws {string} Throws error message
* @returns {string} TokenId of recently minted NFT
*/
async mintNFT(event, issuer){
if(!event.eventid){ throw 'Event ID is required' }
if(!event.name){ throw 'Event name is required' }
if(!event.startdate){ throw 'Event date is required' }
if(!event.uri){ throw 'Event URI is required' }
console.log('Minting NFT...')
let tokenId = null
let client = null
try {
let wallet = xrpl.Wallet.fromSeed(this.minterKey)
client = new xrpl.Client(config.network)
await client.connect()
let hexUri = xrpl.convertStringToHex(event.uri)
let memos = Utils.parseMemo(event)
let tx = {
TransactionType: 'NFTokenMint',
Account: wallet.classicAddress,
URI: hexUri,
Flags: 11, // burnable, resellable, transferable
Fee: '12', // drops per tx
NFTokenTaxon: parseInt(event.eventid), // group all event tickets
Memos: memos
}
if(issuer){ tx.Issuer = issuer }
let info = await client.submitAndWait(tx,{wallet})
console.log('Result:', info?.result?.meta?.TransactionResult)
if(info?.result?.meta?.TransactionResult=='tesSUCCESS'){
tokenId = Utils.parseTokenId(info)
} else {
throw 'Error minting NFT'
}
} catch(ex) {
console.error(ex)
throw ex.message
} finally {
client?.disconnect()
}
return tokenId
}
/**
* Mints NFTs in bulk for future delivery.
* Gets an event object with all the info.
* Optional quantity if minting less than max.
* Returns list of NFTs minted or list of tickets.
*
* @param {object} event - Event object with all info
* @param {integer} qty - Quantity of NFTs being minted
* @param {boolean} nowait - Submits without waiting for response
* @throws {string} Throws error message
* @returns {string} TokenId of recently minted NFT
*/
async bulkMintNFT(event, qty, nowait=false){
if(!qty){ qty = event.quantity } // If no quantity mint them all
console.log(`Minting ${qty} NFTs for event ${event.eventid}`)
let list = []
let client = null
try {
let wallet = xrpl.Wallet.fromSeed(this.minterKey)
let account = wallet.classicAddress
client = new xrpl.Client(config.network)
await client.connect()
// Get account info
let info = await client.request({
'command': 'account_info',
'account': account
})
// Create tickets for bulk minting
let sequence = info.result.account_data.Sequence
let ticketTrx = await client.autofill({
'TransactionType': 'TicketCreate',
'Account': account,
'TicketCount': qty,
'Sequence': sequence
})
let sign = wallet.sign(ticketTrx)
let trx = await client.submitAndWait(sign.tx_blob)
// Request account tickets
let resp = await client.request({
'command': 'account_objects',
'account': account,
'type': 'ticket'
})
let tickets = []
for (let i=0; i < qty; i++) {
tickets.push(resp.result.account_objects[i].TicketSequence)
}
tickets = tickets.sort()
let hexUri = xrpl.convertStringToHex(event.uri)
let taxon = parseInt(event.eventid)
let memos = Utils.parseMemo(event)
// Mint NFTs with tickets
for (let i=0; i<qty; i++) {
console.log('NFT #', i+1)
let blob = {
'TransactionType': 'NFTokenMint',
'Account': account,
'URI': hexUri,
'Flags': 11, // burnable, resellable, transferable
'Fee': '12', // drops per tx
'Sequence': 0,
'TicketSequence': tickets[i],
'LastLedgerSequence': null,
'NFTokenTaxon': taxon,
'Memos': memos
}
if(nowait){
let data = client.submit(blob,{wallet})
console.log('Ticket #', tickets[i])
list.push(tickets[i])
} else {
let data = await client.submitAndWait(blob,{wallet})
console.log('Ticket #', tickets[i], data?.result?.meta?.TransactionResult)
if(data?.result?.meta?.TransactionResult=='tesSUCCESS'){
let tokenId = Utils.parseTokenId(data)
console.log('TokenId:', tokenId)
list.push(tokenId)
}
}
}
} catch(ex) {
console.error(ex)
throw ex.message
} finally {
client?.disconnect()
}
console.log(nowait?'Tickets':'Tokens:', list)
return list
}
/**
* Transfers NFT to new owner.
* Creates sell offer with price = 0.
* Destin account must accept sell offer.
*
* @param {string} tokenId - Id of NFT being claimed
* @param {string} destin - Destination address
* @throws {string} Throws error message
* @returns {string} Recently created Offer Id
*/
async claimNFT(tokenId, destin){
console.log('Claiming NFT...')
let offerId = null
let client = null
try {
let wallet = xrpl.Wallet.fromSeed(this.minterKey)
client = new xrpl.Client(config.network)
await client.connect()
let tx = {
TransactionType: 'NFTokenCreateOffer',
Account: wallet.classicAddress,
NFTokenID: tokenId,
Destination: destin,
Amount: '0',
Flags: 1 // sell offer
}
let info = await client.submitAndWait(tx, {wallet})
console.log('Result:', info?.result?.meta?.TransactionResult)
if(info?.result?.meta?.TransactionResult=='tesSUCCESS'){
offerId = Utils.getOfferId(info)
console.log('OfferId', offerId)
}
} catch(ex) {
console.error(ex)
throw ex.message
} finally {
client?.disconnect()
}
return offerId
}
/**
* Verifies NFT belongs to account.
* Provides tx signature and gets signer.
* If signer matches NFT owner then is valid.
*
* @param {string} account - Account address claiming NFT ownership
* @param {string} tokenId - Id of NFT being verified
* @param {string} signature - Transaction signature to verify
* @throws {string} Throws error message
* @returns {boolean} Transaction was signed by token issuer
*/
async verifyNFT(account, tokenId, signature){
console.log('Verifying NFT', tokenId)
console.log('Belongs to', account)
try {
let token = await Utils.getToken(account, tokenId)
if(!token){ return false }
let result = verify(signature)
console.log('Signature', result)
if(result.signatureValid && result.signedBy == token.Issuer){
return true
}
} catch(ex) {
console.error(ex)
throw ex.message
}
return false
}
/**
* Lookups all accounts that own an NFT.
* EventId (token taxon) must be provided.
* Returns a list of accounts.
*
* @param {string} eventId - Token taxon that identifies an event
* @returns {array} - List of all NFTs for that event
*/
async lookupNFT(eventId){
console.log('Looking up NFTs...')
let list = []
// TODO: STAGE 2 Get all tokens with the same taxon
return list
}
}
/**
* Utility library to get info from XRPL ledger
*/
class Utils{
/**
* Gets account info of provided address.
* If not found returns null.
* If error returns error message.
*
* @param {string} account - Account address
* @param {object} client - XRPL client if already instantiated
* @returns {object} Account info
*/
static async getAccountInfo(account, client){
let close = false
try {
if(!client){
close = true
client = new xrpl.Client(config.network)
await client.connect()
}
let info = await client.request({
'command': 'account_info',
'account': account
})
return info
} catch(ex) {
console.error(ex)
return {error:ex.message}
} finally {
if(close && client){ client.disconnect() }
}
}
/**
* Used to get transaction info including token Id.
* Just pass the transaction hash.
* If not found will return null.
* If error in the process will return error object.
*
* @param {string} txid - Transaction Id to get info
* @throws {string} Throws error message
* @returns {object} Transaction info
*/
static async getTransaction(txid){
let result = null
try {
let opt = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({method: 'tx', params: [{transaction: txid, binary: false}]})
}
let res = await fetch(config.netrpc, opt)
let inf = await res.json()
return inf
} catch(ex) {
console.error(ex)
throw ex.message
}
}
/**
* After minting a token, parses the response to get the token Id.
* Loops all affected nodes looking for a token in final not in previous.
* If a node is found, that's the token Id freshly minted.
*
* @param {object} info - Transaction info to parse for token Id
* @returns {string} Token Id
*/
static parseTokenId(info){
let found = null
for (var i=0; i<info.result.meta.AffectedNodes.length; i++) {
let node = info.result.meta.AffectedNodes[i]
if(node.ModifiedNode && node.ModifiedNode.LedgerEntryType=='NFTokenPage'){
let m = node.ModifiedNode.FinalFields.NFTokens.length
let n = node.ModifiedNode.PreviousFields.NFTokens.length
for (var j=0; j<m; j++) {
let tokenId = node.ModifiedNode.FinalFields.NFTokens[j].NFToken.NFTokenID
found = tokenId
for (var k=0; k<n; k++) {
if(tokenId==node.ModifiedNode.PreviousFields.NFTokens[k].NFToken.NFTokenID){
found = null
break
}
}
if(found){ break }
}
}
if(found){ break }
}
return found
}
/**
* Returns token if found in account's token list.
* Needs account owner and token Id.
* Checks result for null or error when not found.
* Else result is token found.
*
* @param {string} account - Account owner to check token list
* @param {string} tokenId - Token Id to find
* @param {object} client - XRPL client if already instantiated
* @returns {type} Token info for token Id provided
*/
static async getToken(account, tokenId, client){
let found = null
let close = false
try {
if(!client){
close = true
client = new xrpl.Client(config.network)
await client.connect()
}
let nfts = await client.request({
method: 'account_nfts',
account: account,
limit: 400
})
for (var i = 0; i < nfts.result.account_nfts.length; i++) {
if(nfts.result.account_nfts[i].NFTokenID == tokenId){
found = nfts.result.account_nfts[i]
break;
}
}
while(!found && nfts.result.marker){
nfts = await client.request({
method: 'account_nfts',
account: account,
limit: 400,
marker: nfts.result.marker
})
for (var i = 0; i < nfts.result.account_nfts.length; i++) {
if(nfts.result.account_nfts[i].NFTokenID == tokenId){
found = item
break;
}
}
}
} catch(ex) {
console.error(ex)
} finally {
if(close && client){ client.disconnect() }
}
return found
}
/**
* Get the offerId after new sell/buy offer.
* Takes transaction response as input.
* Loop affected nodes and check for entry NFTokenOffer.
*
* @param {object} info - Offer info to parse for offer Id
* @returns {string} Offer Id
*/
static getOfferId(info){
for (var i = 0; i < info.result.meta.AffectedNodes.length; i++) {
let node = info.result.meta.AffectedNodes[i]
if(node.CreatedNode && node.CreatedNode.LedgerEntryType=='NFTokenOffer') { return node.CreatedNode.LedgerIndex }
}
}
/**
* Used to include event info as Memo in a token.
* Given an object it will loop for key:value pairs.
* Key:value pairs will be converted to hex as defined in Memo specs.
* Returns an array of Memo objects with MemoType:MemoData elements.
*
* @param {object} obj - Dictionary with key:value pairs
* @returns {array} Memo fields suitable for XRPL transactions
*/
static parseMemo(obj){
let res = []
for(var key in obj){
if(!obj[key]){ continue; }
let typ = xrpl.convertStringToHex(key)
let dat = xrpl.convertStringToHex(obj[key].toString())
if(dat){
res.push({Memo:{MemoType:typ, MemoData:dat}})
}
}
return res;
}
}
module.exports = Kollek
// END