@shogun-sdk/money-legos-react
TypeScript icon, indicating that this package has built-in type declarations

1.1.70 • Public • Published

@shogun-sdk/money-legos-react

A React SDK for interacting with the Shogun Lego API for NFT purchases.

Installation

npm install @shogun-sdk/money-legos-react
# or
yarn add @shogun-sdk/money-legos-react

Setup

Before using the hooks, you need to set up the ShogunLegoProvider at the root of your application:

import { ShogunLegoProvider } from '@shogun-sdk/money-legos-react';

function App() {
  return (
    <ShogunLegoProvider apiKey="YOUR_API_KEY">
      {/* Your application components */}
    </ShogunLegoProvider>
  );
}

Hooks

useLego

The useLego hook is designed to validate and prepare transaction data for purchasing NFTs in blockchain applications.

Usage

import { useLego } from '@shogun-sdk/money-legos-react';

function NFTPurchaseComponent() {
  const { status, error, data, isLoading, refetch } = useLego({
    items: [
      { address: '0x123...', tokenId: '1' },
      { address: '0x456...', tokenId: '2' }
    ],
    token: {
      address: '0xabc...',
      decimals: 18,
      chainId: 1
    },
    userAddress: '0x789...'
  });

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  // Process the transaction data
  return (
    <div>
      {status && data && (
        <button onClick={() => processTransaction(data)}>
          Purchase NFTs
        </button>
      )}
    </div>
  );
}

Parameters

Parameter Type Description
items NFTItem[] Array of NFT items to purchase, each containing address (contract address) and tokenId
token Token The token used for the transaction, including address, decimals, and chainId
userAddress string The blockchain address of the user making the purchase

Response Data

The data property contains the following structure when the API call is successful:

interface ResponseData {
  steps: Step[];        // Array of transaction steps
  details: Details;     // Transaction details
  fees: Fees;           // Fee information
}
Step
interface Step {
  from: string;                // Sender address
  to: string;                  // Recipient address
  data: string;                // Transaction data
  value: string;               // Transaction value
  chainId: number;             // Chain ID
  gas: string;                 // Gas limit
  maxFeePerGas: string;        // Maximum fee per gas
  maxPriorityFeePerGas: string; // Maximum priority fee per gas
}
Details
interface Details {
  sender: string;       // Sender address
  recipient: string;    // Recipient address
  tokenIn: TokenIn;     // Token information
}
TokenIn
interface TokenIn {
  amountUsd: string;    // Amount in USD
  chainId: number;      // Chain ID
  address: string;      // Token address
  symbol: string;       // Token symbol
  name: string;         // Token name
  decimals: number;     // Token decimals
  amount?: string;      // Optional token amount
}
Fees
interface Fees {
  gas: TokenIn;         // Gas fee information
}

Advanced Usage

Handling Multiple NFTs

You can purchase multiple NFTs in a single transaction by including multiple items in the items array:

const { status, data } = useLego({
  items: [
    { address: '0x123...', tokenId: '1' },
    { address: '0x123...', tokenId: '2' },
    { address: '0x456...', tokenId: '3' }
  ],
  token: {
    address: '0xabc...',
    decimals: 18,
    chainId: 1
  },
  userAddress: '0x789...'
});

Manual Refetching

You can manually trigger a refetch of the data using the refetch function:

const { refetch } = useLego({ /* ... */ });

// Later in your code
const handleRefresh = () => {
  refetch();
};

Error Handling

The hook provides detailed error information that you can use to give feedback to users:

const { error } = useLego({ /* ... */ });

useEffect(() => {
  if (error) {
    // Display error notification to user
    showNotification({
      title: 'Purchase Error',
      message: error,
      type: 'error'
    });
  }
}, [error]);

Integration with wagmi

The SDK can be easily integrated with wagmi for wallet connections and executing transactions. Below is an example of how to use the SDK with wagmi:

Setting up with wagmi

import { useAccount, useSendTransaction } from "wagmi";
import { useLego } from '@shogun-sdk/money-legos-react';

function NFTPurchaseWithWagmi() {
  // Get the connected wallet address using wagmi
  const { address } = useAccount();
  
  // Use the useLego hook with the wallet address
  const { status, error, data, isLoading } = useLego({
    token: {
      address: "0x0000000000000000000000000000000000000000", // Native token (ETH/BASE)
      decimals: 18,
      chainId: 8453, // Base chain ID
    },
    items: [
      {
        address: "0x1c812b7733fbf2dfa5a08b551f969aa702915ade", // NFT contract address
        tokenId: "4892", // Token ID to purchase
      },
    ],
    userAddress: address as string,
  });
  
  // Use wagmi's sendTransaction hook to execute the transaction
  const { sendTransactionAsync } = useSendTransaction();
  
  // Function to execute the NFT purchase transaction
  const handleBuyNFT = async () => {
    try {
      if (!data) return;
      const { steps } = data;
      
      // Execute each transaction step
      for (const step of steps) {
        const txHash = await sendTransactionAsync({
          to: step.to as `0x${string}`,
          data: step.data as `0x${string}`,
          value: BigInt(step.value),
          chainId: step.chainId,
          gas: BigInt(step.gas),
          maxFeePerGas: BigInt(step.maxFeePerGas),
          maxPriorityFeePerGas: BigInt(step.maxPriorityFeePerGas),
        });
        console.log(`NFT purchase successful. Transaction hash: ${txHash}`);
      }
    } catch (error) {
      console.log({ error });
    }
  };
  
  if (isLoading) return <div>Preparing purchase...</div>;
  if (error) return <div>Error: {error}</div>;
  
  return (
    <div>
      {status && data && (
        <button onClick={handleBuyNFT} disabled={!address}>
          Buy NFT with wagmi
        </button>
      )}
    </div>
  );
}

