Skip to content

Commit

Permalink
Merge pull request #142 from lidofinance/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
Jeday authored Jul 1, 2024
2 parents a20dedb + bea4366 commit 87ec66c
Show file tree
Hide file tree
Showing 55 changed files with 12,536 additions and 1,235 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
cache: 'yarn'

- name: Install dependencies
run: yarn --frozen-lockfile
run: yarn --immutable

- name: Check Lint
run: yarn lint
Expand Down
10 changes: 6 additions & 4 deletions .github/workflows/deploy-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ jobs:
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/yarn.lock') }}-${{ hashFiles('**.[jt]s', '**.[jt]sx') }}
# If source files changed but packages didn't, rebuild from a prior cache.
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}-
${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json', '**/yarn.lock') }}--${{ hashFiles('**.[jt]s', '**.[jt]sx') }}
- name: Install dependencies
run: yarn --frozen-lockfile
run: yarn --immutable

- name: Build
run: yarn build
Expand All @@ -59,15 +59,17 @@ jobs:
WALLETCONNECT_PROJECT_ID: ${{ vars.WALLETCONNECT_PROJECT_ID }}
SUPPORTED_CHAINS: ${{ vars.SUPPORTED_CHAINS }}
DEFAULT_CHAIN: ${{ vars.DEFAULT_CHAIN }}
BASE_PATH: ${{ steps.config_pages.outputs.base_path }}
BASE_PATH: ${{ steps.config_pages.outputs.base_path }}/playground
- name: Export
run: yarn build:export
env:
NODE_NO_BUILD_DYNAMICS: true
- name: Move artifacts
run: mkdir -p ./apps && mkdir -p ./apps/playground && mv ./playground/out/* ./apps/playground && mv ./docs/build/* ./apps
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./playground/out
path: ./apps

# Deployment job
deploy:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish-alpha.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
cache: 'yarn'

- name: Install dependencies
run: yarn --frozen-lockfile
run: yarn --immutable

- name: Build
run: yarn build:packages
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
cache: 'yarn'

- name: Install dependencies
run: yarn --frozen-lockfile
run: yarn --immutable

- name: Build
run: yarn build:packages
Expand Down
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ For changes between versions see [CHANGELOG.MD](packages/sdk/CHANGELOG.md)

You can install the Lido Ethereum SDK using npm or yarn:

[Docs SDK package](packages/sdk/README.md)
[Docs SDK package](https://lidofinance.github.io/lido-ethereum-sdk/)

```bash
// SDK (stakes, wrap, withdrawals)
Expand Down Expand Up @@ -88,7 +88,7 @@ Replace "https://eth-goerli.alchemyapi.io/v2/{ALCHEMY_API_KEY}" with the address

## Examples

All examples and usage instructions can be found in the [Docs SDK package](packages/sdk/README.md).
All examples and usage instructions can be found in the [Docs SDK package](https://lidofinance.github.io/lido-ethereum-sdk/).

```ts
const lidoSDK = new LidoSDK({
Expand Down Expand Up @@ -120,8 +120,8 @@ For breaking changes between versions see [MIGRATION.md](packages/sdk/MIGRATION.

## Documentation

For additional information about available methods and functionality, refer to the [the documentation for the Lido Ethereum SDK](packages/sdk/README.md).
For additional information about available methods and functionality, refer to the [the documentation for the Lido Ethereum SDK](https://lidofinance.github.io/lido-ethereum-sdk/).

## Playground

To check out SDK in action visit [playground](https://lidofinance.github.io/lido-ethereum-sdk/). Or tinker locally by cloning this repo and following [Playground instructions](playground/README.md).
To check out SDK in action visit [playground](https://lidofinance.github.io/lido-ethereum-sdk/playground). Or tinker locally by cloning this repo and following [Playground instructions](playground/README.md).
20 changes: 20 additions & 0 deletions docs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Dependencies
/node_modules

# Production
/build

# Generated files
.docusaurus
.cache-loader

# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
41 changes: 41 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Website

This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator.

### Installation

```
$ yarn
```

### Local Development

```
$ yarn start
```

This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.

### Build

```
$ yarn build
```

This command generates static content into the `build` directory and can be served using any static contents hosting service.

### Deployment

Using SSH:

```
$ USE_SSH=true yarn deploy
```

Not using SSH:

```
$ GIT_USER=<Your GitHub username> yarn deploy
```

If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
3 changes: 3 additions & 0 deletions docs/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
};
93 changes: 93 additions & 0 deletions docs/docusaurus.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { themes as prismThemes } from 'prism-react-renderer';
import type { Config } from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';

const config: Config = {
title: 'Lido Ethereum SDK',
tagline:
'Lido Ethereum SDK is a package that provides convenient tools for interacting with Lido contracts on the Ethereum network through a software development kit (SDK). This SDK simplifies working with Lido contracts and accessing their functionality',
favicon: 'img/favicon.png',

// Set the production url of your site here
url: 'https://lidofinance.github.io/',

baseUrl: '/lido-ethereum-sdk/',
organizationName: 'lidofinance',
projectName: 'lido-ethereum-sdk',

onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'throw',

i18n: {
defaultLocale: 'en',
locales: ['en'],
},
plugins: [
[
'@docusaurus/plugin-content-docs',
{
id: 'examples',
path: 'examples',
routeBasePath: 'examples',
sidebarPath: './sidebarsExamples.ts',
},
],
],
presets: [
[
'classic',
{
docs: {
sidebarPath: './sidebarsSdk.ts',
path: 'sdk',
// Remove this to remove the "edit this page" links.
editUrl: 'https://github.com/lidofinance/lido-ethereum-sdk',
routeBasePath: '/',
},
blog: {
showReadingTime: true,
// Please change this to your repo.
// Remove this to remove the "edit this page" links.
editUrl: 'https://github.com/lidofinance/lido-ethereum-sdk',
},
} satisfies Preset.Options,
],
],

markdown: {
mermaid: true,
},
themes: ['@docusaurus/theme-mermaid'],
themeConfig: {
image: 'img/package_logo.png',
navbar: {
title: 'Lido Ethereum SDK Docs',
logo: {
alt: 'Lido Ethereum SDK Logo',
src: 'img/favicon.png',
},
items: [
{
type: 'docSidebar',
sidebarId: 'sdkSidebar',
position: 'left',
label: 'Docs',
},
{ to: '/examples/intro', label: 'Examples', position: 'left' },
{
href: '/playground',
label: 'Playground',
position: 'left',
target: '_blank',
},
{
href: 'https://github.com/lidofinance/lido-ethereum-sdk',
label: 'GitHub',
position: 'right',
},
],
},
} satisfies Preset.ThemeConfig,
};

export default config;
22 changes: 22 additions & 0 deletions docs/examples/intro.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
sidebar_position: 1
title: Introduction
---

SDK usage examples for various practical cases.

## stETH rewards accounting

The provided examples are useful to establish robust accounting for the stETH rebaseable token, learn more about [stETH rebases](https://docs.lido.fi/contracts/lido/#rebase). For some complicated scenarios of using collective accounts for multiples users (might be applicable for CEXes and custodian services), see the suggested [reward attribution](https://hackmd.io/@lido/rewards-attribution) approaches.

### Basic rebase tracking

- [Example 1. Subscribe on the stETH token rebase events to track rewards updates](rewards/subscribe-on-events)
- [Example 2. Get rewards accrued with the latest stETH token rebase for the chosen account](rewards/get-rewards.md)

### Reward history

- [Example 3. Retrieve reward history for the chosen account using the event logs (recommended)](rewards/retrieve-rewards-onchain.md)
- [Example 4. Retrieve reward history for the chosen account using the Subgraph indexer (alternative way)](rewards/retrieve-rewards-subgraph.md)
- [Example 5. Calculate the effective APR for the chosen account concerning the given period](rewards/calculate-effective-apr.md)
- [Example 6. Keep track of rewards accrued for the set of accounts](rewards/keep-track-rewards.md)
7 changes: 7 additions & 0 deletions docs/examples/rewards/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"label": "Rewards",
"position": 2,
"link": {
"type": "generated-index"
}
}
75 changes: 75 additions & 0 deletions docs/examples/rewards/calculate-effective-apr.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
sidebar_position: 6
---

# Calculate the effective APR for the chosen account concerning the given period

## On-chain

[Implementation example](https://github.com/lidofinance/lido-ethereum-sdk/blob/main/examples/rewards/src/averageAPRbyOnChain.ts)

### Requirements

- RPC provider (full node)

To calculate the effective APR for the address concerning the given period, you need:

- Calculate user's rewards for the period
- Sum APR for each rebase event
- Calculate the average APR for the period

Simplified code example:

```ts
const rewardsQuery = await lidoSDK.rewards.getRewardsFromChain({
address: mockAddress,
stepBlock: 10000, // max blocks in 1 query - depend on the RPC capabilities and pricing plans
back: {
days: 1n,
},
includeOnlyRebases: true,
});
const totalAPR = rewardsQuery.rewards.reduce(
(acc: number, reward: any) => acc + reward.apr,
0,
);

return totalAPR / rewards.length;
```

## Subgraph

### Requirements

- The Graph API key

> **_NOTE:_** The subgraph deployed on The Graph Decentralized Network. The subgraph data is indexed and served by independent indexers on the network. Therefore, the performance of the subgraph may depend on the indexer selected at the time of the request.
> Also, due to distributed indexers, the data in the subgraph may lag slightly behind the data in the on-chain network.
[Implementation example](https://github.com/lidofinance/lido-ethereum-sdk/blob/main/examples/rewards/src/averageAPRbySubgraph.ts)

To calculate the effective APR for the address concerning the given period, you need:

- Calculate user's rewards for the period
- Sum APR for each rebase event
- Calculate the average APR for the period

Simplified code example:

```ts
const rewardsQuery = await lidoSDK.rewards.getRewardsFromSubgraph({
address: rewardsAddress,
blocksBack: 10000,
stepEntities: 500, // defaults to 1000, max entities per one request to endpoint
includeOnlyRebases: true,
getSubgraphUrl(graphId, chainId) {
return `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/${id}`;
},
});
const totalAPR = rewardsQuery.rewards.reduce(
(acc: number, reward: any) => acc + reward.apr,
0,
);

return totalAPR / rewards.length;
```
42 changes: 42 additions & 0 deletions docs/examples/rewards/get-rewards.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
sidebar_position: 3
---

# Get rewards accrued with the latest stETH token rebase for the chosen account

## Requirements

- RPC provider

[Implementation example](https://github.com/lidofinance/lido-ethereum-sdk/blob/main/examples/rewards/src/lastEvent.ts)

For the convenience of calculating user balances, it is proposed to use [`Shares`](https://docs.lido.fi/guides/lido-tokens-integration-guide#steth-internals-share-mechanics).

This case can be used to calculate rewards without having to subscribe to a Rebase event.
The first thing you need to do is get the latest `TokenRebased` event to receive information about the token rebase. As soon as the event is received, it is necessary to calculate the change in the user’s balance. To do this you need to use the following formula:

```ts
(balanceInShares * totalEther) / totalShares;
```

Next, you need to calculate the user’s balance in stETH before the event (if unknown) and calculate the user’s balance in stETH after the event. The difference between these values will be the user’s reward for the rebase.

Simplified code example:

```ts
// Get the last Rebase event
const lastRebaseEvent = await sdk.events.stethEvents.getLastRebaseEvent();
// Event arguments
const { preTotalShares, preTotalEther, postTotalShares, postTotalEther } =
lastRebaseEvent?.args;

// User's balance in shares before the event
const balanceInShares = await lidoSDK.shares.balance(address); // for example, the value can be taken from the database
// Calculation of the user's balance in stETH before the event
const preBalanceStETH = (balanceInShares * preTotalEther) / preTotalShares;
// Calculation of the user's balance in stETH after the event
const postBalanceStETH = (balanceInShares * postTotalEther) / postTotalShares;

// Calculate user's balance change per Rebase event
const rewardsInStETH = postBalanceStETH - preBalanceStETH;
```
Loading

0 comments on commit 87ec66c

Please sign in to comment.