npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@folks-finance/xchain-sdk

v0.0.27

Published

The official JavaScript SDK for the Folks Finance Cross-Chain Lending Protocol

Downloads

936

Readme

@folks-finance/xchain-sdk

License: MIT CI NPM version Downloads

xChain Header

The official JavaScript SDK for the Folks Finance Cross-Chain Lending Protocol.

Table of Contents

Getting Started

Before diving into the SDK, we recommend familiarizing yourself with the Folks Finance Cross-Chain Lending Protocol:

Installation

Package manager

Using npm:

npm install @folks-finance/xchain-sdk

Using yarn:

yarn add @folks-finance/xchain-sdk

Using pnpm:

pnpm add @folks-finance/xchain-sdk

Using bun:

bun add @folks-finance/xchain-sdk

SDK Structure and Usage

The Folks Finance Cross-Chain Lending SDK consists of two main components:

  1. FolksCore: This acts as the central context for the SDK, managing configuration and state that is shared across all modules.
  2. Various modules: Located in /src/xchain/modules, these provide specific functionalities for interacting with different aspects of the Folks Finance protocol.

FolksCore

FolksCore is responsible for initializing the SDK and maintaining the global context. It handles:

  • Network selection (testnet/mainnet)
  • Provider management
  • Signer management

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.

Modules

The SDK includes several modules, each focusing on a specific area of functionality:

  • FolksAccount: Manages account-related operations, including creating accounts, retrieving account information, and performing management operations such as inviting addresses, accepting invites, and unregistering addresses.
  • FolksLoan: Handles all loan-related functions, including retrieving loan information, creating loans, and performing operations such as depositing, withdrawing, repaying, and more.
  • FolksOracle: Provides access to updated price information from the oracle.
  • FolksPool: Allows retrieval of informations about the pools.
  • FolksRewards: Offers access to information about the rewards system.
  • FolksGmp: Manages retry and revert functions for failed operations.

These modules use the context provided by FolksCore internally, so they always operate based on the current state of FolksCore.

Basic Usage

To start using the Folks Finance Cross-Chain Lending SDK:

  1. Import and initialize FolksCore:
import { FolksCore, NetworkType } from "@folks-finance/xchain-sdk";

const folksConfig = {
  network: NetworkType.TESTNET, // or NetworkType.MAINNET
  provider: {
    evm: {
      // Add your EVM provider configuration here (optional)
      // If not provided, default providers will be used
    },
  },
};

FolksCore.init(folksConfig);

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.

  1. Use the desired modules to interact with the protocol:
import {
  Action,
  BYTES4_LENGTH,
  FolksAccount,
  FolksCore,
  getRandomBytes,
  getSupportedMessageAdapters,
  MessageAdapterParamsType,
  NetworkType,
} from "@folks-finance/xchain-sdk";
import { createWalletClient, http } from "viem";
import { mnemonicToAccount } from "viem/accounts";

import type { FolksChainId, Nonce } from "@folks-finance/xchain-sdk";

const generateRandomNonce = () => {
  return getRandomBytes(BYTES4_LENGTH) as Nonce;
};

const MNEMONIC = "your mnemonic here";
const account = mnemonicToAccount(MNEMONIC);

// In a real environment you should already have a signer
const signer = createWalletClient({
  account,
  transport: http(),
});

// Example: Creating an account
const createAccount = async (sourceFolksChainId: FolksChainId) => {
  const nonce = generateRandomNonce();
  const {
    adapterIds: [adapterId],
    returnAdapterIds: [returnAdapterId],
  } = getSupportedMessageAdapters({
    action: Action.CreateAccount,
    network: NetworkType.TESTNET,
    messageAdapterParamType: MessageAdapterParamsType.Data,
    sourceFolksChainId,
  });
  const adapters = { adapterId, returnAdapterId };

  // You must set the correct signer before calling a write method that involves signing a transaction
  FolksCore.setFolksSigner({
    signer,
    folksChainId,
  });

  const prepareCall = await FolksAccount.prepare.createAccount(nonce, adapters);
  const hash = await FolksAccount.write.createAccount(nonce, prepareCall);

  console.log("Create account hash:", hash);
};

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.

React Usage

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:

Initializing FolksCore

To initialize FolksCore only once in your React application, you can create a custom hook:

import { useEffect } from "react";
import { FolksCore, NetworkType } from "@folks-finance/xchain-sdk";

import type { FolksCoreConfig } from "@folks-finance/xchain-sdk";

export const useInitFolksCore = () => {
  useEffect(() => {
    if (FolksCore.isInitialized()) return;

    const folksCoreConfig: FolksCoreConfig = {
      network: NetworkType.TESTNET,
      provider,
    };

    FolksCore.init(folksCoreConfig);
  }, []);
};

Use this hook in a component that's common to all pages, such as the root layout in Next.js.

Synchronizing FolksCore Signer

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:

import { FOLKS_CHAIN, NetworkType, ChainType } from "@folks-finance/xchain-sdk";
import { useWalletClient } from "wagmi";
import { useMemo, useEffect } from "react";

import type { FolksChainId } from "@folks-finance/xchain-sdk";

function assertExhaustive(value: never, message = "Reached unexpected case in exhaustive switch"): never {
  throw new Error(message);
}

const AVAILABLE_FOLKS_CHAINS = FOLKS_CHAIN[NetworkType.TESTNET];
const getFolksChainFromFolksChainId = (folksChainId: FolksChainId) => AVAILABLE_FOLKS_CHAINS[folksChainId];

const useEvmSigner = ({ chainId }: { chainId?: number }) => {
  const { data: walletClient } = useWalletClient({ chainId });
  const signer = useMemo(() => walletClient, [walletClient]);
  return { signer };
};

export const useSyncFolksCoreSigner = () => {
  // useFolksChain is a hook that returns the current selected FolksChainId on frontend
  const { selectedFolksChainId } = useFolksChain();

  const selectedFolksChain = selectedFolksChainId ? getFolksChainFromFolksChainId(selectedFolksChainId) : null;

  const { signer: evmSigner } = useEvmSigner(
    selectedFolksChain?.chainType === ChainType.EVM ? { chainId: selectedFolksChain.chainId as number } : {},
  );

  useEffect(() => {
    if (!selectedFolksChain) return;

    const folksChainId = selectedFolksChain.folksChainId;

    switch (selectedFolksChain.chainType) {
      case ChainType.EVM: {
        if (!evmSigner) return;
        FolksCore.setFolksSigner({
          signer: evmSigner,
          folksChainId,
        });
        break;
      }
      default:
        assertExhaustive(selectedFolksChain.chainType);
    }
  }, [selectedFolksChain, evmSigner]);
};

Like the initialization hook, useSyncFolksCoreSigner should be called in a component shared by all pages.