Complete Example with wagmi Provider

Here's a complete example showing how to set up both the ShogunLegoProvider and wagmi's Providers:

import { ShogunLegoProvider } from '@shogun-sdk/money-legos-react';
import { WagmiConfig, createConfig, configureChains } from 'wagmi';
import { base } from 'wagmi/chains';
import { publicProvider } from 'wagmi/providers/public';
import { MetaMaskConnector } from 'wagmi/connectors/metaMask';

// Configure wagmi
const { chains, publicClient } = configureChains(
  [base],
  [publicProvider()]
);

const config = createConfig({
  autoConnect: true,
  connectors: [
    new MetaMaskConnector({ chains })
  ],
  publicClient
});

function App() {
  return (
    <WagmiConfig config={config}>
      <ShogunLegoProvider apiKey="YOUR_API_KEY">
        <NFTPurchaseWithWagmi />
      </ShogunLegoProvider>
    </WagmiConfig>
  );
}

Shogun SDK React Integration

Overview

The Shogun SDK React is a TypeScript library that enables cross-chain swaps and transfers between EVM chains and Solana. It provides quote fetching, transaction execution, and fee management capabilities.

Installation

npm install @shogun-sdk/money-legos-react

or

yarn add @shogun-sdk/money-legos-react

Features

  • Cross-chain token swaps between EVM chains and Solana
  • Quote fetching for optimal swap rates
  • Transaction execution management
  • Fee estimation and management
  • Balance tracking across chains
  • React hooks and context providers for seamless integration

Requirements

  • Node.js 16 or higher
  • TypeScript 4.5 or higher

Quick Start

import { useShogunQuote } from '@shogun-sdk/money-legos';

...

function SwapComponent() {
    const { quote, isLoading, error } = useShogunQuote({
        fromChain: 'ethereum',
        toChain: 'solana',
        fromToken: '0x...',
        toToken: '...',
        amount: '1000000000000000000'
    });
}

React providers

'use client';
import { useSwap } from '@/store';
import { ShogunBalancesProvider, ShogunQuoteProvider, Token } from '@shogun-sdk/money-legos';
import { useMemo } from 'react';

export const ShogunProvider = ({ children }: { children: React.ReactNode }) => {
  const {
    inputAmount,
    tokenIn,
    tokenOut,
    recipientAddress,
    slippage,
    setLatestSuggestedAutoSlippageValue,
    setInputAmount,
    dynamicSlippage // true/false, only for Solana transactions
  } = useSwap(); // Your swaps store

  const yourAddresses = {....} // Here your wallet addresses

  const affiliateWallets = useMemo(() => {
    return {
      solana: process.env.NEXT_PUBLIC_SOLANA_AFFILIATE_WALLET!, // Your affiliate wallet on solana
      evm: process.env.NEXT_PUBLIC_EVM_AFFILIATE_WALLET!, // Your affiliate wallet on evm chains
    };
  }, []);

  const api = useMemo(() => {
    return {
      key: process.env.NEXT_PUBLIC_DEXTRA_X_API_KEY!, // Dextra API keys
      url: process.env.NEXT_PUBLIC_DEXTRA_URL!, // Dextra API URL
    };
  }, []);

  return (
    <ShogunBalancesProvider apiKey={process.env.NEXT_PUBLIC_CODEX_API!}>
      <ShogunQuoteProvider
        swap={{
          tokenIn: tokenIn as Token,
          tokenOut: tokenOut as Token,
          setLatestSuggestedAutoSlippageValue,
          inputAmount,
          setInputAmount,
          recipientAddress,
          slippage,
        }}
        system={{
          api,
          systemFeePercent: 0.01,
          userEVMAddress: yourAddresses?.turnKeyEVMAddress as string,
          userSolanaAddress: yourAddresses?.turnkeySolanaAddress as string,
          affiliateWallets,
        }}
      >
        {children}
      </ShogunQuoteProvider>
    </ShogunBalancesProvider>
  );
};

Development

Install dependencies

npm install

Build the package

npm run build

Run tests

npm test

Format code

npm run format

Lint code

npm run lint

Contributing Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

Package Sidebar

Install

npm i @shogun-sdk/money-legos-react

Weekly Downloads

15

Version

1.1.70

License

ISC

Unpacked Size

233 kB

Total Files

44

Last publish

Collaborators

  • ebrahimshogun
  • garageinc