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

fetch-in-lit-action Docs Update #347

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
129 changes: 40 additions & 89 deletions docs/sdk/serverless-signing/fetch.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,119 +3,70 @@ import FeedbackComponent from "@site/src/pages/feedback.md";
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# Using Fetch

## Prerequisites

- Familiarity with JavaScript
- Basic understanding of [serverless signing](../serverless-signing/quick-start.md)
# Fetching Data from the Web within a Lit Action

## Overview
Unlike traditional smart contract ecosystems, Lit Actions can natively talk to the external world. This is useful for things like fetching data from the web, or sending API requests to other services.

The Lit Action below will get the current temperature from the [National Weather Service](https://www.weather.gov/) API, and ONLY sign a txn if the temperature is forecast to be **above 60 degrees F**. Since you can put this HTTP request and logic that uses the response directly in your Lit Action, you don't have to worry about using a 3rd party oracle to pull data in.
Unlike traditional smart contract ecosystems, Lit Actions can natively talk to the external world. This is useful for things like fetching data from the web, or sending API requests to other services.

### How it works
This Lit Action fetches the current temperature from the [National Weather Service](https://www.weather.gov/) API. It will only sign the given message if the temperature forecast exceeds 60°F (15.5°C). By incorporating the API request and response logic directly within the Lit Action, you eliminate the need for a third-party oracle.

The HTTP request will be sent out by all the Lit Nodes in parallel, and consensus is based on at least 2/3 of the nodes getting the same response. If less than 2/3 nodes get the same response, then the user can not collect the signature shares above the threshold and therefore cannot produce the final signature. Note that your HTTP request will be sent N times where N is the number of nodes in the Lit Network, because it's sent from every Lit Node in parallel.
## Prerequisites

Be careful about how many requests you're making and note that this may trigger rate limiting issues on some servers.
- Basic understanding of [PKPs](../../../user-wallets/pkps/overview)
- Basic understanding of [Lit Actions](../serverless-signing/quick-start)

## Example
## Complete Code Example

### Lit Action code
The complete code example is available in the [Lit Developer Guides Code Repository](https://github.com/LIT-Protocol/developer-guides-code/tree/master/lit-action-using-fetch). There you can find a Node.js and browser implementation of this example code.

:::note
`toSign` data is required to be in 32 byte format.
### Example Lit Action

The `ethers.utils.arrayify(ethers.utils.keccak256(...)` can be used to convert the `toSign` data to the correct format.
:::
The `signEcdsa` function returns a boolean value stored in the `sigShare` variable. It's `true` if the message is successfully signed, and `false` if an error occurs during the Lit Action. If the temperature is below 60°F (15.5°C), the Lit Action will instead return a response message to the user.

```jsx
const litActionCode = `
const go = 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;

// only sign if the temperature is above 60. if it's below 60, exit.
if (temp < 60) {
return;
const _litActionCode = async () => {
try {
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("Current temperature from the API:", temp);

if (temp < 60) {
Lit.Actions.setResponse({ response: "It's too cold to sign the message!" });
return;
}

const sigShare = await LitActions.signEcdsa({ toSign, publicKey, sigName });
Lit.Actions.setResponse({ response: sigShare });
} catch (error) {
Lit.Actions.setResponse({ response: error.message });
}

// 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 });
};

go();
`;
export const litActionCode = `(${_litActionCode.toString()})();`;
```

### Execute Lit Action code on Lit nodes
## Important Considerations
You can use fetch() inside a Lit Action to write data, but caution is necessary. The HTTP request will execute multiple times, once for each Lit Node in the network.
When writing data, it's crucial to use operations that produce the same result regardless of how often they're repeated. Consider these examples:

```jsx
const runLitAction = async () => {
const message = new Uint8Array(
await crypto.subtle.digest('SHA-256', new TextEncoder().encode('Hello world'))
);

const litNodeClient = new LitJsSdk.LitNodeClient({
alertWhenUnauthorized: false,
litNetwork: "datil-dev",
debug: true,
});
await litNodeClient.connect();
const signatures = await litNodeClient.executeJs({
code: litActionCode,
sessionSigs,
// all jsParams can be used anywhere in your litActionCode
jsParams: {
toSign: message,
publicKey:
"0x02e5896d70c1bc4b4844458748fe0f936c7919d7968341e391fb6d82c258192e64",
sigName: "sig1",
},
});
console.log("signatures: ", signatures);
};
1. Repeatable operation (preferred):

runLitAction();
```
- SQL Update: Running it multiple times only changes the row once.
- Result: Consistent outcome, regardless of repetition.

## Using fetch() to write data
You can also use fetch() inside a Lit Action to write data, but you **must be careful** (because the HTTP request will be run N times where N is the number of Lit Nodes). On Serrano, N is 10, so any fetch() request will be sent to the server 10 times.

**This is safe**, however, if the place you're writing the data to is *idempotent*. Idempotent means that applying the same operation over and over will not change the result. So for example, a SQL Insert is not idempotent, becuase if you run it 10 times, it will create 10 rows. On the other hand, a SQL Update is idempotent, because if you run it 10 times, it will only update the row once. So if you're using fetch() to write data, make sure the server you're writing to is idempotent.
2. Non-repeatable operation (avoid):

### Lit Action code
- SQL Insert: Each execution creates a new row.
- Result: Unintended duplicates with multiple executions.

```jsx
const runLitAction = async () => {
if (day === "") {
alert("Select a day first!");
return;
}
For Lit Actions using fetch() to write data, aim for repeatable operations. This approach prevents issues like duplicate entries or unintended changes if the request repeats due to network conditions or distributed execution across nodes.

const litActionCode = `
const fetchWeatherApiResponse = async () => {
const url = "https://api.weather.gov/gridpoints/LWX/97,71/forecast";
let toSign;
try {
const response = await fetch(url).then((res) => res.json());
const forecast = response.properties.periods[day];
toSign = { temp: forecast.temperature + " " + forecast.temperatureUnit, shortForecast: forecast.shortForecast };
const sigShare = await LitActions.signEcdsa({ toSign, publicKey, sigName });
} catch(e) {
console.log(e);
}
LitActions.setResponse({ response: JSON.stringify(toSign) });
};

fetchWeatherApiResponse();
`;
## Summary
This guide demonstrates how to fetch data from the web within a Lit Action.

```
If you'd like to learn more about Lit Actions, check out the [Lit Actions SDK](https://actions-docs.litprotocol.com/), or our [Advanced Topics](https://developer.litprotocol.com/category/advanced-topics-1) section on Lit Actions.

<FeedbackComponent/>