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

Init using Fetch within a Lit Action example #6

Merged
merged 7 commits into from
May 7, 2024
Merged
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
1 change: 1 addition & 0 deletions lit-action-using-fetch/browser/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PKP_PUBLIC_KEY=
4 changes: 4 additions & 0 deletions lit-action-using-fetch/browser/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.env
.cache
dist
node_modules
8 changes: 8 additions & 0 deletions lit-action-using-fetch/browser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Running this Example

1. `yarn`
2. `yarn start`
3. Click the `Click Me` button
4. Connect your wallet
5. Sign a message to generate a SessionSig
6. The PKP signed message will be in the JavaScript console
22 changes: 22 additions & 0 deletions lit-action-using-fetch/browser/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "lit-action-using-fetch-browser",
"version": "0.1.0",
"description": "Example of executing a Lit Action that makes a API request using Fetch",
"source": "src/index.html",
"license": "MIT",
"scripts": {
"start": "parcel ./src/index.html"
},
"dependencies": {
"@dotenvx/dotenvx": "^0.37.1",
"@lit-protocol/auth-browser": "^6.0.0-alpha.11",
"@lit-protocol/auth-helpers": "^6.0.0-alpha.11",
"@lit-protocol/constants": "^6.0.0-alpha.11",
"@lit-protocol/contracts-sdk": "^6.0.0-alpha.11",
"@lit-protocol/lit-node-client": "^6.0.0-alpha.11",
"ethers": "5.7.2"
},
"devDependencies": {
"parcel-bundler": "^1.12.5"
}
}
12 changes: 12 additions & 0 deletions lit-action-using-fetch/browser/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lit Session Signature Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script src="./index.js"></script>
</body>
</html>
130 changes: 130 additions & 0 deletions lit-action-using-fetch/browser/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { LitNodeClient } from "@lit-protocol/lit-node-client";
import { LitNetwork } from "@lit-protocol/constants";
import {
createSiweMessageWithRecaps,
generateAuthSig,
LitAbility,
LitActionResource,
LitPKPResource,
} from "@lit-protocol/auth-helpers";
import { LitContracts } from "@lit-protocol/contracts-sdk";
import { disconnectWeb3 } from "@lit-protocol/auth-browser";
import * as ethers from "ethers";

import { litActionCode } from "./litAction";

document.addEventListener("DOMContentLoaded", () => {
document.getElementById("myButton").addEventListener("click", buttonClick);
});

async function buttonClick() {
try {
console.log("Clicked");

const provider = new ethers.providers.Web3Provider(window.ethereum);
await provider.send("eth_requestAccounts", []);
const ethersSigner = provider.getSigner();
console.log("Connected account:", await ethersSigner.getAddress());

const litNodeClient = await getLitNodeClient();

const sessionSigs = await getSessionSigs(litNodeClient, ethersSigner);
console.log("Got Session Signatures!");

const message = new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode("Hello world")
)
);
const litActionSignatures = await litNodeClient.executeJs({
sessionSigs,
code: litActionCode,
jsParams: {
toSign: message,
publicKey: await getPkpPublicKey(),
sigName: "sig",
},
});
console.log("litActionSignatures: ", litActionSignatures);
} catch (error) {
console.error(error);
} finally {
disconnectWeb3();
}
}

async function getLitNodeClient() {
const litNodeClient = new LitNodeClient({
litNetwork: LitNetwork.Cayenne,
});

console.log("Connecting litNodeClient to network...");
await litNodeClient.connect();

console.log("litNodeClient connected!");
return litNodeClient;
}

async function getPkpPublicKey(ethersSigner) {
if (
process.env.PKP_PUBLIC_KEY !== undefined &&
process.env.PKP_PUBLIC_KEY !== ""
)
return process.env.PKP_PUBLIC_KEY;

const pkp = await mintPkp(ethersSigner);
console.log("Minted PKP!", pkp);
return pkp.publicKey;
}

async function mintPkp(ethersSigner) {
console.log("Minting new PKP...");
const litContracts = new LitContracts({
signer: ethersSigner,
network: LitNetwork.Cayenne,
});

await litContracts.connect();

return (await litContracts.pkpNftContractUtils.write.mint()).pkp;
}

async function getSessionSigs(litNodeClient, ethersSigner) {
console.log("Getting Session Signatures...");
return litNodeClient.getSessionSigs({
chain: "ethereum",
expiration: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // 24 hours
resourceAbilityRequests: [
{
resource: new LitActionResource("*"),
ability: LitAbility.LitActionExecution,
},
{
resource: new LitPKPResource("*"),
ability: LitAbility.PKPSigning,
},
],
authNeededCallback: getAuthNeededCallback(litNodeClient, ethersSigner),
});
}

function getAuthNeededCallback(litNodeClient, ethersSigner) {
return async ({ resourceAbilityRequests, expiration, uri }) => {
const toSign = await createSiweMessageWithRecaps({
uri,
expiration,
resources: resourceAbilityRequests,
walletAddress: await ethersSigner.getAddress(),
nonce: await litNodeClient.getLatestBlockhash(),
litNodeClient,
});

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

return authSig;
};
}
19 changes: 19 additions & 0 deletions lit-action-using-fetch/browser/src/litAction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const litActionCode = `
(async () => {
const url = "https://api.weather.gov/gridpoints/TOP/31,80/forecast";
const resp = await fetch(url).then((response) => response.json());
const temp = resp.properties.periods[0].temperature;

console.log(temp);

// only sign if the temperature is above 60. If it's below 60, exit.
if (temp < 60) {
return;
}

// this requests a signature share from the Lit Node
// the signature share will be automatically returned in the HTTP response from the node
// all the params (toSign, publicKey, sigName) are passed in from the LitJsSdk.executeJs() function
const sigShare = await LitActions.signEcdsa({ toSign, publicKey, sigName });
})();
`;
Loading