-
Notifications
You must be signed in to change notification settings - Fork 13
/
lit.ts
911 lines (801 loc) · 22 KB
/
lit.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
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
import { ethers, utils } from "ethers";
import fs from "fs";
import { RedisClientType } from "redis";
import config from "./config";
import redisClient from "./lib/redisClient";
import { AuthMethodType, PKP, StoreConditionWithSigner } from "./models";
import { Sequencer } from "./lib/sequencer";
import { parseEther } from "ethers/lib/utils";
import { CapacityToken } from "lit";
import { LIT_NETWORK_VALUES } from "@lit-protocol/constants";
// import {
// manzano,
// datilDev,
// datilTest,
// habanero,
// datil,
// } from "@lit-protocol/contracts";
import {
datil,
datilDev,
datilTest,
habanero,
manzano,
} from "@lit-protocol/contracts";
function getContractFromWorker(
network: LIT_NETWORK_VALUES,
contractName: string,
signer?: ethers.Wallet,
) {
signer = signer ?? getSigner();
let contractsDataRes;
switch (network) {
case "manzano":
contractsDataRes = manzano;
break;
case "habanero":
contractsDataRes = habanero;
break;
case "datil-dev":
contractsDataRes = datilDev;
break;
case "datil-test":
contractsDataRes = datilTest;
break;
case "datil":
contractsDataRes = datil;
break;
default:
throw new Error(`Unsupported network: ${network}`);
}
const contractList = contractsDataRes.data as any;
console.log(
`Attempting to get contract "${contractName} from "${network}"`,
);
// find object where name is == contractName
const contractData = contractList.find(
(contract: any) => contract.name === contractName,
);
// -- validate
if (!contractData) {
throw new Error(`No contract found with name ${contractName}`);
}
const contract = contractData.contracts[0];
console.log(`Contract address: ${contract.address_hash}"`);
// -- ethers contract
const ethersContract = new ethers.Contract(
contract.address_hash,
contract.ABI,
signer,
);
return ethersContract;
}
export function getProvider() {
return new ethers.providers.JsonRpcProvider(
process.env.LIT_TXSENDER_RPC_URL,
);
}
function getSigner() {
const provider = getProvider();
const privateKey = process.env.LIT_TXSENDER_PRIVATE_KEY!;
const signer = new ethers.Wallet(privateKey, provider);
return signer;
}
function getContract(abiPath: string, deployedContractAddress: string) {
const signer = getSigner();
const contractJson = JSON.parse(fs.readFileSync(abiPath, "utf8"));
let ethersContract;
// -- when passing in the API directly
try {
ethersContract = new ethers.Contract(
deployedContractAddress,
contractJson,
signer,
);
// -- when reading from a file which we have to access the ABI property
} catch (e) {
ethersContract = new ethers.Contract(
deployedContractAddress,
contractJson.abi,
signer,
);
}
return ethersContract;
}
function getAccessControlConditionsContract() {
switch (config.network) {
case "serrano":
return getContract(
"./contracts/serrano/AccessControlConditions.json",
config?.serranoContract
?.accessControlConditionsAddress as string,
);
case "cayenne":
return getContract(
"./contracts/cayenne/AccessControlConditions.json",
config?.cayenneContracts
?.accessControlConditionsAddress as string,
);
}
}
function getPkpHelperContractAbiPath() {
if (config.useSoloNet) {
return "./contracts/serrano/SoloNetPKPHelper.json";
}
switch (config.network) {
case "serrano":
return "./contracts/serrano/PKPHelper.json";
case "cayenne":
return "./contracts/cayenne/PKPHelper.json";
}
}
function getPkpNftContractAbiPath() {
if (config.useSoloNet) {
return "./contracts/serrano/SoloNetPKP.json";
}
switch (config.network) {
case "serrano":
return "./contracts/serrano/PKPNFT.json";
case "cayenne":
return "./contracts/cayenne/PKPNFT.json";
}
}
async function getPkpHelperContract(network: string) {
let contract: ethers.Contract | undefined;
switch (network) {
case "serrano":
contract = getContract(
getPkpHelperContractAbiPath()!,
config?.serranoContract?.pkpHelperAddress as string,
);
break;
case "cayenne":
contract = getContract(
getPkpHelperContractAbiPath()!,
config?.cayenneContracts?.pkpHelperAddress as string,
);
break;
case "manzano":
contract = getContractFromWorker("manzano", "PKPHelper");
break;
case "habanero":
contract = getContractFromWorker("habanero", "PKPHelper");
break;
case "datil-dev":
contract = getContractFromWorker("datil-dev", "PKPHelper");
break;
case "datil-test":
contract = getContractFromWorker("datil-test", "PKPHelper");
break;
case "datil":
contract = getContractFromWorker("datil", "PKPHelper");
break;
default:
throw new Error(`Unsupported network: ${network}`);
}
if (!contract) {
throw new Error("PKP Helper contract not available");
}
return contract;
}
async function getPermissionsContract() {
let contract: ethers.Contract | undefined;
switch (config.network) {
case "serrano":
contract = getContract(
"./contracts/serrano/PKPPermissions.json",
config?.serranoContract?.pkpPermissionsAddress as string,
);
break;
case "cayenne":
contract = getContract(
"./contracts/cayenne/PKPPermissions.json",
config?.cayenneContracts?.pkpPermissionsAddress as string,
);
break;
case "manzano":
contract = getContractFromWorker("manzano", "PKPPermissions");
break;
case "habanero":
contract = getContractFromWorker("habanero", "PKPPermissions");
break;
case "datil-dev":
contract = getContractFromWorker("datil-dev", "PKPPermissions");
break;
case "datil-test":
contract = getContractFromWorker("datil-test", "PKPPermissions");
break;
case "datil":
contract = getContractFromWorker("datil", "PKPPermissions");
break;
default:
throw new Error(`Unsupported network: ${config.network}`);
}
if (!contract) {
throw new Error("PKPPermissions contract not available");
}
return contract;
}
async function getPaymentDelegationContract() {
switch (config.network) {
case "manzano":
return getContractFromWorker("manzano", "PaymentDelegation");
case "habanero":
return getContractFromWorker("habanero", "PaymentDelegation");
default:
throw new Error(
"PaymentDelegation contract not available for this network",
);
}
}
async function getPkpNftContract(network: string) {
let contract: ethers.Contract | undefined;
switch (network) {
case "serrano":
contract = getContract(
getPkpNftContractAbiPath()!,
config?.serranoContract?.pkpNftAddress as string,
);
break;
case "cayenne":
contract = getContract(
getPkpNftContractAbiPath()!,
config?.cayenneContracts?.pkpNftAddress as string,
);
break;
case "manzano":
contract = getContractFromWorker("manzano", "PKPNFT");
break;
case "habanero":
contract = getContractFromWorker("habanero", "PKPNFT");
break;
case "datil-dev":
contract = getContractFromWorker("datil-dev", "PKPNFT");
break;
case "datil-test":
contract = getContractFromWorker("datil-test", "PKPNFT");
break;
case "datil":
contract = getContractFromWorker("datil", "PKPNFT");
break;
}
if (!contract) {
throw new Error("PKP NFT contract not available");
}
return contract;
}
function prependHexPrefixIfNeeded(hexStr: string) {
if (hexStr.substring(0, 2) === "0x") {
return hexStr;
}
return `0x${hexStr}`;
}
export async function getPkpEthAddress(tokenId: string) {
const pkpNft = await getPkpNftContract(config.network);
return pkpNft.getEthAddress(tokenId)!;
}
export async function getPkpPublicKey(tokenId: string) {
const pkpNft = await getPkpNftContract(config.network);
return pkpNft.getPubkey(tokenId);
}
export async function setSequencerWallet(
wallet: ethers.Wallet | ethers.providers.JsonRpcProvider,
) {
Sequencer.Wallet = wallet;
}
export async function storeConditionWithSigner(
storeConditionRequest: StoreConditionWithSigner,
): Promise<ethers.Transaction> {
console.log("Storing condition");
const accessControlConditions = getAccessControlConditionsContract();
const tx = accessControlConditions?.storeConditionWithSigner(
prependHexPrefixIfNeeded(storeConditionRequest.key),
prependHexPrefixIfNeeded(storeConditionRequest.value),
prependHexPrefixIfNeeded(storeConditionRequest.securityHash),
storeConditionRequest.chainId,
storeConditionRequest.permanent,
utils.getAddress(storeConditionRequest.creatorAddress),
);
console.log("tx", tx);
return tx;
}
export async function mintPKPV2({
keyType,
permittedAuthMethodTypes,
permittedAuthMethodIds,
permittedAuthMethodPubkeys,
permittedAuthMethodScopes,
addPkpEthAddressAsPermittedAddress,
sendPkpToItself,
}: {
keyType: string;
permittedAuthMethodTypes: string[];
permittedAuthMethodIds: string[];
permittedAuthMethodPubkeys: string[];
permittedAuthMethodScopes: string[][];
addPkpEthAddressAsPermittedAddress: boolean;
sendPkpToItself: boolean;
}): Promise<ethers.Transaction> {
console.log(
"In mintPKPV2",
keyType,
permittedAuthMethodTypes,
permittedAuthMethodIds,
permittedAuthMethodPubkeys,
permittedAuthMethodScopes,
addPkpEthAddressAsPermittedAddress,
sendPkpToItself,
);
const pkpHelper = await getPkpHelperContract(config.network);
const pkpNft = await getPkpNftContract(config.network);
// first get mint cost
const mintCost = await pkpNft.mintCost();
const mintTxData =
await pkpHelper.populateTransaction.mintNextAndAddAuthMethods(
keyType,
permittedAuthMethodTypes,
permittedAuthMethodIds,
permittedAuthMethodPubkeys,
permittedAuthMethodScopes,
addPkpEthAddressAsPermittedAddress,
sendPkpToItself,
{ value: mintCost },
);
// on our new arb l3, the stylus gas estimation can be too low when interacting with stylus contracts. manually estimate gas and add 5%.
let gasLimit;
try {
gasLimit = await pkpNft.provider.estimateGas(mintTxData);
// since the gas limit is a BigNumber we have to use integer math and multiply by 200 then divide by 100 instead of just multiplying by 1.05
gasLimit = gasLimit
.mul(
ethers.BigNumber.from(
parseInt(process.env["GAS_LIMIT_INCREASE_PERCENTAGE"]!) ||
200,
),
)
.div(ethers.BigNumber.from(100));
console.log("adjustedGasLimit:", gasLimit);
} catch (e) {
console.error("❗️ Error while estimating gas, using default");
gasLimit = ethers.utils.hexlify(5000000);
}
try {
const tx = await pkpHelper.mintNextAndAddAuthMethods(
keyType,
permittedAuthMethodTypes,
permittedAuthMethodIds,
permittedAuthMethodPubkeys,
permittedAuthMethodScopes,
addPkpEthAddressAsPermittedAddress,
sendPkpToItself,
{ value: mintCost, gasLimit: gasLimit },
);
await tx.wait();
console.log("tx", tx);
return tx;
} catch (e: any) {
console.log("❗️ Error while minting pkp:", e);
throw e;
}
}
export async function mintPKP({
authMethodType,
authMethodId,
authMethodPubkey,
}: {
authMethodType: AuthMethodType;
authMethodId: string;
authMethodPubkey: string;
}): Promise<ethers.Transaction> {
console.log("in mintPKP");
const pkpHelper = await getPkpHelperContract(config.network);
const pkpNft = await getPkpNftContract(config.network);
// first get mint cost
const mintCost = await pkpNft.mintCost();
const sequencer = Sequencer.Instance;
Sequencer.Wallet = getSigner();
// then, mint PKP using helper
if (config.useSoloNet) {
console.info("Minting PKP against SoloNet PKPHelper contract", {
authMethodType,
authMethodId,
authMethodPubkey,
});
// Get next unminted PKP pubkey.
const pkpPubkeyForPkpNft = await getNextAvailablePkpPubkey(redisClient);
const tx = await sequencer
.wait({
action: pkpHelper.mintAndAddAuthMethods,
params: [
pkpPubkeyForPkpNft, // In SoloNet, we choose which PKP pubkey we would like to attach to the minted PKP.
[authMethodType],
[authMethodId],
[authMethodPubkey],
[[ethers.BigNumber.from(1)]],
true,
false,
],
transactionData: { value: mintCost },
})
.catch((e) => {
console.error("Error while minting pkp", e);
});
console.log("tx", tx);
return tx;
} else {
console.info("Minting PKP against PKPHelper contract", {
authMethodType,
authMethodId,
authMethodPubkey,
});
const tx = await sequencer.wait({
action: pkpHelper.mintNextAndAddAuthMethods,
params: [
2,
[authMethodType],
[authMethodId],
[authMethodPubkey],
[[ethers.BigNumber.from(1)]],
true,
true,
],
transactionData: { value: mintCost },
});
console.log("tx", tx);
return tx;
}
}
export async function claimPKP({
keyId,
signatures,
authMethodType,
authMethodId,
authMethodPubkey,
}: {
keyId: string;
signatures: ethers.Signature[];
authMethodType: AuthMethodType;
authMethodId: string;
authMethodPubkey: string;
}): Promise<ethers.Transaction> {
console.log("in claimPKP");
const pkpHelper = await getPkpHelperContract(config.network);
const pkpNft = await getPkpNftContract(config.network);
// first get mint cost
const mintCost = await pkpNft.mintCost();
const sequencer = Sequencer.Instance;
Sequencer.Wallet = getSigner();
// then, mint PKP using helper
if (config.useSoloNet) {
console.info("Minting PKP against SoloNet PKPHelper contract", {
authMethodType,
authMethodId,
authMethodPubkey,
});
// Get next unminted PKP pubkey.
const pkpPubkeyForPkpNft = await getNextAvailablePkpPubkey(redisClient);
const tx = await sequencer
.wait({
action: pkpHelper.mintAndAddAuthMethods,
params: [
pkpPubkeyForPkpNft, // In SoloNet, we choose which PKP pubkey we would like to attach to the minted PKP.
[authMethodType],
[authMethodId],
[authMethodPubkey],
[[ethers.BigNumber.from("1")]],
true,
false,
],
transactionData: { value: mintCost },
})
.catch((e) => {
console.error("Error while minting pkp", e);
});
console.log("tx", tx);
return tx;
} else {
console.info("Minting PKP against PKPHelper contract", {
authMethodType,
authMethodId,
authMethodPubkey,
});
let tx = await sequencer.wait({
action: pkpHelper.claimAndMintNextAndAddAuthMethods,
params: [
[2, `0x${keyId}`, signatures],
[
2,
[],
[],
[],
[],
[authMethodType],
[`0x${authMethodId}`],
[authMethodPubkey],
[[ethers.BigNumber.from(1)]],
],
],
transactionData: { value: mintCost },
});
console.log("tx", tx);
return tx;
}
}
export async function getPKPsForAuthMethod({
authMethodType,
idForAuthMethod,
}: {
authMethodType: AuthMethodType;
idForAuthMethod: string;
}) {
if (!authMethodType || !idForAuthMethod) {
throw new Error(
"Auth method type and id are required to fetch PKPs by auth method",
);
}
const pkpPermissions = await getPermissionsContract();
if (pkpPermissions) {
try {
const tokenIds = await pkpPermissions.getTokenIdsForAuthMethod(
authMethodType,
idForAuthMethod,
);
const pkps: PKP[] = [];
for (let i = 0; i < tokenIds.length; i++) {
const pubkey = await pkpPermissions.getPubkey(tokenIds[i]);
if (pubkey) {
const ethAddress = ethers.utils.computeAddress(pubkey);
pkps.push({
tokenId: tokenIds[i],
publicKey: pubkey,
ethAddress: ethAddress,
});
}
}
return pkps;
} catch (err) {
throw new Error("Unable to get PKPs for auth method");
}
} else {
throw new Error("Unable to connect to PKP Permissions contract");
}
}
export async function getPubkeyForAuthMethod({
authMethodType,
authMethodId,
}: {
authMethodType: AuthMethodType;
authMethodId: string;
}): Promise<string> {
const permissionsContract = await getPermissionsContract();
const pubkey = permissionsContract.getUserPubkeyForAuthMethod(
authMethodType,
authMethodId,
);
return pubkey;
}
export async function sendLitTokens(
recipientPublicKey: string,
amount: string,
) {
const signer = getSigner();
const tx = await signer.sendTransaction({
to: recipientPublicKey,
value: parseEther(amount),
});
const reciept = await tx.wait();
console.log("Sent LIT tokens", reciept.blockHash);
return reciept.blockHash;
}
export async function mintCapacityCredits({
signer,
}: {
signer: ethers.Wallet;
}) {
if (config.network === "serrano" || config.network === "cayenne") {
throw new Error(
`Payment delegation is not available on ${config.network}`,
);
}
const contract = await getContractFromWorker(
config.network,
"RateLimitNFT",
signer,
);
if (!contract) {
throw new Error("Contract is not available");
}
// set the expiration to midnight, 15 days from now
const timestamp = Date.now() + 15 * 24 * 60 * 60 * 1000;
const futureDate = new Date(timestamp);
futureDate.setUTCHours(0, 0, 0, 0);
// Get the Unix timestamp in seconds
const expires = Math.floor(futureDate.getTime() / 1000);
console.log("expires is set to", expires);
const requestsPerKilosecond = 150;
let cost;
try {
cost = await contract.functions.calculateCost(
requestsPerKilosecond,
expires,
);
} catch (e) {
console.error(
"Unable to estimate gas cost for minting capacity credits",
e,
);
return;
}
const tx = await contract.functions.mint(expires, {
value: cost.toString(),
});
console.log("mint tx hash: ", tx.hash);
const res = await tx.wait();
const tokenIdFromEvent = res.events[0].topics[3];
return { tx, capacityTokenId: tokenIdFromEvent };
}
function normalizeTokenURI(tokenURI: string) {
const base64 = tokenURI[0];
const data = base64.split("data:application/json;base64,")[1];
const dataToString = Buffer.from(data, "base64").toString("binary");
return JSON.parse(dataToString);
}
function normalizeCapacity(capacity: any) {
const [requestsPerMillisecond, expiresAt] = capacity[0];
return {
requestsPerMillisecond: parseInt(requestsPerMillisecond.toString()),
expiresAt: {
timestamp: parseInt(expiresAt.toString()),
},
};
}
async function queryCapacityCredit(
contract: ethers.Contract,
owner: string,
tokenIndexForUser: number,
) {
console.log(
`Querying capacity credit for owner ${owner} at index ${tokenIndexForUser}`,
);
const tokenId = (
await contract.functions.tokenOfOwnerByIndex(owner, tokenIndexForUser)
).toString();
console.log(`Actually querying tokenId ${tokenId}`);
try {
const [URI, capacity, isExpired] = await Promise.all([
contract.functions.tokenURI(tokenId).then(normalizeTokenURI),
contract.functions.capacity(tokenId).then(normalizeCapacity),
contract.functions.isExpired(tokenId),
]);
return {
tokenId,
URI,
capacity,
isExpired: isExpired[0],
} as CapacityToken;
} catch (e) {
// Makes the stack trace a bit more clear as to what actually failed
throw new Error(
`Failed to fetch details for capacity token ${tokenId}: ${e}`,
);
}
}
export async function queryCapacityCredits(signer: ethers.Wallet) {
if (config.network === "serrano" || config.network === "cayenne") {
throw new Error(
`Payment delegation is not available on ${config.network}`,
);
}
const contract = await getContractFromWorker(
config.network,
"RateLimitNFT",
);
const count = parseInt(await contract.functions.balanceOf(signer.address));
return Promise.all(
[...new Array(count)].map((_, i) =>
queryCapacityCredit(contract, signer.address, i),
),
) as Promise<CapacityToken[]>;
}
export async function addPaymentDelegationPayee({
wallet,
payeeAddresses,
}: {
wallet: ethers.Wallet;
payeeAddresses: string[];
}) {
if (config.network === "serrano" || config.network === "cayenne") {
throw new Error(
`Payment delegation is not available on ${config.network}`,
);
}
// get the first token that is not expired
const capacityTokens: CapacityToken[] = await queryCapacityCredits(wallet);
console.log("Got capacity tokens", JSON.stringify(capacityTokens, null, 2));
const capacityToken = capacityTokens.find((token) => !token.isExpired);
let tokenId: number | null = null;
if (!capacityToken) {
// mint a new token
const minted = await mintCapacityCredits({ signer: wallet });
if (!minted) {
throw new Error("Failed to mint capacity credits");
}
console.log(
"No capacity token found, minted a new one:",
minted.capacityTokenId,
);
tokenId = minted.capacityTokenId;
} else {
tokenId = capacityToken.tokenId;
}
if (!tokenId) {
throw new Error("Failed to get ID for capacity token");
}
// add payer in contract
const provider = getProvider();
const paymentDelegationContract = await getContractFromWorker(
config.network,
"PaymentDelegation",
wallet,
);
const tx = await paymentDelegationContract.functions.delegatePaymentsBatch(
payeeAddresses,
);
console.log("tx hash for delegatePaymentsBatch()", tx.hash);
await tx.wait();
return tx;
}
// export function packAuthData({
// credentialPublicKey,
// credentialID,
// counter,
// }: {
// credentialPublicKey: Buffer;
// credentialID: Buffer;
// counter: number;
// }): Buffer {
// // mint a PKP for this user
// // first, pack the credential public key, credential id, and counter into bytes
// const formattedJson = JSON.stringify({
// pubkey: credentialPublicKey.toString("base64"),
// cid: credentialID.toString("base64"),
// counter,
// });
// console.log("formattedJson", formattedJson);
// const packed = Buffer.from(formattedJson, "utf8");
// console.log("packed", packed);
// return packed;
// }
/**
* This function returns the next available PKP that can be minted. Specifically,
*
* 1. Gets 1 unminted PKP from the data store - eg. ZRANGEBYSCORE myzset 0 0 LIMIT 0 1
* (assuming all unminted PKPs have a score of 0)
* 2. Sets the score of the PKP to 1 to mark it as "used", optimistically - eg. ZADD myzset 1 0x1234
* 3. Returns the PKP public key.
*/
export async function getNextAvailablePkpPubkey(redisClient: RedisClientType) {
// 1. Get 1 unminted PKP from the data store
const unmintedPkpPubkey = await redisClient.zRangeByScore(
"pkp_public_keys",
0,
0,
{
LIMIT: {
offset: 0,
count: 1,
},
},
);
if (unmintedPkpPubkey.length === 0) {
throw new Error("No more PKPs available");
}
const unmintedPkpPubkeyToUse = unmintedPkpPubkey[0];
// 2. Set the score of the PKP to 1 to mark it as "used", optimistically
await redisClient.zAdd("pkp_public_keys", {
score: 1,
value: unmintedPkpPubkeyToUse,
});
// 3. Return the PKP public key
return unmintedPkpPubkeyToUse;
}