-
Notifications
You must be signed in to change notification settings - Fork 12
/
v3.js
834 lines (684 loc) · 25.5 KB
/
v3.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
/**
*
*
*
*
*
* ██████╗░███████╗██████╗░███╗░░░███╗░█████╗░░█████╗░░█████╗░░██████╗████████╗
* ██╔══██╗██╔════╝██╔══██╗████╗░████║██╔══██╗██╔══██╗██╔══██╗██╔════╝╚══██╔══╝
* ██████╔╝█████╗░░██████╔╝██╔████╔██║███████║██║░░╚═╝███████║╚█████╗░░░░██║░░░
* ██╔═══╝░██╔══╝░░██╔══██╗██║╚██╔╝██║██╔══██║██║░░██╗██╔══██║░╚═══██╗░░░██║░░░
* ██║░░░░░███████╗██║░░██║██║░╚═╝░██║██║░░██║╚█████╔╝██║░░██║██████╔╝░░░██║░░░
* ╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝╚═╝░░╚═╝░╚════╝░╚═╝░░╚═╝╚═════╝░░░░╚═╝░░░
*
* SWC as first level data registery for Arweave hosted podcasts.
*
* @version TESTNET V3 - Amber Version
* @author charmful0x
* @website permacast.net
* @license MIT
**/
export async function handle(state, action) {
const input = action.input;
const caller = action.caller;
// STATE
const podcasts = state.podcasts;
const maintainers = state.maintainers;
const superAdmins = state.superAdmins;
const limitations = state.limitations;
const oracle_address = state.oracle_address;
// LIMITATION METADATA ACCESS
const POD_NAME_LIMITS = limitations["podcast_name_len"];
const POD_DESC_LIMITS = limitations["podcast_desc_len"];
const EP_NAME_LIMITS = limitations["episode_name_len"];
const EP_DESC_LIMITS = limitations["episode_desc_len"];
const AUTHOR_NAME_LIMITS = limitations["author_name_len"];
const LANG_CHAR_LIMITS = limitations["lang_char_code"];
const CATEGORY_LIMITS = limitations["categories"];
// ERRORS List
const ERROR_INVALID_CALLER =
"the caller is not allowed to execute this function";
const ERROR_INVALID_PRIMITIVE_TYPE =
"the given data is not a corrected primitive type per function";
const ERROR_INVALID_STRING_LENGTH =
"the string is out of the allowed length ranges";
const ERROR_NOT_A_DATA_TX = "the transaction is not an Arweave TX DATA";
const ERROR_MIME_TYPE = "the given mime type is not supported";
const ERROR_UNSUPPORTED_LANG = "the given language code is not supported";
const ERROR_REQUIRED_PARAMETER = "the function still require a parameter";
const ERROR_INVALID_NUMBER_TYPE = "only inetegers are allowed";
const ERROR_NEGATIVE_INTEGER =
"negative integer was supplied when only positive Intare allowed";
const ERROR_EPISODE_INDEX_NOT_FOUND =
"there is no episode with the given index";
const ERROR_PODCAST_INDEX_NOT_FOUND =
"there is no podcast with the given index";
const ERROR_OLD_VALUE_EQUAL_TO_NEW = "old valueand new value are equal";
const ERROR_MAINTAINER_ALREADY_ADDED =
"the address has been already added as maintainer";
const ERROR_MAINTAINER_NOT_FOUND =
"cannot find a mainatiner with the given address";
const ERROR_SUPER_ADMIN_ALREADY_ADDED =
"the given address has been already added as super admin";
const ERROR_SUPER_ADMIN_NOT_EXIST = "the given address is not a super admin";
const ERROR_V2_SRC_NOT_VALID = "the given factoryID does not have the V2 SRC";
const ERROR_MIGRATION_DONE = "the contract has already migrated a V2 state";
const ERROR_CANNOT_MIGRATE_TO_ACTIVE_FACTORY =
"this contract has been already activated - cannot override the state";
const ERROR_STATE_CANNOT_MIGRATE = "error while retrieving the V2 state";
const ERROR_PID_NOT_FOUND = "cannot find a podcast with the given PID";
const ERROR_EID_NOT_FOUND = "cannot find an episode with the given EID";
const ERROR_PID_OF_EID_NOT_FOUND = "cannot find a podcast with the given EID";
const ERROR_PODCAST_UPLOAD_DUPLICATED =
"auto-minimal protection from double podcast creation activated";
const ERROR_EPISODE_UPLOAD_DUPLICATED =
"auto-minimal protection from double episode uploads activated";
const ERROR_OWNER_ALREADY_SWAPPED =
"contract owner can be swapped one time only";
const ERROR_INVALID_ARWEAVE_ADDRESS = "invalid Arweave address";
if (input.function === "createPodcast") {
/**
* @dev create a podcast object and append it to
* the smart contract state. Only the factory's
* superAdmins have the permission to invoke it.
*
* @param name podcast name
* @param author podcast author
* @param lang language char code (ISO 639-1:2002)
* @param isExplicit indicates the existence of
* explicit content, used for RSS feed generating
* @param categories RSS supported categories strings
* @param email author email address
* @param cover Arweave data TXID of type `image/*`
* @param contentType 'a' or 'v' indication audio or
* video (content type) that will be supported in this podcast.
*
* @return state
**/
const name = input.name;
const author = input.author;
const lang = input.lang;
const isExplicit = input.isExplicit;
const categories = input.categories;
const email = input.email;
const cover = input.cover;
const contentType = input.contentType === "a" ? "audio/" : "video/"
await _isSuperAdmin(true, caller);
const pid = SmartWeave.transaction.id;
const desc = await _handleDescription(
pid,
POD_DESC_LIMITS.min,
POD_DESC_LIMITS.max
);
_validateStringTypeLen(name, POD_NAME_LIMITS.min, POD_NAME_LIMITS.max);
_validateStringTypeLen(
author,
AUTHOR_NAME_LIMITS.min,
AUTHOR_NAME_LIMITS.max
);
_validateStringTypeLen(email, 0, 320);
_validateStringTypeLen(
categories,
CATEGORY_LIMITS.min,
CATEGORY_LIMITS.max
);
_validateStringTypeLen(cover, 43, 43);
_validateStringTypeLen(lang, LANG_CHAR_LIMITS.min, LANG_CHAR_LIMITS.max);
// auto-prevent double podcast creation
_checkPodcastUploadDuplication(name);
await _validateDataTransaction(cover, "image/");
if (!["yes", "no"].includes(isExplicit)) {
throw new ContractError(ERROR_INVALID_PRIMITIVE_TYPE);
}
podcasts.push({
pid: pid,
contentType: contentType,
createdAtBlockheight: SmartWeave.block.height, // blockheight - V3 metadata
createdAt: SmartWeave.block.timestamp, // block's timestamp
index: _getPodcastIndex(), // id equals the index of the podacast obj in the podcasts array
childOf: SmartWeave.contract.id,
owner: caller,
podcastName: name,
author: author,
email: email,
description: desc,
language: lang,
explicit: isExplicit,
categories: categories.split(",").map((category) => category.trim()),
cover: cover,
isVisible: true,
episodes: [],
logs: [pid],
});
return { state };
}
if (input.function === "addEpisode") {
/**
* @dev create an episode object and append
* it to a podcast object's episodes array
* Maintainers and SuperAdmins can invoke
* this function.
*
* @param pid podcast ID (pid). 43 chars string
* @param name episode name
* @param content episode audio's or video's Arweave TXID
*
* @return state
**/
const pid = input.pid;
const name = input.name;
const content = input.content;
await _getMaintainers(true, caller);
const eid = SmartWeave.transaction.id;
// episode's description is extracted from the
// interaction's TX body data.
const desc = await _handleDescription(
eid,
EP_DESC_LIMITS.min,
EP_DESC_LIMITS.max
);
_validateStringTypeLen(name, EP_NAME_LIMITS.min, EP_NAME_LIMITS.max);
_validateStringTypeLen(content, 43, 43);
_validateStringTypeLen(pid, 43, 43);
const pidIndex = _getAndValidatePidIndex(pid);
// auto prevent double episode uploads
_checkEpisodeUploadDuplication(pidIndex, name);
const contentType = podcasts[pidIndex]["contentType"];
const TxMetadata = await _validateDataTransaction(content, contentType);
podcasts[pidIndex]["episodes"].push({
eid: SmartWeave.transaction.id,
childOf: pidIndex,
episodeName: name,
description: desc,
contentTx: content,
contentTxByteSize: Number.parseInt(TxMetadata.size),
type: TxMetadata.type,
uploader: caller,
uploadedAt: SmartWeave.block.timestamp,
uploadedAtBlockheight: SmartWeave.block.height, // V3 metadata
isVisible: true,
logs: [SmartWeave.transaction.id],
});
return { state };
}
// PODCAST ACTIONS:
// PERMISSIONED TO THE CONTRACT
// OWNER (DEPLOYER) ONLY
if (input.function === "updatePodcastMetadata") {
/**
* @dev update a podcast's object metadata that is
* already created. Only superAdmins can invoke it.
*
* @param name podcast name
* @param author podcast author
* @param lang language char code (ISO 639-1:2002)
* @param isExplicit indicates the existence of
* explicit content, used for RSS feed generating
* @param categories RSS supported categories strings
* @param email author email address
* @param cover Arweave data TXID of type `image/*`
*
* @return state
**/
const pid = input.pid;
const name = input.name;
const cover = input.cover;
const author = input.author;
const email = input.email;
const lang = input.lang;
const categories = input.categories;
const isExplicit = input.isExplicit;
// boolean - if true, get and validate
// the interaction body TX data ( text/* )
let desc = input.desc;
await _isSuperAdmin(true, caller);
const pidIndex = _getAndValidatePidIndex(pid);
const actionTx = SmartWeave.transaction.id;
if (name) {
_validateStringTypeLen(name, POD_NAME_LIMITS.min, POD_NAME_LIMITS.max);
podcasts[pidIndex]["podcastName"] = name;
}
if (desc) {
desc = await _handleDescription(
actionTx,
POD_DESC_LIMITS.min,
POD_DESC_LIMITS.max
);
podcasts[pidIndex]["description"] = desc;
}
if (author) {
_validateStringTypeLen(
author,
AUTHOR_NAME_LIMITS.min,
AUTHOR_NAME_LIMITS.max
);
podcasts[pidIndex]["author"] = author;
}
if (email) {
_validateStringTypeLen(email, 0, 320);
podcasts[pidIndex]["email"] = email;
}
if (lang) {
_validateStringTypeLen(lang, LANG_CHAR_LIMITS.min, LANG_CHAR_LIMITS.max);
podcasts[pidIndex]["language"] = lang;
}
if (categories) {
_validateStringTypeLen(
categories,
CATEGORY_LIMITS.min,
CATEGORY_LIMITS.max
);
podcasts[pidIndex]["categories"] = categories
.split(",")
.map((category) => category.trim());
}
if (isExplicit) {
if (!["yes", "no"].includes(isExplicit)) {
throw new ContractError(ERROR_INVALID_PRIMITIVE_TYPE);
}
podcasts[pidIndex]["explicit"] = isExplicit;
}
if (cover) {
await _validateDataTransaction(cover, "image/");
podcasts[pidIndex]["cover"] = cover;
}
podcasts[pidIndex]["logs"].push(actionTx);
return { state };
}
// PERMISSION: CONTRACT OWNER (DEPLOYER)
if (input.function === "addMaintainer") {
/**
* @dev add an address the the maintainers array.
* Only the contract owner (deployer) has permission.
*
* @param address the new maintainer address
*
* @return state
**/
const address = input.address;
await _getContractOwner(true, caller);
_validateAddress(address);
if (maintainers.includes(address)) {
throw new ContractError(ERROR_MAINTAINER_ALREADY_ADDED);
}
maintainers.push(address);
return { state };
}
if (input.function === "removeMaintainer") {
/**
* @dev remove a maintainer from the the maintainers array.
* Only the contract owner (deployer) has permission.
*
* @param address the address of to-remove maintainer
*
* @return state
**/
const address = input.address;
_validateAddress(address);
// a maintainer can remove himself or get removed by the sc owner
if (address !== caller && caller !== SmartWeave.contract.owner) {
throw new ContractError(ERROR_INVALID_CALLER);
}
if (!maintainers.includes(address)) {
throw new ContractError(ERROR_MAINTAINER_NOT_FOUND);
}
maintainers.splice(
maintainers.findIndex((m) => m === address),
1
);
return { state };
}
if (input.function === "addSuperAdmin") {
/**
* @dev add an address the the superAdmins array.
* Only the contract owner (deployer) has permission.
*
* @param address the new superAdmin address
*
* @return state
**/
const address = input.address;
await _getContractOwner(true, caller);
_validateAddress(address);
if (superAdmins.includes(address)) {
throw new ContractError(ERROR_SUPER_ADMIN_ALREADY_ADDED);
}
superAdmins.push(address);
return { state };
}
if (input.function === "removeSuperAdmin") {
/**
* @dev remove a superAdmin from the the superAdmins array.
* Only the contract owner (deployer) has permission.
*
* @param address the address of to-remove maintainer
*
* @return state
**/
const address = input.address;
_validateAddress(address);
// a superAdmin can remove himself or get removed by the sc owner
if (caller !== address && caller !== SmartWeave.contract.owner) {
throw new ContractError(ERROR_INVALID_CALLER);
}
if (!superAdmins.includes(address)) {
throw new ContractError(ERROR_SUPER_ADMIN_NOT_EXIST);
}
superAdmins.splice(
superAdmins.findIndex((m) => m === address),
1
);
return { state };
}
if (input.function === "reverseVisibility") {
/**
* @dev reverse the visibility of a podcast/episode.
* it just reverse a boolean value of the `isVisibile`
* property. The podcast/episode cannot be removed
* from the factory state.
*
* Only superAdmins can invoke this function.
*
* @param type is the object type, "eid" or "pid"
* @param id PID of type "pid" or EID of type "eid"
*
* @return state
*
**/
const type = input.type;
const id = input.id;
await _isSuperAdmin(true, caller);
if (type === "pid") {
const pidIndex = _getAndValidatePidIndex(id);
const currentVisibility = podcasts[pidIndex].isVisible;
podcasts[pidIndex].isVisible = !currentVisibility;
return { state };
}
if (type === "eid") {
const pid = _getPidOfEid(id);
const pidIndex = _getAndValidatePidIndex(pid);
const eidIndex = _getAndValidateEidIndex(id, pidIndex);
const currentVisibility =
podcasts[pidIndex]["episodes"][eidIndex].isVisible;
podcasts[pidIndex]["episodes"][eidIndex].isVisible = !currentVisibility;
return { state };
}
throw new ContractError(ERROR_INVALID_CALLER);
}
// EPISODES ACTIONS:
// PERMISSIONED TO THE CONTRACT
// OWNER AND MAINTAINERS
if (input.function === "updateEpisodeMetadata") {
/**
* @dev update the episode's metadata.
* Maintainers and SuperAdmins can invoke
* this function.
*
* @param eid episode ID (eid). 43 chars string
* @param name episode name
* @param audio episode audio's Arweave TXID
* @param desc is a boolean that's when set to true,
* the episode's description is extracted from the
* interaction TXID body data.
*
* @return state
*
**/
const eid = input.eid;
const name = input.name;
let desc = input.desc;
await _getMaintainers(true, caller);
const pid = _getPidOfEid(eid);
const pidIndex = _getAndValidatePidIndex(pid);
const eidIndex = _getAndValidateEidIndex(eid, pidIndex);
const actionTx = SmartWeave.transaction.id;
if (name) {
_validateStringTypeLen(name, EP_NAME_LIMITS.min, EP_NAME_LIMITS.max);
podcasts[pidIndex]["episodes"][eidIndex]["episodeName"] = name;
}
if (desc) {
desc = await _handleDescription(
actionTx,
EP_DESC_LIMITS.min,
EP_DESC_LIMITS.max
);
podcasts[pidIndex]["episodes"][eidIndex]["description"] = desc;
}
podcasts[pidIndex]["episodes"][eidIndex]["logs"].push(actionTx);
return { state };
}
if (input.function === "swapOwner") {
/**
* @dev this function is invoked one time only after V2 <> V3 migration
* the purpose of this function is to deploy & migrate V2 on behalf
* of the V2 factory owner, then give him/her back full ownership.
*
* @param address the address of the new contract owner.
*
* @return state
**/
const address = input.address;
_validateAddress(address);
await _isSuperAdmin(true, caller);
// contract owner can be swapped for once only
if (!state.ownerSwapped) {
SmartWeave.contract.owner = address;
state.ownerSwapped = true;
state.contractOwner = address;
return { state };
}
throw new ContractError(ERROR_OWNER_ALREADY_SWAPPED);
}
if (input.function === "fetchOracle") {
/**
* @dev read the oracle's state and update the limitations
* object of the factory (contract's state).
*
* @return state
*
**/
await _getContractOwner(true, caller);
const oracleState = await SmartWeave.contracts.readContractState(
state.oracle_address
);
// update the limitations according to the oracle;
state.limitations = oracleState.limitations;
return { state };
}
if (input.function === "updateOracleAddress") {
/**
* @dev contract owner can update the factory's
* oracle address to his/her own oracle. The initial
* factory's state come with an oracle provided from
* Permacast protocol developers. The new oracle state
* must be backward compatible with the original oracle,
*
* @param address the new oracle address
*
* @return state
*
**/
const address = input.address;
await _getContractOwner(true, caller);
_validateAddress(address);
state.oracle_address = address;
return { state };
}
// HELPER FUNCTIONS:
function _getPodcastIndex() {
if (podcasts.length === 0) {
return 0;
}
return podcasts.length;
}
function _validateAddress(address) {
_validateStringTypeLen(address, 43, 43);
if (!/[a-z0-9_-]{43}/i.test(address)) {
throw new ContractError(ERROR_INVALID_ARWEAVE_ADDRESS);
}
}
function _validateStringTypeLen(str, minLen, maxLen) {
if (typeof str !== "string") {
throw new ContractError(ERROR_INVALID_PRIMITIVE_TYPE);
}
if (str.trim().length < minLen || str.trim().length > maxLen) {
throw new ContractError(ERROR_INVALID_STRING_LENGTH);
}
}
function _validateInteger(number, allowNull) {
if (typeof allowNull === "undefined") {
throw new ContractError(ERROR_REQUIRED_PARAMETER);
}
if (!Number.isInteger(number)) {
throw new ContractError(ERROR_INVALID_NUMBER_TYPE);
}
if (allowNull) {
if (number < 0) {
throw new ContractError(ERROR_NEGATIVE_INTEGER);
}
} else if (number <= 0) {
throw new ContractError(ERROR_INVALID_NUMBER_TYPE);
}
}
async function _getContractOwner(validate, caller) {
const contractOwner = SmartWeave.contract.owner;
if (validate && contractOwner !== caller) {
throw new ContractError(ERROR_INVALID_CALLER);
}
}
async function _getMaintainers(validate, address) {
const superAdmins = await _isSuperAdmin(false);
const contractMaintainers = superAdmins.concat(maintainers);
// remove any address duplication amongst different privileges
const filteredMaintainers = Array.from(new Set(contractMaintainers));
if (validate && !filteredMaintainers.includes(address)) {
throw new ContractError(ERROR_INVALID_CALLER);
}
return filteredMaintainers;
}
async function _validateDataTransaction(tx, mimeType) {
const tagsMap = new Map();
const transaction = await SmartWeave.unsafeClient.transactions.get(tx);
const tags = transaction.get("tags");
for (let tag of tags) {
const key = tag.get("name", { decode: true, string: true });
const value = tag.get("value", { decode: true, string: true });
tagsMap.set(key, value);
}
if (!tagsMap.has("Content-Type")) {
throw new ContractError(ERROR_NOT_A_DATA_TX);
}
if (!tagsMap.get("Content-Type").startsWith(mimeType)) {
throw new ContractError(ERROR_MIME_TYPE);
}
return {
size: transaction.data_size,
type: tagsMap.get("Content-Type"),
};
}
function _validateEpisodeExistence(index, id) {
if (!podcasts[index]) {
throw new ContractError(ERROR_PODCAST_INDEX_NOT_FOUND);
}
if (!podcasts[index]["episodes"][id]) {
throw new ContractError(ERROR_EPISODE_INDEX_NOT_FOUND);
}
}
function _getAndValidatePidIndex(pid) {
const index = podcasts.findIndex((podcast) => podcast["pid"] === pid);
if (index >= 0) {
return index;
}
throw new ContractError(ERROR_PID_NOT_FOUND);
}
function _getAndValidateEidIndex(eid, pidIndex) {
const index = podcasts[pidIndex].episodes.findIndex(
(episode) => episode["eid"] === eid
);
if (index >= 0) {
return index;
}
throw new ContractError(ERROR_EID_NOT_FOUND);
}
function _getPidOfEid(eid) {
const pid = podcasts.find((podcast) =>
podcast.episodes.find((episode) => episode["eid"] === eid)
)?.["pid"];
if (!pid) {
throw new ContractError(ERROR_PID_OF_EID_NOT_FOUND);
}
return pid;
}
async function _isSuperAdmin(validate, address) {
const contractOwner = SmartWeave.contract.owner;
const allAdmins = superAdmins.concat(contractOwner);
// remove any address duplication amongst different privileges
const filteredSupers = Array.from(new Set(allAdmins));
if (validate && !filteredSupers.includes(address)) {
throw new ContractError(ERROR_INVALID_CALLER);
}
return filteredSupers;
}
function _checkPodcastUploadDuplication(name) {
const duplicationIndex = podcasts.findIndex(
(podcast) => podcast["podcastName"] === name
);
if (duplicationIndex === -1) {
return false;
}
const duplicationBlockheight =
podcasts[duplicationIndex]?.createdAtBlockheight;
// backward compatibility with V2 migrations
if (!duplicationBlockheight) {
return false;
}
if (duplicationBlockheight + 5 > SmartWeave.block.height) {
throw new ContractError(ERROR_PODCAST_UPLOAD_DUPLICATED);
}
return false;
}
function _checkEpisodeUploadDuplication(pidIndex, name) {
const duplicationIndex = podcasts[pidIndex].episodes.findIndex(
(episode) => episode["episodeName"] === name
);
if (duplicationIndex === -1) {
return false;
}
const duplicationBlockheight =
podcasts[pidIndex]["episodes"][duplicationIndex]?.uploadedAtBlockheight;
// backward compatibility with V2 migrations
if (!duplicationBlockheight) {
return false;
}
if (duplicationBlockheight + 5 > SmartWeave.block.height) {
throw new ContractError(ERROR_EPISODE_UPLOAD_DUPLICATED);
}
return false;
}
async function _handleDescription(txid, min, max) {
if (/[a-z0-9_-]{43}/i.test(txid)) {
const tagsMap = new Map();
const txObject = await SmartWeave.unsafeClient.transactions.get(txid);
const tags = txObject.get("tags");
for (let tag of tags) {
const key = tag.get("name", { decode: true, string: true });
const value = tag.get("value", { decode: true, string: true });
tagsMap.set(key, value);
}
if (!tagsMap.has("Content-Type")) {
throw new ContractError(ERROR_NOT_A_DATA_TX);
}
if (!tagsMap.get("Content-Type").startsWith("text/")) {
throw new ContractError(ERROR_MIME_TYPE);
}
const data = await SmartWeave.unsafeClient.transactions.getData(txid, {
decode: true,
string: true,
});
_validateStringTypeLen(data, min, max);
return data;
}
throw new ContractError(ERROR_INVALID_STRING_LENGTH);
}
throw new ContractError("unknow function supplied: ", input.function);
}