forked from LIT-Protocol/relay-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlit.ts
276 lines (249 loc) · 7 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
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";
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"));
const ethersContract = new ethers.Contract(
deployedContractAddress,
contractJson,
signer,
);
return ethersContract;
}
function getAccessControlConditionsContract() {
return getContract(
"./contracts/AccessControlConditions.json",
config.accessControlConditionsAddress,
);
}
function getPkpHelperContractAbiPath() {
if (config.useSoloNet) {
return "./contracts/SoloNetPKPHelper.json";
}
return "./contracts/PKPHelper.json";
}
function getPkpNftContractAbiPath() {
if (config.useSoloNet) {
return "./contracts/SoloNetPKP.json";
}
return "./contracts/PKPNFT.json";
}
function getPkpHelperContract() {
return getContract(getPkpHelperContractAbiPath(), config.pkpHelperAddress);
}
function getPermissionsContract() {
return getContract(
"./contracts/PKPPermissions.json",
config.pkpPermissionsAddress,
);
}
function getPkpNftContract() {
return getContract(getPkpNftContractAbiPath(), config.pkpNftAddress);
}
function prependHexPrefixIfNeeded(hexStr: string) {
if (hexStr.substring(0, 2) === "0x") {
return hexStr;
}
return `0x${hexStr}`;
}
export async function getPkpEthAddress(tokenId: string) {
const pkpNft = getPkpNftContract();
return pkpNft.getEthAddress(tokenId);
}
export async function getPkpPublicKey(tokenId: string) {
const pkpNft = getPkpNftContract();
return pkpNft.getPubkey(tokenId);
}
export async function storeConditionWithSigner(
storeConditionRequest: StoreConditionWithSigner,
): Promise<ethers.Transaction> {
console.log("Storing condition");
const accessControlConditions = getAccessControlConditionsContract();
const tx = await 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 mintPKP({
authMethodType,
authMethodId,
authMethodPubkey,
}: {
authMethodType: AuthMethodType;
authMethodId: string;
authMethodPubkey: string;
}): Promise<ethers.Transaction> {
console.log("in mintPKP");
const pkpHelper = getPkpHelperContract();
const pkpNft = getPkpNftContract();
// first get mint cost
const mintCost = await pkpNft.mintCost();
// 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 pkpHelper.mintAndAddAuthMethods(
pkpPubkeyForPkpNft, // In SoloNet, we choose which PKP pubkey we would like to attach to the minted PKP.
[authMethodType],
[authMethodId],
[authMethodPubkey],
[[ethers.BigNumber.from("0")]],
true,
false,
{ value: mintCost },
);
console.log("tx", tx);
return tx;
} else {
console.info("Minting PKP against PKPHelper contract", {
authMethodType,
authMethodId,
authMethodPubkey,
});
const tx = await pkpHelper.mintNextAndAddAuthMethods(
2,
[authMethodType],
[authMethodId],
[authMethodPubkey],
[[ethers.BigNumber.from("0")]],
true,
true,
{ 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 = 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 = getPermissionsContract();
const pubkey = permissionsContract.getUserPubkeyForAuthMethod(
authMethodType,
authMethodId,
);
return pubkey;
}
// 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;
}