@folks-finance/xchain-sdk 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,9 +9,29 @@
9
9
 
10
10
  The official JavaScript SDK for the Folks Finance Cross-Chain Lending Protocol.
11
11
 
12
- ## Installation
12
+ ## Table of Contents
13
13
 
14
- ### Package manager
14
+ - [Getting Started](#getting-started)
15
+ - [Installation](#installation)
16
+ - [Package manager](#package-manager)
17
+ - [SDK Structure and Usage](#sdk-structure-and-usage)
18
+ - [FolksCore](#folkscore)
19
+ - [Modules](#modules)
20
+ - [Basic Usage](#basic-usage)
21
+ - [React Usage](#react-usage)
22
+ - [Initializing FolksCore](#initializing-folkscore)
23
+ - [Synchronizing FolksCore Signer](#synchronizing-folkscore-signer)
24
+
25
+ ## Getting Started
26
+
27
+ Before diving into the SDK, we recommend familiarizing yourself with the Folks Finance Cross-Chain Lending Protocol:
28
+
29
+ - Explore our [comprehensive documentation](https://docs.xapp.folks.finance/?utm_source=github&utm_medium=sdk-readme&utm_campaign=xchain-sdk) for in-depth information about the protocol and its features.
30
+ - Access additional resources and materials in our [Google Drive folder](https://drive.google.com/drive/folders/1P-C_V28JlIJNmoUH6pUKVgVpIfZYQYn5?usp=drive_link).
31
+
32
+ ### Installation
33
+
34
+ #### Package manager
15
35
 
16
36
  Using npm:
17
37
 
@@ -37,6 +57,207 @@ Using bun:
37
57
  bun add @folks-finance/xchain-sdk
38
58
  ```
39
59
 
60
+ ### SDK Structure and Usage
61
+
62
+ The Folks Finance Cross-Chain Lending SDK consists of two main components:
63
+
64
+ 1. `FolksCore`: This acts as the central context for the SDK, managing configuration and state that is shared across all modules.
65
+ 2. Various modules: Located in `/src/xchain/modules`, these provide specific functionalities for interacting with different aspects of the Folks Finance protocol.
66
+
67
+ #### FolksCore
68
+
69
+ `FolksCore` is responsible for initializing the SDK and maintaining the global context. It handles:
70
+
71
+ - Network selection (testnet/mainnet)
72
+ - Provider management
73
+ - Signer management
74
+
75
+ Any changes made to `FolksCore` will affect subsequent calls to the various modules. For example, changing the network or signer will impact how the modules interact with the blockchain.
76
+
77
+ #### Modules
78
+
79
+ The SDK includes several modules, each focusing on a specific area of functionality:
80
+
81
+ - `FolksAccount`: Manages account-related operations, including creating accounts, retrieving account information, and performing management operations such as inviting addresses, accepting invites, and unregistering addresses.
82
+ - `FolksLoan`: Handles all loan-related functions, including retrieving loan information, creating loans, and performing operations such as depositing, withdrawing, repaying, and more.
83
+ - `FolksOracle`: Provides access to updated price information from the oracle.
84
+ - `FolksPool`: Allows retrieval of informations about the pools.
85
+ - `FolksRewards`: Offers access to information about the rewards system.
86
+ - `FolksGmp`: Manages retry and revert functions for failed operations.
87
+
88
+ These modules use the context provided by `FolksCore` internally, so they always operate based on the current state of `FolksCore`.
89
+
90
+ ### Basic Usage
91
+
92
+ To start using the Folks Finance Cross-Chain Lending SDK:
93
+
94
+ 1. Import and initialize `FolksCore`:
95
+
96
+ ```ts
97
+ import { FolksCore, NetworkType } from "@folks-finance/xchain-sdk";
98
+
99
+ const folksConfig = {
100
+ network: NetworkType.TESTNET, // or NetworkType.MAINNET
101
+ provider: {
102
+ evm: {
103
+ // Add your EVM provider configuration here (optional)
104
+ // If not provided, default providers will be used
105
+ },
106
+ },
107
+ };
108
+
109
+ FolksCore.init(folksConfig);
110
+ ```
111
+
112
+ Note: The `provider` configuration in `folksConfig` is optional. If not provided, the SDK will use default providers defined in `src/chains/evm/common/utils/provider.ts`.
113
+
114
+ 2. Use the desired modules to interact with the protocol:
115
+
116
+ ```ts
117
+ import {
118
+ Action,
119
+ BYTES4_LENGTH,
120
+ FolksAccount,
121
+ FolksCore,
122
+ getRandomBytes,
123
+ getSupportedMessageAdapters,
124
+ MessageAdapterParamsType,
125
+ NetworkType,
126
+ } from "@folks-finance/xchain-sdk";
127
+ import { createWalletClient, http } from "viem";
128
+ import { mnemonicToAccount } from "viem/accounts";
129
+
130
+ import type { FolksChainId, Nonce } from "@folks-finance/xchain-sdk";
131
+
132
+ const generateRandomNonce = () => {
133
+ return getRandomBytes(BYTES4_LENGTH) as Nonce;
134
+ };
135
+
136
+ const MNEMONIC = "your mnemonic here";
137
+ const account = mnemonicToAccount(MNEMONIC);
138
+
139
+ // In a real environment you should already have a signer
140
+ const signer = createWalletClient({
141
+ account,
142
+ transport: http(),
143
+ });
144
+
145
+ // Example: Creating an account
146
+ const createAccount = async (sourceFolksChainId: FolksChainId) => {
147
+ const nonce = generateRandomNonce();
148
+ const {
149
+ adapterIds: [adapterId],
150
+ returnAdapterIds: [returnAdapterId],
151
+ } = getSupportedMessageAdapters({
152
+ action: Action.CreateAccount,
153
+ network: NetworkType.TESTNET,
154
+ messageAdapterParamType: MessageAdapterParamsType.Data,
155
+ sourceFolksChainId,
156
+ });
157
+ const adapters = { adapterId, returnAdapterId };
158
+
159
+ // You must set the correct signer before calling a write method that involves signing a transaction
160
+ FolksCore.setFolksSigner({
161
+ signer,
162
+ folksChainId,
163
+ });
164
+
165
+ const prepareCall = await FolksAccount.prepare.createAccount(nonce, adapters);
166
+ const hash = await FolksAccount.write.createAccount(nonce, prepareCall);
167
+
168
+ console.log("Create account hash:", hash);
169
+ };
170
+ ```
171
+
172
+ Remember that any changes made to `FolksCore` (like changing the network or signer) will affect all subsequent module calls. This design allows for flexible and context-aware interactions with the Folks Finance protocol across different chains and environments.
173
+
174
+ ### React Usage
175
+
176
+ When using the SDK with React, there are a few additional considerations to ensure proper initialization and synchronization. Here's how to set up and use the SDK in a React environment:
177
+
178
+ #### Initializing FolksCore
179
+
180
+ To initialize FolksCore only once in your React application, you can create a custom hook:
181
+
182
+ ```ts
183
+ import { useEffect } from "react";
184
+ import { FolksCore, NetworkType } from "@folks-finance/xchain-sdk";
185
+
186
+ import type { FolksCoreConfig } from "@folks-finance/xchain-sdk";
187
+
188
+ export const useInitFolksCore = () => {
189
+ useEffect(() => {
190
+ if (FolksCore.isInitialized()) return;
191
+
192
+ const folksCoreConfig: FolksCoreConfig = {
193
+ network: NetworkType.TESTNET,
194
+ provider,
195
+ };
196
+
197
+ FolksCore.init(folksCoreConfig);
198
+ }, []);
199
+ };
200
+ ```
201
+
202
+ Use this hook in a component that's common to all pages, such as the root layout in Next.js.
203
+
204
+ #### Synchronizing FolksCore Signer
205
+
206
+ To ensure that the correct signer is used for transactions, you need to synchronize the FolksCore signer whenever the chain (and consequently the associated signer) changes on the frontend:
207
+
208
+ ```ts
209
+ import { FOLKS_CHAIN, NetworkType, ChainType } from "@folks-finance/xchain-sdk";
210
+ import { useWalletClient } from "wagmi";
211
+ import { useMemo, useEffect } from "react";
212
+
213
+ import type { FolksChainId } from "@folks-finance/xchain-sdk";
214
+
215
+ function assertExhaustive(value: never, message = "Reached unexpected case in exhaustive switch"): never {
216
+ throw new Error(message);
217
+ }
218
+
219
+ const AVAILABLE_FOLKS_CHAINS = FOLKS_CHAIN[NetworkType.TESTNET];
220
+ const getFolksChainFromFolksChainId = (folksChainId: FolksChainId) => AVAILABLE_FOLKS_CHAINS[folksChainId];
221
+
222
+ const useEvmSigner = ({ chainId }: { chainId?: number }) => {
223
+ const { data: walletClient } = useWalletClient({ chainId });
224
+ const signer = useMemo(() => walletClient, [walletClient]);
225
+ return { signer };
226
+ };
227
+
228
+ export const useSyncFolksCoreSigner = () => {
229
+ // useFolksChain is a hook that returns the current selected FolksChainId on frontend
230
+ const { selectedFolksChainId } = useFolksChain();
231
+
232
+ const selectedFolksChain = selectedFolksChainId ? getFolksChainFromFolksChainId(selectedFolksChainId) : null;
233
+
234
+ const { signer: evmSigner } = useEvmSigner(
235
+ selectedFolksChain?.chainType === ChainType.EVM ? { chainId: selectedFolksChain.chainId as number } : {},
236
+ );
237
+
238
+ useEffect(() => {
239
+ if (!selectedFolksChain) return;
240
+
241
+ const folksChainId = selectedFolksChain.folksChainId;
242
+
243
+ switch (selectedFolksChain.chainType) {
244
+ case ChainType.EVM: {
245
+ if (!evmSigner) return;
246
+ FolksCore.setFolksSigner({
247
+ signer: evmSigner,
248
+ folksChainId,
249
+ });
250
+ break;
251
+ }
252
+ default:
253
+ assertExhaustive(selectedFolksChain.chainType);
254
+ }
255
+ }, [selectedFolksChain, evmSigner]);
256
+ };
257
+ ```
258
+
259
+ Like the initialization hook, `useSyncFolksCoreSigner` should be called in a component shared by all pages.
260
+
40
261
  [license-image]: https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square
41
262
  [license-url]: https://opensource.org/licenses/MIT
42
263
  [ci-image]: https://img.shields.io/github/actions/workflow/status/Folks-Finance/folks-finance-xchain-js-sdk/lint-and-typecheck.yml?branch=main&logo=github&style=flat-square
@@ -4,4 +4,4 @@ import type { LoanTypeId } from "../../../../common/types/module.js";
4
4
  import type { LoanTypeInfo } from "../types/loan.js";
5
5
  import type { UserRewards } from "../types/rewards.js";
6
6
  import type { Client } from "viem";
7
- export declare function getUserRewards(provider: Client, network: NetworkType, accountId: AccountId, referredAccountIds: Array<AccountId>, allLoanIds: Array<LoanId>, loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>): Promise<UserRewards>;
7
+ export declare function getUserRewards(provider: Client, network: NetworkType, accountId: AccountId, loanIds: Array<LoanId>, loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>): Promise<UserRewards>;
@@ -3,19 +3,7 @@ import { calcAccruedRewards } from "../../../../common/utils/formulae.js";
3
3
  import { getHubChain } from "../utils/chain.js";
4
4
  import { getLoanManagerContract } from "../utils/contract.js";
5
5
  import { getUserLoans } from "./folks-hub-loan.js";
6
- const emptyAccountRewards = (folksTokenIds) => {
7
- const accountRewards = {};
8
- for (const folksTokenId of folksTokenIds) {
9
- accountRewards[folksTokenId] = { collateral: 0n, borrow: 0n, interestPaid: 0n };
10
- }
11
- return accountRewards;
12
- };
13
- const addToAccountRewards = (existing, add) => {
14
- existing.collateral += add.collateral;
15
- existing.borrow += add.borrow;
16
- existing.interestPaid += add.interestPaid;
17
- };
18
- export async function getUserRewards(provider, network, accountId, referredAccountIds, allLoanIds, loanTypesInfo) {
6
+ export async function getUserRewards(provider, network, accountId, loanIds, loanTypesInfo) {
19
7
  const hubChain = getHubChain(network);
20
8
  const loanManager = getLoanManagerContract(provider, hubChain.loanManagerAddress);
21
9
  // derive the tokens/pools you are interested in
@@ -31,41 +19,30 @@ export async function getUserRewards(provider, network, accountId, referredAccou
31
19
  }
32
20
  }
33
21
  }
34
- // fetch the accounts rewards which are updated
22
+ // fetch the account rewards which are updated
35
23
  const getUsersPoolRewards = [];
36
- for (const aId of [accountId, ...referredAccountIds]) {
37
- for (const pId of poolIds) {
38
- getUsersPoolRewards.push({
39
- address: loanManager.address,
40
- abi: loanManager.abi,
41
- functionName: "getUserPoolRewards",
42
- args: [aId, pId],
43
- });
44
- }
24
+ for (const poolId of poolIds) {
25
+ getUsersPoolRewards.push({
26
+ address: loanManager.address,
27
+ abi: loanManager.abi,
28
+ functionName: "getUserPoolRewards",
29
+ args: [accountId, poolId],
30
+ });
45
31
  }
46
- const accountsPoolRewards = (await multicall(provider, {
32
+ const accountPoolRewards = (await multicall(provider, {
47
33
  contracts: getUsersPoolRewards,
48
34
  allowFailure: false,
49
35
  }));
50
- // initialise the rewards
51
- const userRewards = {
52
- accountId,
53
- rewards: emptyAccountRewards(folksTokenIds),
54
- referrals: {},
55
- };
56
- for (const aId of referredAccountIds)
57
- userRewards.referrals[aId] = emptyAccountRewards(folksTokenIds);
58
- // add all the rewards which are updated
59
- for (const [i, accountPoolReward] of accountsPoolRewards.entries()) {
60
- const accountIndex = Math.floor(i / folksTokenIds.length) - 1;
61
- const folksTokenId = folksTokenIds[Math.floor(i / folksTokenIds.length)];
62
- const accountRewards = accountIndex === -1 ? userRewards.rewards : userRewards.referrals[referredAccountIds[accountIndex]];
63
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
64
- addToAccountRewards(accountRewards[folksTokenId], accountPoolReward);
36
+ // initialise with all the rewards which are updated
37
+ const rewards = {};
38
+ for (const [i, accountPoolReward] of accountPoolRewards.entries()) {
39
+ const folksTokenId = folksTokenIds[i];
40
+ rewards[folksTokenId] = accountPoolReward;
65
41
  }
42
+ const userRewards = { accountId, rewards };
66
43
  // add all the rewards which are not updated
67
- const userLoans = await getUserLoans(provider, network, allLoanIds);
68
- for (const loanId of allLoanIds) {
44
+ const userLoans = await getUserLoans(provider, network, loanIds);
45
+ for (const loanId of loanIds) {
69
46
  const userLoan = userLoans.get(loanId);
70
47
  if (userLoan === undefined)
71
48
  throw Error("Unknown user loan");
@@ -73,7 +50,8 @@ export async function getUserRewards(provider, network, accountId, referredAccou
73
50
  const loanTypeInfo = loanTypesInfo[loanTypeId];
74
51
  if (!loanTypeInfo)
75
52
  throw new Error(`Unknown loan type id ${loanTypeId}`);
76
- const accountRewards = accountId === userLoanAccountId ? userRewards.rewards : userRewards.referrals[userLoanAccountId];
53
+ if (accountId !== userLoanAccountId)
54
+ throw new Error(`Loan ${loanId} belongs to account ${userLoanAccountId}`);
77
55
  for (const [i, poolId] of colPools.entries()) {
78
56
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
79
57
  const folksTokenId = seen.get(poolId);
@@ -84,7 +62,7 @@ export async function getUserRewards(provider, network, accountId, referredAccou
84
62
  const { collateralRewardIndex } = loanPool.reward;
85
63
  const accrued = calcAccruedRewards(balance, collateralRewardIndex, [rewardIndex, 18]);
86
64
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
87
- accountRewards[folksTokenId].collateral += accrued;
65
+ userRewards.rewards[folksTokenId].collateral += accrued;
88
66
  }
89
67
  for (const [i, poolId] of borPools.entries()) {
90
68
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
@@ -96,7 +74,7 @@ export async function getUserRewards(provider, network, accountId, referredAccou
96
74
  const { borrowRewardIndex } = loanPool.reward;
97
75
  const accrued = calcAccruedRewards(amount, borrowRewardIndex, [rewardIndex, 18]);
98
76
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
99
- accountRewards[folksTokenId].borrow += accrued;
77
+ userRewards.rewards[folksTokenId].collateral += accrued;
100
78
  }
101
79
  }
102
80
  return userRewards;
@@ -1 +1 @@
1
- {"version":3,"file":"folks-hub-rewards.js","sourceRoot":"","sources":["../../../../../src/chains/evm/hub/modules/folks-hub-rewards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAUnD,MAAM,mBAAmB,GAAG,CAAC,aAAkC,EAAkB,EAAE;IACjF,MAAM,cAAc,GAAmB,EAAE,CAAC;IAC1C,KAAK,MAAM,YAAY,IAAI,aAAa,EAAE,CAAC;QACzC,cAAc,CAAC,YAAY,CAAC,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,CAAC;IAClF,CAAC;IACD,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAEF,MAAM,mBAAmB,GAAG,CAAC,QAA4B,EAAE,GAAuB,EAAE,EAAE;IACpF,QAAQ,CAAC,UAAU,IAAI,GAAG,CAAC,UAAU,CAAC;IACtC,QAAQ,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC;IAC9B,QAAQ,CAAC,YAAY,IAAI,GAAG,CAAC,YAAY,CAAC;AAC5C,CAAC,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,QAAgB,EAChB,OAAoB,EACpB,SAAoB,EACpB,kBAAoC,EACpC,UAAyB,EACzB,aAAwD;IAExD,MAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,WAAW,GAAG,sBAAsB,CAAC,QAAQ,EAAE,QAAQ,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AC,UAAU,IAAI,OAAO,CAAC;QAC3D,CAAC;QAED,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;YAC7C,oEAAoE;YACpE,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAE,CAAC;YACvC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;YAElD,MAAM,QAAQ,GAAG,YAAY,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YAClD,IAAI,CAAC,QAAQ;gBAAE,MAAM,IAAI,KAAK,CAAC,+BAA+B,YAAY,EAAE,CAAC,CAAC;YAC9E,MAAM,EAAE,iBAAiB,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;YAE9C,MAAM,OAAO,GAAG,kBAAkB,CAAC,MAAM,EAAE,iBAAiB,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC,CAAC;YACjF,oEAAoE;YACpE,WAAW,CAAC,OAAO,CAAC,YAAY,CAAE,CAAC,UAAU,IAAI,OAAO,CAAC;QAC3D,CAAC;IACH,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC"}
@@ -9,5 +9,4 @@ export type AccountRewards = Partial<Record<FolksTokenId, AccountPoolRewards>>;
9
9
  export type UserRewards = {
10
10
  accountId: AccountId;
11
11
  rewards: AccountRewards;
12
- referrals: Record<AccountId, AccountRewards>;
13
12
  };
@@ -3,5 +3,5 @@ import type { UserRewards } from "../../chains/evm/hub/types/rewards.js";
3
3
  import type { AccountId, LoanId } from "../../common/types/lending.js";
4
4
  import type { LoanTypeId } from "../../common/types/module.js";
5
5
  export declare const read: {
6
- rewards(accountId: AccountId, referredAccountIds: Array<AccountId>, allLoanIds: Array<LoanId>, loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>): Promise<UserRewards>;
6
+ rewards(accountId: AccountId, loanIds: Array<LoanId>, loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>): Promise<UserRewards>;
7
7
  };
@@ -1,8 +1,8 @@
1
1
  import { FolksHubRewards } from "../../chains/evm/hub/modules/index.js";
2
2
  import { FolksCore } from "../core/folks-core.js";
3
3
  export const read = {
4
- async rewards(accountId, referredAccountIds, allLoanIds, loanTypesInfo) {
5
- return FolksHubRewards.getUserRewards(FolksCore.getHubProvider(), FolksCore.getSelectedNetwork(), accountId, referredAccountIds, allLoanIds, loanTypesInfo);
4
+ async rewards(accountId, loanIds, loanTypesInfo) {
5
+ return FolksHubRewards.getUserRewards(FolksCore.getHubProvider(), FolksCore.getSelectedNetwork(), accountId, loanIds, loanTypesInfo);
6
6
  },
7
7
  };
8
8
  //# sourceMappingURL=folks-rewards.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"folks-rewards.js","sourceRoot":"","sources":["../../../src/xchain/modules/folks-rewards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAOlD,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,KAAK,CAAC,OAAO,CACX,SAAoB,EACpB,kBAAoC,EACpC,UAAyB,EACzB,aAAwD;QAExD,OAAO,eAAe,CAAC,cAAc,CACnC,SAAS,CAAC,cAAc,EAAE,EAC1B,SAAS,CAAC,kBAAkB,EAAE,EAC9B,SAAS,EACT,kBAAkB,EAClB,UAAU,EACV,aAAa,CACd,CAAC;IACJ,CAAC;CACF,CAAC"}
1
+ {"version":3,"file":"folks-rewards.js","sourceRoot":"","sources":["../../../src/xchain/modules/folks-rewards.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAOlD,MAAM,CAAC,MAAM,IAAI,GAAG;IAClB,KAAK,CAAC,OAAO,CACX,SAAoB,EACpB,OAAsB,EACtB,aAAwD;QAExD,OAAO,eAAe,CAAC,cAAc,CACnC,SAAS,CAAC,cAAc,EAAE,EAC1B,SAAS,CAAC,kBAAkB,EAAE,EAC9B,SAAS,EACT,OAAO,EACP,aAAa,CACd,CAAC;IACJ,CAAC;CACF,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@folks-finance/xchain-sdk",
3
3
  "description": "The official JavaScript SDK for the Folks Finance Cross-Chain Lending Protocol",
4
- "version": "0.0.21",
4
+ "version": "0.0.22",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -11,29 +11,14 @@ import type { AccountId, LoanId } from "../../../../common/types/lending.js";
11
11
  import type { LoanTypeId } from "../../../../common/types/module.js";
12
12
  import type { FolksTokenId } from "../../../../common/types/token.js";
13
13
  import type { LoanTypeInfo } from "../types/loan.js";
14
- import type { AccountPoolRewards, AccountRewards, UserRewards } from "../types/rewards.js";
14
+ import type { AccountPoolRewards, UserRewards } from "../types/rewards.js";
15
15
  import type { Client, ContractFunctionParameters } from "viem";
16
16
 
17
- const emptyAccountRewards = (folksTokenIds: Array<FolksTokenId>): AccountRewards => {
18
- const accountRewards: AccountRewards = {};
19
- for (const folksTokenId of folksTokenIds) {
20
- accountRewards[folksTokenId] = { collateral: 0n, borrow: 0n, interestPaid: 0n };
21
- }
22
- return accountRewards;
23
- };
24
-
25
- const addToAccountRewards = (existing: AccountPoolRewards, add: AccountPoolRewards) => {
26
- existing.collateral += add.collateral;
27
- existing.borrow += add.borrow;
28
- existing.interestPaid += add.interestPaid;
29
- };
30
-
31
17
  export async function getUserRewards(
32
18
  provider: Client,
33
19
  network: NetworkType,
34
20
  accountId: AccountId,
35
- referredAccountIds: Array<AccountId>,
36
- allLoanIds: Array<LoanId>,
21
+ loanIds: Array<LoanId>,
37
22
  loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>,
38
23
  ): Promise<UserRewards> {
39
24
  const hubChain = getHubChain(network);
@@ -53,45 +38,33 @@ export async function getUserRewards(
53
38
  }
54
39
  }
55
40
 
56
- // fetch the accounts rewards which are updated
41
+ // fetch the account rewards which are updated
57
42
  const getUsersPoolRewards: Array<ContractFunctionParameters> = [];
58
- for (const aId of [accountId, ...referredAccountIds]) {
59
- for (const pId of poolIds) {
60
- getUsersPoolRewards.push({
61
- address: loanManager.address,
62
- abi: loanManager.abi,
63
- functionName: "getUserPoolRewards",
64
- args: [aId, pId],
65
- });
66
- }
43
+ for (const poolId of poolIds) {
44
+ getUsersPoolRewards.push({
45
+ address: loanManager.address,
46
+ abi: loanManager.abi,
47
+ functionName: "getUserPoolRewards",
48
+ args: [accountId, poolId],
49
+ });
67
50
  }
68
51
 
69
- const accountsPoolRewards: Array<AccountPoolRewards> = (await multicall(provider, {
52
+ const accountPoolRewards: Array<AccountPoolRewards> = (await multicall(provider, {
70
53
  contracts: getUsersPoolRewards,
71
54
  allowFailure: false,
72
55
  })) as Array<AccountPoolRewards>;
73
56
 
74
- // initialise the rewards
75
- const userRewards: UserRewards = {
76
- accountId,
77
- rewards: emptyAccountRewards(folksTokenIds),
78
- referrals: {},
79
- };
80
- for (const aId of referredAccountIds) userRewards.referrals[aId] = emptyAccountRewards(folksTokenIds);
81
-
82
- // add all the rewards which are updated
83
- for (const [i, accountPoolReward] of accountsPoolRewards.entries()) {
84
- const accountIndex = Math.floor(i / folksTokenIds.length) - 1;
85
- const folksTokenId = folksTokenIds[Math.floor(i / folksTokenIds.length)];
86
- const accountRewards =
87
- accountIndex === -1 ? userRewards.rewards : userRewards.referrals[referredAccountIds[accountIndex]];
88
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
89
- addToAccountRewards(accountRewards[folksTokenId]!, accountPoolReward);
57
+ // initialise with all the rewards which are updated
58
+ const rewards: Partial<Record<FolksTokenId, AccountPoolRewards>> = {};
59
+ for (const [i, accountPoolReward] of accountPoolRewards.entries()) {
60
+ const folksTokenId = folksTokenIds[i];
61
+ rewards[folksTokenId] = accountPoolReward;
90
62
  }
63
+ const userRewards: UserRewards = { accountId, rewards };
91
64
 
92
65
  // add all the rewards which are not updated
93
- const userLoans = await getUserLoans(provider, network, allLoanIds);
94
- for (const loanId of allLoanIds) {
66
+ const userLoans = await getUserLoans(provider, network, loanIds);
67
+ for (const loanId of loanIds) {
95
68
  const userLoan = userLoans.get(loanId);
96
69
  if (userLoan === undefined) throw Error("Unknown user loan");
97
70
 
@@ -106,9 +79,8 @@ export async function getUserRewards(
106
79
 
107
80
  const loanTypeInfo = loanTypesInfo[loanTypeId];
108
81
  if (!loanTypeInfo) throw new Error(`Unknown loan type id ${loanTypeId}`);
82
+ if (accountId !== userLoanAccountId) throw new Error(`Loan ${loanId} belongs to account ${userLoanAccountId}`);
109
83
 
110
- const accountRewards =
111
- accountId === userLoanAccountId ? userRewards.rewards : userRewards.referrals[userLoanAccountId];
112
84
  for (const [i, poolId] of colPools.entries()) {
113
85
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
114
86
  const folksTokenId = seen.get(poolId)!;
@@ -119,10 +91,10 @@ export async function getUserRewards(
119
91
  const { collateralRewardIndex } = loanPool.reward;
120
92
 
121
93
  const accrued = calcAccruedRewards(balance, collateralRewardIndex, [rewardIndex, 18]);
122
-
123
94
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
124
- accountRewards[folksTokenId]!.collateral += accrued;
95
+ userRewards.rewards[folksTokenId]!.collateral += accrued;
125
96
  }
97
+
126
98
  for (const [i, poolId] of borPools.entries()) {
127
99
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
128
100
  const folksTokenId = seen.get(poolId)!;
@@ -134,7 +106,7 @@ export async function getUserRewards(
134
106
 
135
107
  const accrued = calcAccruedRewards(amount, borrowRewardIndex, [rewardIndex, 18]);
136
108
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
137
- accountRewards[folksTokenId]!.borrow += accrued;
109
+ userRewards.rewards[folksTokenId]!.collateral += accrued;
138
110
  }
139
111
  }
140
112
 
@@ -12,5 +12,4 @@ export type AccountRewards = Partial<Record<FolksTokenId, AccountPoolRewards>>;
12
12
  export type UserRewards = {
13
13
  accountId: AccountId;
14
14
  rewards: AccountRewards;
15
- referrals: Record<AccountId, AccountRewards>;
16
15
  };
@@ -9,16 +9,14 @@ import type { LoanTypeId } from "../../common/types/module.js";
9
9
  export const read = {
10
10
  async rewards(
11
11
  accountId: AccountId,
12
- referredAccountIds: Array<AccountId>,
13
- allLoanIds: Array<LoanId>,
12
+ loanIds: Array<LoanId>,
14
13
  loanTypesInfo: Partial<Record<LoanTypeId, LoanTypeInfo>>,
15
14
  ): Promise<UserRewards> {
16
15
  return FolksHubRewards.getUserRewards(
17
16
  FolksCore.getHubProvider(),
18
17
  FolksCore.getSelectedNetwork(),
19
18
  accountId,
20
- referredAccountIds,
21
- allLoanIds,
19
+ loanIds,
22
20
  loanTypesInfo,
23
21
  );
24
22
  },