Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merg #126

Merged
merged 9 commits into from
May 25, 2024
Merged

Merg #126

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@
"@didtools/cacao": "^3.0.1",
"@elastic/elasticsearch": "^8.6.0",
"@ethersproject/keccak256": "^5.7.0",
"@lit-protocol/contracts-sdk": "5.0.0",
"@lit-protocol/lit-node-client-nodejs": "5.0.0",
"@lit-protocol/auth-helpers": "6.0.0-beta.4",
"@lit-protocol/contracts-sdk": "6.0.0-beta.4",
"@lit-protocol/lit-node-client-nodejs": "6.0.0-beta.4",
"@lit-protocol/pkp-ethers": "^5.0.0",
"@lit-protocol/types": "6.0.0-beta.4",
"@lit-protocol/uint8arrays": "4.1.1",
"@mailchimp/mailchimp_marketing": "^3.0.80",
"@pinata/sdk": "^2.1.0",
Expand Down
103 changes: 54 additions & 49 deletions api/src/libs/lit/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,61 +382,66 @@ export const getPKPSessionForIndexer = async (index) => {
};

export const mintPKP = async (ownerAddress, actionCID) => {
const signer = new ethers.Wallet(
process.env.INDEXER_WALLET_PRIVATE_KEY,
provider,
);

const litContracts = new LitContracts({
network: config.litNetwork,
signer: signer,
debug: false,
});
if (!litContracts.connected) {
await litContracts.connect();
}

const signerFunctionV0 = CID.parse(actionCID).toV0().toString();
const acid = litContracts.utils.getBytesFromMultihash(signerFunctionV0);

const mintCost = await litContracts.pkpNftContract.read.mintCost();
const mint =
await litContracts.pkpHelperContract.write.mintNextAndAddAuthMethods(
2,
[AuthMethodType.EthWallet, AuthMethodType.LitAction],
[ownerAddress.toLowerCase(), acid],
["0x", "0x"],
[[BigInt(1)], [BigInt(1)]],
true,
true,
{
value: mintCost,
},
try {
const signer = new ethers.Wallet(
process.env.INDEXER_WALLET_PRIVATE_KEY,
provider,
);
const wait = await mint.wait(1);

/* eslint-disable */
const tokenIdFromEvent = wait?.logs
? wait.logs[0].topics[1]
: wait?.logs[0].topics[1];
const tokenIdNumber = BigInt(tokenIdFromEvent).toString();
const pkpPublicKey =
await litContracts.pkpNftContract.read.getPubkey(tokenIdFromEvent);
const litContracts = new LitContracts({
network: config.litNetwork,
signer: signer,
debug: false,
});
if (!litContracts.connected) {
await litContracts.connect();
}

const signerFunctionV0 = CID.parse(actionCID).toV0().toString();
const acid = litContracts.utils.getBytesFromMultihash(signerFunctionV0);

const mintCost = await litContracts.pkpNftContract.read.mintCost();
console.log(mintCost, `mintcost`);
const mint =
await litContracts.pkpHelperContract.write.mintNextAndAddAuthMethods(
2,
[AuthMethodType.EthWallet, AuthMethodType.LitAction],
[ownerAddress.toLowerCase(), acid],
["0x", "0x"],
[[BigInt(1)], [BigInt(1)]],
true,
true,
{
value: mintCost,
},
);
const wait = await mint.wait(1);
console.log(wait);
/* eslint-disable */
const tokenIdFromEvent = wait?.logs
? wait.logs[0].topics[1]
: wait?.logs[0].topics[1];
const tokenIdNumber = BigInt(tokenIdFromEvent).toString();
const pkpPublicKey =
await litContracts.pkpNftContract.read.getPubkey(tokenIdFromEvent);

const pubKeyToAddr = await import("ethereum-public-key-to-address");
sendLit(pubKeyToAddr.default(pkpPublicKey), "0.0001"); //Run in the background
const pubKeyToAddr = await import("ethereum-public-key-to-address");
sendLit(pubKeyToAddr.default(pkpPublicKey), "0.0001"); //Run in the background

console.log("Minted and loaded!");
console.log("Minted and loaded!");

console.log(
`superlog, PKP public key is ${pkpPublicKey} and Token ID is ${tokenIdFromEvent} and Token ID number is ${tokenIdNumber}`,
);
console.log(
`superlog, PKP public key is ${pkpPublicKey} and Token ID is ${tokenIdFromEvent} and Token ID number is ${tokenIdNumber}`,
);

return {
tokenIdFromEvent,
tokenIdNumber,
pkpPublicKey,
};
return {
tokenIdFromEvent,
tokenIdNumber,
pkpPublicKey,
};
} catch (e) {
console.log(e);
}
};

const delay = async (ms) => {
Expand Down
102 changes: 48 additions & 54 deletions api/src/packages/indexer_auth_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@ import { Wallet, ethers } from "ethers";
import * as LitJsSdk from "@lit-protocol/lit-node-client-nodejs";
import { LitContracts } from "@lit-protocol/contracts-sdk";
import {
LitAbility,
LitPKPResource,
LitActionResource,
generateAuthSig,
createSiweMessageWithRecaps,
} from "@lit-protocol/auth-helpers";
import { LitAbility } from "@lit-protocol/types";

import { DIDSession, createDIDCacao, createDIDKey } from "did-session";
import { Cacao, SiweMessage } from "@didtools/cacao";
import { randomBytes, randomString } from "@stablelib/random";

import RedisClient from "../clients/redis.js";
import { generateLITAction } from "../utils/helpers.js";
import { fetchModelInfo, generateLITAction } from "../utils/helpers.js";

// Configuration
const config = {
Expand Down Expand Up @@ -96,71 +98,57 @@ async function mintNewCapacityToken() {
return capacityTokenIdStr;
}

async function authNeededCallback({ resources, expiration, uri }) {
// you can change this resource to anything you would like to specify
const litResource = new LitActionResource("*");

const recapObject =
await litNodeClient.generateSessionCapabilityObjectWithWildcards([
litResource,
]);

recapObject.addCapabilityForResource(
litResource,
LitAbility.LitActionExecution,
);

const verified = recapObject.verifyCapabilitiesForResource(
litResource,
LitAbility.LitActionExecution,
);

if (!verified) {
throw new Error("Failed to verify capabilities for resource");
}

let siweMessage = new SiweMessage({
domain: "index.network", // change to your domain ex: example.app.com
address: indexerWallet.address,
statement: "Index Network says: ", // configure to what ever you would like
uri,
version: "1",
chainId: "1",
expirationTime: expiration,
resources,
});

siweMessage = recapObject.addToSiweMessage(siweMessage);

const messageToSign = siweMessage.toMessage();
const signature = await indexerWallet.signMessage(messageToSign);

const authSig = {
sig: signature,
derivedVia: "web3.eth.personal.sign",
signedMessage: messageToSign,
address: indexerWallet.address,
};

return authSig;
}

async function generateAndStoreAuthSigs(capacityTokenId) {
console.log("Generating and storing authorization signatures...");
const { capacityDelegationAuthSig } =
await litNodeClient.createCapacityDelegationAuthSig({
dAppOwnerWallet: indexerWallet,
delegateeAddresses: [indexerWallet.address],
capacityTokenId: capacityTokenId,
expiration: thirtyDaysLater.toISOString(),
});

const latestBlockhash = await litNodeClient.getLatestBlockhash();
console.log("latestBlockhash:", latestBlockhash);

const dAppSessionSigs = await litNodeClient.getSessionSigs({
expiration: thirtyDaysLater.toISOString(),
chain: "ethereum",
resourceAbilityRequests: [
{ resource: new LitPKPResource("*"), ability: LitAbility.PKPSigning },
{
resource: new LitActionResource("*"),
ability: LitAbility.LitActionExecution,
},
],
authNeededCallback: authNeededCallback,
authNeededCallback: async (params) => {
if (!params.uri) {
throw new Error("uri is required");
}
if (!params.expiration) {
throw new Error("expiration is required");
}

if (!params.resourceAbilityRequests) {
throw new Error("resourceAbilityRequests is required");
}

const toSign = await createSiweMessageWithRecaps({
uri: params.uri,
expiration: params.expiration,
resources: params.resourceAbilityRequests,
walletAddress: indexerWallet.address,
nonce: latestBlockhash,
litNodeClient,
});

const authSig = await generateAuthSig({
signer: indexerWallet,
toSign,
});

return authSig;
},
capacityDelegationAuthSig,
});

Expand Down Expand Up @@ -214,6 +202,7 @@ async function scheduleTokenRefresh() {
console.log("Current capacity token is still valid. No action needed.");
}
} catch (error) {
console.log(error);
process.exit(1);
}
}
Expand All @@ -237,7 +226,12 @@ async function generateDefaultLitActions() {
},
},
];
const defaultCID = await generateLITAction(defaultConditions);

let { runtimeDefinition } = await fetchModelInfo();
const defaultCID = await generateLITAction(
defaultConditions,
runtimeDefinition,
);
console.log("Default CID", defaultCID);
}

Expand Down Expand Up @@ -281,4 +275,4 @@ async function run() {
process.exit(0);
}

generateDefaultLitActions();
run();
Loading
Loading