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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bagel-rwa/sdk

v1.0.16

Published

SDK for integrating with the Bagels Fractionalized NFT DeFi Platform smart contracts

Readme

Fractionalized NFT Platform SDK - Complete Service Documentation

A comprehensive TypeScript SDK for interacting with the Fractionalized NFT Platform smart contracts. This SDK provides a simple and type-safe interface for all platform operations including enhanced Chainlink integrations, cross-chain functionality, and advanced governance features.

🔄 Automatic Nonce Management

This SDK features built-in automatic nonce management for all transactions using a custom NonceManager implementation compatible with ethers v6. This ensures reliable transaction execution when sending multiple transactions rapidly.

Features:

  • Automatic Nonce Tracking: Each transaction gets the correct nonce automatically
  • Rapid Transaction Support: Send multiple transactions simultaneously without nonce conflicts
  • Error Recovery: Manual nonce management tools for error recovery scenarios
  • Ethers v6 Compatible: Works seamlessly with the latest ethers.js version

🆕 Enhanced Helper Methods

This SDK now includes comprehensive helper methods to simplify common operations and prevent errors:

AssetNFTService Enhancements

  • mintAssetWithUSDAppraisal() - Create NFTs with proper USD values for lending compatibility
  • updateAppraisalToUSD() - Fix existing NFT appraisals to USD format
  • validateAppraisalForLending() - Check NFT value compatibility and detect unit mismatches
  • convertETHToUSDAppraisal() - Convert ETH values to USD format
  • getAppraisalValueInFormat() - Convert between different decimal formats

LendingService Enhancements

  • approveNFTForLending() - Approve NFTs for lending contract
  • isNFTApprovedForLending() - Check NFT approval status
  • validateLoanParameters() - Comprehensive loan validation before creation
  • getRecommendedLoanAmount() - Get safe loan amounts based on collateral value
  • Enhanced createNFTLoan() - Now supports auto-approval for seamless loan creation
  • Liquidity Pool Methods - Complete pool management and yield earning functionality

Key Benefits

  • Prevents Unit Mismatch Errors - Automatic conversion between ETH and USD formats
  • Pre-Transaction Validation - Catch issues before submitting transactions
  • Auto-Approval Workflows - Simplify multi-step processes into single calls
  • Comprehensive Error Reporting - Detailed feedback for debugging
  • Backward Compatibility - Existing code continues to work unchanged

Table of Contents

  1. Installation & Setup
  2. Usage Modes
  3. AssetNFTService
  4. FractionalizationService
  5. LendingService
  6. AuctionService
  7. IndexVaultService
  8. LaunchpadService
  9. AssetFractionalTokenService
  10. GovernanceService
  11. ChainlinkService
  12. Usage Patterns

Installation & Setup

npm install @bagel-rwa/sdk wagmi viem ethers

Backend Setup

import { BagelsRWA, ethers } from '@bagel-rwa/sdk';

// Initialize with signer
const provider = new ethers.JsonRpcProvider('YOUR_RPC_URL');
const wallet = new ethers.Wallet('PRIVATE_KEY', provider);

const sdk = new BagelsRWA({
  usageType: 'Backend',
  networkConfig: {
    chainId: 1,
    name: 'mainnet',
    rpcUrl: 'YOUR_RPC_URL'
  },
  contractAddresses: {
    assetNFT: '0x...',
    fractionalizationVault: '0x...',
    lendingContract: '0x...',
    auctionContract: '0x...',
    indexVault: '0x...',
    governanceContract: '0x...', // optional
    governanceToken: '0x...' // optional
  },
  signer: wallet
});

Frontend Setup

// hooks/useSDK.ts
import { BagelsRWA } from '@bagel-rwa/sdk';
import { useMemo } from 'react';

export function useSDK() {
  return useMemo(() => new BagelsRWA({
    usageType: 'Frontend',
    networkConfig: {
      chainId: 1,
      name: 'mainnet',
      rpcUrl: 'YOUR_RPC_URL'
    },
    contractAddresses: {
      assetNFT: '0x...',
      fractionalizationVault: '0x...',
      lendingContract: '0x...',
      auctionContract: '0x...',
      indexVault: '0x...'
    }
  }), []);
}

Usage Modes

The SDK supports two distinct usage modes optimized for different environments:

Backend Mode (Default)

For server-side applications or direct blockchain interaction:

const sdk = new BagelsRWA({
  usageType: 'Backend', // or omit for default
  signer: yourEthersSigner,
  // ... config
});

// Executes transaction directly
const result = await sdk.assetNFT.mintAsset(/* args */);
console.log('Transaction hash:', result.txHash);
console.log('Token ID:', result.tokenId);

Frontend Mode (wagmi Integration)

For React frontend applications using wagmi:

import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi';

function MintComponent() {
  const sdk = useSDK();
  const { data: hash, writeContract, isPending } = useWriteContract();
  
  const { isLoading: isConfirming, isSuccess: isConfirmed } =
    useWaitForTransactionReceipt({ hash });

  const handleMint = async () => {
    // Returns wagmi-compatible contract call object
    const contractCall = await sdk.assetNFT.mintAsset(/* args */);
    writeContract(contractCall);
  };

  return (
    <div>
      <button onClick={handleMint} disabled={isPending}>
        {isPending ? 'Confirming...' : 'Mint Asset'}
      </button>
      {hash && <div>Transaction Hash: {hash}</div>}
      {isConfirming && <div>Waiting for confirmation...</div>}
      {isConfirmed && <div>Transaction confirmed!</div>}
    </div>
  );
}

AssetNFTService

The AssetNFTService handles NFT minting, metadata management, and cross-chain transfers with Chainlink integration.

Core Methods

mintAsset()

Mint a new asset NFT with enhanced metadata and custodial information.

Parameters:

  • to: string - Recipient address
  • assetType: string - Type of asset (e.g., "artwork", "collectible", "real_estate")
  • physicalLocation: string - Physical location/custody information
  • appraisalValue: bigint - Appraised value in wei
  • custodian: string - Address of the asset custodian
  • authenticityCertHash: string - IPFS hash of authenticity certificate
  • metadataURI: string - URI pointing to asset metadata

Backend Usage:

const result = await sdk.assetNFT.mintAsset(
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b",
  "artwork",
  "Secure Storage Facility, NYC",
  ethers.parseEther("100"), // $100 ETH equivalent
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b",
  ethers.keccak256(ethers.toUtf8Bytes("cert-hash")),
  "https://ipfs.io/ipfs/QmExample"
);

console.log('Token ID:', result.tokenId);
console.log('Transaction Hash:', result.txHash);

Frontend Usage with wagmi:

// Component
function MintAssetComponent() {
  const sdk = useSDK();
  const { writeContract, isPending } = useWriteContract();
  
  const handleMint = async () => {
    const contractCall = await sdk.assetNFT.mintAsset(
      to,
      assetType,
      physicalLocation,
      BigInt(appraisalValue),
      custodian,
      authenticityCertHash,
      metadataURI
    );
    
    writeContract(contractCall);
  };
}

getAssetInfo(tokenId: bigint)

Retrieve comprehensive information about an asset.

Returns: AssetInfo object containing:

  • tokenId - Token ID
  • owner - Current owner address
  • assetType - Type of asset
  • physicalLocation - Physical location
  • appraisalValue - Current appraised value
  • lastAppraisalDate - Last appraisal timestamp
  • isAuthenticated - Authentication status
  • custodian - Custodian address
  • authenticityCertHash - Certificate hash
  • isCrossChain - Cross-chain status
  • originChain - Original blockchain
  • metadata - Asset metadata

Usage (Both Modes):

const assetInfo = await sdk.assetNFT.getAssetInfo(BigInt(1));
console.log('Asset Owner:', assetInfo.owner);
console.log('Appraisal Value:', ethers.formatEther(assetInfo.appraisalValue));
console.log('Is Authenticated:', assetInfo.isAuthenticated);

updateAssetInfo(tokenId: bigint, appraisalValue: bigint, physicalLocation: string)

Update asset appraisal value and physical location.

Backend Usage:

const txHash = await sdk.assetNFT.updateAssetInfo(
  BigInt(1),
  ethers.parseEther("150"), // New value
  "Updated Storage Location"
);

Frontend Usage:

const contractCall = await sdk.assetNFT.updateAssetInfo(
  tokenId,
  newAppraisalValue,
  newLocation
);
writeContract(contractCall);

requestMetadataUpdate(tokenId: bigint)

Request metadata update via Chainlink Functions.

Returns: Object with requestId and txHash

transferCrossChain(tokenId: bigint, destinationChainSelector: bigint, recipient: string)

Transfer NFT to another blockchain using Chainlink CCIP.

estimateCrossChainFee(tokenId: bigint, destinationChain: bigint, recipient: string)

Estimate fees for cross-chain transfer.

Returns: bigint - Fee amount in wei

Utility Methods

  • getTokensOwnedBy(owner: string) - Get all token IDs owned by an address
  • getAppraisalHistory(tokenId: bigint) - Get historical appraisal values
  • createMetadata() - Helper to create properly formatted metadata objects
  • formatAssetForDisplay() - Format asset information for UI display
  • approve(), getApproved(), setApprovalForAll() - Standard NFT approval methods
  • safeTransferFrom(), transferFrom() - Standard NFT transfer methods

🆕 Enhanced Helper Methods

mintAssetWithUSDAppraisal()

Create NFT with USD appraisal value (recommended for lending compatibility).

Parameters:

  • to: string - Recipient address
  • assetType: string - Type of asset
  • physicalLocation: string - Physical location
  • appraisalValueUSD: number - USD value as a number (e.g., 10000 for $10,000)
  • custodian: string - Custodian address
  • authenticityCertHash: string - Certificate hash
  • metadataURI: string - Metadata URI
  • loanTokenDecimals?: number - Decimal precision (default: 6 for USDC)

Backend Usage:

const result = await sdk.assetNFT.mintAssetWithUSDAppraisal(
  userAddress,
  "artwork",
  "Secure Gallery Storage",
  10000, // $10,000 USD
  custodianAddress,
  ethers.keccak256(ethers.toUtf8Bytes("cert-123")),
  "https://example.com/metadata.json"
  // loanTokenDecimals defaults to 6 for USDC compatibility
);

console.log('Token ID:', result.tokenId);
console.log('Appraisal: $10,000 USD (6 decimals for USDC loans)');

updateAppraisalToUSD()

Update existing NFT appraisal to USD value for lending compatibility.

Parameters:

  • tokenId: bigint - Token ID to update
  • appraisalValueUSD: number - New USD value
  • loanTokenDecimals?: number - Target decimal precision (default: 6)

Usage:

// Fix existing NFT with ETH-denominated appraisal
const txHash = await sdk.assetNFT.updateAppraisalToUSD(
  BigInt(1),
  8500, // $8,500 USD
  6 // USDC decimals
);

validateAppraisalForLending()

Validate NFT appraisal value for lending compatibility and detect unit mismatches.

Parameters:

  • tokenId: bigint - Token ID to validate
  • expectedLoanTokenDecimals?: number - Expected decimals (default: 6)

Returns: Validation object with compatibility status and recommendations

Usage:

const validation = await sdk.assetNFT.validateAppraisalForLending(BigInt(1), 6);

console.log('Compatible:', validation.isCompatible);
console.log('Current Decimals:', validation.currentDecimals);
console.log('Current Value:', ethers.formatUnits(validation.currentValue, validation.currentDecimals));
console.log('Recommended Value:', ethers.formatUnits(validation.recommendedValue, 6), 'USD');

if (validation.issues.length > 0) {
  console.log('Issues:');
  validation.issues.forEach(issue => console.log(' -', issue));
}

convertETHToUSDAppraisal()

Convert ETH-denominated value to USD format for lending.

Parameters:

  • ethValue: bigint - ETH value in wei
  • ethPriceUSD: number - ETH price in USD
  • loanTokenDecimals?: number - Target decimals (default: 6)

Returns: bigint - USD value in target decimal format

Usage:

const ethValue = ethers.parseEther("1"); // 1 ETH
const ethPrice = 2400; // $2400 per ETH

const usdValue = sdk.assetNFT.convertETHToUSDAppraisal(ethValue, ethPrice, 6);
console.log('USD Value:', ethers.formatUnits(usdValue, 6), 'USDC');

getAppraisalValueInFormat()

Get NFT appraisal value converted to different decimal formats.

Parameters:

  • tokenId: bigint - Token ID
  • targetDecimals: number - Target decimal precision

Returns: Object with original and converted values plus conversion details

Usage:

const formatInfo = await sdk.assetNFT.getAppraisalValueInFormat(BigInt(1), 18);

console.log('Original (6 decimals):', ethers.formatUnits(formatInfo.originalValue, 6));
console.log('Converted (18 decimals):', ethers.formatUnits(formatInfo.convertedValue, 18));
console.log('Conversion Ratio:', formatInfo.conversionRatio);

FractionalizationService

Handles NFT fractionalization, yield distribution, and proof of reserve verification.

Core Methods

fractionalize()

Convert an NFT into fractional ERC-20 tokens with proof of reserve.

Parameters:

  • nftContract: string - NFT contract address
  • tokenId: bigint - NFT token ID
  • fractionalSupply: bigint - Total supply of fractional tokens
  • reservePrice: bigint - Minimum price for redemption
  • custodianEndpoint: string - API endpoint for custodian verification
  • options?: { autoApprove?: boolean } - Optional auto-approval

Backend Usage:

// Option 1: Manual approval
await sdk.fractionalization.approveNFTForFractionalization(nftContract, tokenId);
const result = await sdk.fractionalization.fractionalize(
  nftContract,
  tokenId,
  BigInt(1000000), // 1M fractional tokens
  ethers.parseEther("10"), // 10 ETH reserve price
  "https://api.custodian.com/verify"
);

// Option 2: Auto-approval
const result = await sdk.fractionalization.fractionalize(
  nftContract,
  tokenId,
  BigInt(1000000),
  ethers.parseEther("10"),
  "https://api.custodian.com/verify",
  { autoApprove: true }
);

console.log('Asset ID:', result.assetId);
console.log('Transaction Hash:', result.txHash);

Frontend Usage:

// First approve if needed
const approvalCall = await sdk.fractionalization.approveNFTForFractionalization(
  nftContract,
  tokenId
);
if (approvalCall !== 'already-approved') {
  writeContract(approvalCall);
  // Wait for approval, then fractionalize
}

const fractionalizeCall = await sdk.fractionalization.fractionalize(
  nftContract,
  tokenId,
  fractionalSupply,
  reservePrice,
  custodianEndpoint
);
writeContract(fractionalizeCall);

getFractionalizedAsset(assetId: string)

Get detailed information about a fractionalized asset.

Returns: FractionalizationInfo object

getUserShares(assetId: string, user: string)

Get user's share balance for a fractionalized asset.

requestReserveVerification(assetId: string)

Request proof of reserve verification via Chainlink Functions.

Returns: Object with requestId and txHash

distributeYield(assetId: string, value?: bigint)

Distribute yield to fractional token holders.

claimYield(assetId: string)

Claim accumulated yield for a user.

redeemNFT(assetId: string)

Redeem the underlying NFT by burning all fractional tokens.

Voting Methods

  • startVoting(assetId: string, proposedReservePrice: bigint) - Start a governance vote
  • castVote(assetId: string, inFavor: boolean, shares: bigint) - Cast a vote
  • executeVotingResult(assetId: string) - Execute vote result

Administrative Methods

  • updateAssetStatus(assetId: string, newStatus: AssetStatus) - Update asset status
  • emergencyFreeze(assetId: string, reason: string) - Emergency freeze
  • updateReservePrice(assetId: string, newPrice: bigint) - Update reserve price

LendingService

Handles collateralized lending with NFT and fractional token collateral.

Core Methods

createNFTLoan()

Create a loan using an NFT as collateral.

Parameters:

  • collateralContract: string - NFT contract address
  • tokenId: bigint - NFT token ID
  • loanToken: string - Loan token address (e.g., USDC)
  • loanAmount: bigint - Requested loan amount
  • interestRate: bigint - Interest rate (basis points)
  • duration: bigint - Loan duration in seconds

Backend Usage:

const result = await sdk.lending.createNFTLoan(
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b", // NFT contract
  BigInt(1), // Token ID
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b", // USDC address
  ethers.parseUnits("1000", 6), // 1000 USDC
  BigInt(500), // 5% interest rate
  BigInt(30 * 24 * 60 * 60) // 30 days
);

console.log('Loan ID:', result.loanId);
console.log('Transaction Hash:', result.txHash);

Security Features:

  • Contract Verification: Uses vault.verifyTokenContract() to prevent asset ID spoofing
  • Direct Value Calculation: Gets collateral value directly from vault (user cannot manipulate)
  • Anti-Spoofing Protection: Prevents fake fractional token contracts
  • Pool-Funded: Loans funded by community liquidity pools

createTokenLoan()

Create a loan using ERC-20 tokens as collateral.

Parameters:

  • collateralContract: string - Token contract address
  • collateralAmount: bigint - Collateral amount
  • loanToken: string - Loan token address
  • loanAmount: bigint - Requested loan amount
  • interestRate: bigint - Interest rate
  • duration: bigint - Loan duration

createFractionalTokenLoan()

Create a loan using fractional tokens as collateral with enhanced security verification.

Parameters:

  • fractionalTokenContract: string - Fractional token contract address
  • collateralAmount: bigint - Amount of fractional tokens as collateral
  • loanToken: string - Loan token address (e.g., USDC)
  • loanAmount: bigint - Requested loan amount
  • interestRate: bigint - Interest rate (basis points)
  • duration: bigint - Loan duration in seconds

Backend Usage:

const result = await sdk.lending.createFractionalTokenLoan(
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b", // Fractional token contract
  ethers.parseEther("500"), // 500 fractional tokens
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b", // USDC address
  ethers.parseUnits("2000", 6), // 2,000 USDC
  BigInt(0), // Pool-determined interest rate
  BigInt(30 * 24 * 60 * 60) // 30 days
);

console.log('Loan ID:', result.loanId);
console.log('Transaction Hash:', result.txHash);

repayLoan(loanId: bigint, amount: bigint)

Repay a loan partially or fully.

liquidateLoan(loanId: bigint)

Liquidate an unhealthy loan.

getLoan(loanId: bigint)

Get detailed loan information.

Returns: LoanInfo object

Usage:

const loan = await sdk.lending.getLoan(BigInt(1));
console.log('Borrower:', loan.borrower);
console.log('Collateral Type:', loan.collateralType);
console.log('Loan Amount:', ethers.formatUnits(loan.loanAmount, 6));
console.log('Status:', loan.status);

Utility Methods

  • calculateTotalOwed(loanId: bigint) - Calculate total amount owed including interest
  • isLiquidatable(loanId: bigint) - Check if a loan can be liquidated
  • getUserLoans(user: string) - Get all loan IDs for a user
  • getLoansByBorrower(borrower: string) - Get detailed loan information for a borrower
  • getActiveLoans() - Get all active loans in the system
  • calculateHealthRatio(loanId: bigint) - Calculate loan health ratio

🆕 Enhanced Helper Methods

approveNFTForLending()

Approve NFT for lending contract (required before creating NFT-backed loans).

Parameters:

  • nftContract: string - NFT contract address
  • tokenId: bigint - Token ID to approve

Backend Usage:

const txHash = await sdk.lending.approveNFTForLending(nftContract, BigInt(1));
if (txHash !== 'already-approved') {
  console.log('NFT approved:', txHash);
} else {
  console.log('NFT already approved');
}

Frontend Usage:

const approvalCall = await sdk.lending.approveNFTForLending(nftContract, tokenId);
if (approvalCall !== 'already-approved') {
  writeContract(approvalCall);
}

isNFTApprovedForLending()

Check if NFT is approved for lending contract.

Parameters:

  • nftContract: string - NFT contract address
  • tokenId: bigint - Token ID to check

Returns: boolean - Approval status

Usage:

const isApproved = await sdk.lending.isNFTApprovedForLending(nftContract, BigInt(1));
console.log('Is approved:', isApproved);

validateLoanParameters()

Validate loan parameters before creation to catch issues early.

Parameters:

  • collateralContract: string - NFT contract address
  • tokenId: bigint - Token ID
  • loanToken: string - Loan token address
  • loanAmount: bigint - Requested loan amount

Returns: Validation object with detailed analysis

Usage:

const validation = await sdk.lending.validateLoanParameters(
  nftContract,
  BigInt(1),
  usdcAddress,
  ethers.parseUnits("5000", 6) // $5,000 USDC
);

console.log('Is Valid:', validation.isValid);
console.log('LTV Ratio:', validation.ltvRatio.toFixed(2) + '%');
console.log('Max LTV Allowed:', validation.maxLtvAllowed.toFixed(2) + '%');
console.log('Collateral Value:', ethers.formatUnits(validation.collateralValue, 6), 'USD');

if (validation.issues.length > 0) {
  console.log('Issues:');
  validation.issues.forEach(issue => console.log(' -', issue));
}

getRecommendedLoanAmount()

Get recommended loan amounts based on NFT value and target LTV.

Parameters:

  • collateralContract: string - NFT contract address
  • tokenId: bigint - Token ID
  • loanToken: string - Loan token address
  • targetLtvPercentage?: number - Target LTV (default: 60%)

Returns: Object with recommended and maximum loan amounts

Usage:

const recommendations = await sdk.lending.getRecommendedLoanAmount(
  nftContract,
  BigInt(1),
  usdcAddress,
  60 // Target 60% LTV for safety
);

console.log('Recommended Amount (60% LTV):', ethers.formatUnits(recommendations.recommendedAmount, 6), 'USDC');
console.log('Maximum Amount (75% LTV):', ethers.formatUnits(recommendations.maxAmount, 6), 'USDC');
console.log('Collateral Value:', ethers.formatUnits(recommendations.collateralValue, 6), 'USD');

Enhanced createNFTLoan() with Auto-Approval

The createNFTLoan() method now supports auto-approval for seamless loan creation.

New Parameters:

  • options?: { autoApprove?: boolean } - Automatically approve NFT if needed

Backend Usage:

// Option 1: Manual approval (existing workflow)
await sdk.lending.approveNFTForLending(nftContract, tokenId);
const result = await sdk.lending.createNFTLoan(
  nftContract,
  tokenId,
  loanToken,
  loanAmount,
  interestRate,
  duration
);

// Option 2: Auto-approval (new enhanced workflow)
const result = await sdk.lending.createNFTLoan(
  nftContract,
  tokenId,
  loanToken,
  loanAmount,
  interestRate,
  duration,
  { autoApprove: true } // Automatically approve if needed
);

console.log('Loan ID:', result.loanId);
console.log('Transaction Hash:', result.txHash);

🌊 Liquidity Pool Methods

createLiquidityPool()

Create a new liquidity pool for a token (admin only).

Parameters:

  • token: string - Token address
  • baseRate: bigint - Base interest rate in basis points
  • reserveFactor: bigint - Reserve factor in basis points

depositLiquidity()

Deposit tokens into liquidity pool to earn yield.

Parameters:

  • token: string - Token address
  • amount: bigint - Amount to deposit

Returns: Object with LP tokens received and transaction hash

withdrawLiquidity()

Withdraw tokens from liquidity pool.

Parameters:

  • token: string - Token address
  • lpTokenAmount: bigint - LP tokens to redeem

Returns: Object with tokens withdrawn and transaction hash

getLiquidityPool()

Get liquidity pool information.

Parameters:

  • token: string - Token address

Returns: Pool information object

getPoolInterestRates()

Get current interest rates for a pool.

Parameters:

  • token: string - Token address

Returns: Object with borrow and supply rates

calculatePoolAPY()

Calculate APY for pool rates.

Parameters:

  • token: string - Token address

Returns: Object with borrow and supply APY

getAvailableLiquidity()

Get available liquidity in a pool.

Parameters:

  • token: string - Token address

Returns: bigint - Available liquidity amount

getUserPoolInfo()

Get user's position in a liquidity pool.

Parameters:

  • user: string - User address
  • token: string - Token address

Returns: Object with LP balance and underlying value


AuctionService

Handles English and Dutch auctions for NFTs and fractional tokens.

Core Methods

createEnglishAuction()

Create an English (ascending price) auction.

Parameters:

  • collateralContract: string - Asset contract address
  • collateralTokenId: bigint - Token ID
  • collateralAmount: bigint - Amount (for ERC-20s)
  • isNFT: boolean - Whether asset is an NFT
  • startPrice: bigint - Starting bid price
  • reservePrice: bigint - Reserve price
  • duration: bigint - Auction duration in seconds
  • paymentToken: string - Payment token address

Backend Usage:

const result = await sdk.auction.createEnglishAuction(
  "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b", // NFT contract
  BigInt(1), // Token ID
  BigInt(1), // Amount (1 for NFTs)
  true, // Is NFT
  ethers.parseEther("1"), // Start at 1 ETH
  ethers.parseEther("5"), // Reserve at 5 ETH
  BigInt(7 * 24 * 60 * 60), // 7 days
  "0x0000000000000000000000000000000000000000" // ETH
);

console.log('Auction ID:', result.auctionId);

createDutchAuction()

Create a Dutch (descending price) auction with same parameters as English auction.

placeBid(auctionId: bigint, bidAmount: bigint)

Place a bid on an English auction.

buyNow(auctionId: bigint)

Immediately purchase in a Dutch auction.

endAuction(auctionId: bigint)

End an auction and settle.

cancelAuction(auctionId: bigint)

Cancel an auction (before any bids).

getCurrentDutchPrice(auctionId: bigint)

Get current price for a Dutch auction.

getAuction(auctionId: bigint)

Get detailed auction information.

Returns: AuctionInfo object

Query Methods

  • getAuctionBids(auctionId: bigint) - Get all bids for an auction
  • getUserAuctions(user: string) - Get auctions created by a user
  • getActiveAuctions() - Get all active auctions
  • getAuctionsBySeller(seller: string) - Get auctions by a specific seller
  • getAuctionsEndingSoon(hoursThreshold: number) - Get auctions ending soon

IndexVaultService

The IndexVaultService manages ERC-4626 compliant index vaults for diversified NFT exposure, allowing users to invest in a basket of fractional tokens and NFTs with automatic rebalancing and professional management.

Core ERC-4626 Methods

deposit(assets: bigint, receiver: string)

Deposit assets into the vault and receive shares.

Parameters:

  • assets: bigint - Amount of assets to deposit
  • receiver: string - Address to receive the shares

Backend Usage:

const result = await sdk.indexVault.deposit(
  ethers.parseEther("10"), // 10 ETH
  userAddress
);

console.log('Shares Received:', ethers.formatEther(result.shares));
console.log('Transaction Hash:', result.txHash);

Frontend Usage:

const depositCall = await sdk.indexVault.deposit(assets, receiver);
writeContract(depositCall);

withdraw(assets: bigint, receiver: string, owner: string)

Withdraw specific amount of assets from the vault.

Parameters:

  • assets: bigint - Amount of assets to withdraw
  • receiver: string - Address to receive the assets
  • owner: string - Owner of the shares

redeem(shares: bigint, receiver: string, owner: string)

Redeem shares for underlying assets.

Parameters:

  • shares: bigint - Amount of shares to redeem
  • receiver: string - Address to receive the assets
  • owner: string - Owner of the shares

Conversion & Preview Methods

Preview Operations

Preview operations before execution to understand the outcome:

// Preview deposit - how many shares will I get?
const sharesToReceive = await sdk.indexVault.previewDeposit(ethers.parseEther("100"));
console.log('Shares to receive:', ethers.formatEther(sharesToReceive));

// Preview withdrawal - how many shares will be burned?
const sharesToBurn = await sdk.indexVault.previewWithdraw(ethers.parseEther("50"));

// Preview redemption - how many assets will I get?
const assetsToReceive = await sdk.indexVault.previewRedeem(BigInt(1000));

// Preview mint - how many assets needed?
const assetsNeeded = await sdk.indexVault.previewMint(BigInt(500));

Conversion Methods

Convert between assets and shares:

// Convert assets to shares
const shares = await sdk.indexVault.convertToShares(ethers.parseEther("100"));

// Convert shares to assets
const assets = await sdk.indexVault.convertToAssets(BigInt(1000));

getTotalAssets()

Get total assets under management in the vault.

Returns: bigint - Total assets in wei

Portfolio Management Methods (Admin Only)

addAsset(tokenAddress: string, tokenId: bigint, amount: bigint, weight: bigint)

Add a new asset to the vault's portfolio.

Parameters:

  • tokenAddress: string - Token contract address
  • tokenId: bigint - Token ID (for NFTs)
  • amount: bigint - Amount to add to vault
  • weight: bigint - Weight in portfolio (basis points)

Usage:

// Add fractional art token with 20% portfolio weight
await sdk.indexVault.addAsset(
  fractionalTokenAddress,
  BigInt(0), // Not applicable for ERC-20
  ethers.parseEther("1000"),
  2000 // 20% weight (2000 basis points)
);

removeAsset(tokenAddress: string, tokenId: bigint)

Remove an asset from the vault's portfolio.

rebalance()

Rebalance the vault portfolio according to target weights.

Usage:

// Trigger portfolio rebalancing
const txHash = await sdk.indexVault.rebalance();
console.log('Rebalancing completed:', txHash);

Query & Analytics Methods

getVaultInfo()

Get comprehensive vault information.

Returns: IndexVaultInfo object containing:

  • vaultAddress: string - Vault contract address
  • name: string - Vault name
  • symbol: string - Vault token symbol
  • totalAssets: bigint - Total assets under management
  • totalSupply: bigint - Total share supply
  • sharePrice: bigint - Current share price
  • managementFee: bigint - Management fee (basis points)
  • performanceFee: bigint - Performance fee (basis points)
  • manager: string - Vault manager address
  • isActive: boolean - Whether vault is active

getVaultAssets()

Get all assets in the vault portfolio.

Returns: Array of VaultAsset objects containing:

  • tokenAddress: string - Asset contract address
  • tokenId: bigint - Token ID
  • amount: bigint - Amount held
  • weight: bigint - Portfolio weight
  • lastPrice: bigint - Last recorded price
  • lastUpdated: bigint - Last price update

getUserShares(user: string)

Get user's share balance in the vault.

Returns: bigint - User's share balance

getUserAssetValue(user: string)

Get USD value of user's vault position.

Returns: bigint - Position value in USD (scaled)

getPerformanceMetrics()

Get detailed vault performance metrics.

Returns: Object containing:

  • totalReturn: bigint - Total return percentage
  • annualizedReturn: bigint - Annualized return
  • sharpeRatio: bigint - Risk-adjusted return metric
  • maxDrawdown: bigint - Maximum portfolio decline
  • volatility: bigint - Portfolio volatility
  • assetsUnderManagement: bigint - Total AUM

getUserHistory(user: string)

Get user's transaction history with the vault.

Returns: Array of transaction objects with deposits, withdrawals, and performance

calculateOptimalDeposit(userBalance: bigint, targetAllocation: number)

Calculate optimal deposit amount based on user balance and target allocation.

Parameters:

  • userBalance: bigint - User's available balance
  • targetAllocation: number - Target allocation percentage (0-1)

Returns: bigint - Recommended deposit amount

getAssetHistory()

Get historical changes to the vault's asset composition.

Returns: Array of asset addition/removal events

Usage Examples

Complete Investment Flow

// 1. Check vault info
const vaultInfo = await sdk.indexVault.getVaultInfo();
console.log('Vault Name:', vaultInfo.name);
console.log('Total AUM:', ethers.formatEther(vaultInfo.totalAssets));
console.log('Share Price:', ethers.formatEther(vaultInfo.sharePrice));

// 2. Preview deposit
const depositAmount = ethers.parseEther("5");
const expectedShares = await sdk.indexVault.previewDeposit(depositAmount);
console.log('Expected shares:', ethers.formatEther(expectedShares));

// 3. Make deposit
const result = await sdk.indexVault.deposit(depositAmount, userAddress);
console.log('Actual shares received:', ethers.formatEther(result.shares));

// 4. Check portfolio
const assets = await sdk.indexVault.getVaultAssets();
assets.forEach(asset => {
  console.log(`Asset: ${asset.tokenAddress}`);
  console.log(`Weight: ${Number(asset.weight) / 100}%`);
  console.log(`Amount: ${ethers.formatEther(asset.amount)}`);
});

// 5. Track performance
const performance = await sdk.indexVault.getPerformanceMetrics();
console.log('Total Return:', `${Number(performance.totalReturn) / 100}%`);
console.log('Annualized Return:', `${Number(performance.annualizedReturn) / 100}%`);

Frontend Dashboard Component

function VaultDashboard() {
  const sdk = useSDK();
  const [vaultInfo, setVaultInfo] = useState(null);
  const [userShares, setUserShares] = useState(BigInt(0));
  const [performance, setPerformance] = useState(null);

  useEffect(() => {
    const loadVaultData = async () => {
      const info = await sdk.indexVault.getVaultInfo();
      const shares = await sdk.indexVault.getUserShares(userAddress);
      const perf = await sdk.indexVault.getPerformanceMetrics();
      
      setVaultInfo(info);
      setUserShares(shares);
      setPerformance(perf);
    };

    loadVaultData();
  }, []);

  return (
    <div>
      <h2>{vaultInfo?.name} - Index Vault</h2>
      <div>
        <p>Your Shares: {ethers.formatEther(userShares)}</p>
        <p>Share Price: {ethers.formatEther(vaultInfo?.sharePrice || 0)}</p>
        <p>Total AUM: {ethers.formatEther(vaultInfo?.totalAssets || 0)}</p>
        <p>Total Return: {Number(performance?.totalReturn || 0) / 100}%</p>
      </div>
    </div>
  );
}

Security Features

  • ERC-4626 Compliance: Standard vault interface ensures composability
  • Professional Management: Only authorized managers can modify portfolio
  • Transparent Fees: Management and performance fees clearly defined
  • Automated Rebalancing: Maintains target portfolio allocation
  • Real-time Valuation: Assets priced using Chainlink oracles

LaunchpadService

The LaunchpadService provides a secure marketplace for trading NFTs and fractional tokens with built-in anti-fraud protection and automated royalty distribution.

Core Interfaces

interface NFTListing {
  listingId: bigint;
  seller: string;
  nftContract: string;
  tokenId: bigint;
  price: bigint;
  paymentToken: string;
  createdAt: bigint;
  expiresAt: bigint;
  status: number;
  hasRoyalty: boolean;
  royaltyRecipient: string;
  royaltyBps: bigint;
}

interface FractionalTokenListing {
  listingId: bigint;
  seller: string;
  fractionalTokenContract: string;
  assetId: string;
  tokenAmount: bigint;
  pricePerToken: bigint;
  paymentToken: string;
  createdAt: bigint;
  expiresAt: bigint;
  status: number;
  reservePrice: bigint;
  totalSupply: bigint;
}

interface Offer {
  offerId: bigint;
  listingId: bigint;
  buyer: string;
  offerAmount: bigint;
  paymentToken: string;
  createdAt: bigint;
  expiresAt: bigint;
  status: number;
  listingType: number;
}

NFT Listing Methods

listNFT()

List an NFT for sale with automatic royalty detection and verification.

Parameters:

  • nftContract: string - NFT contract address (must be verified)
  • tokenId: bigint - NFT token ID
  • price: bigint - Sale price in wei
  • paymentToken?: string - Payment token address (default: ETH)
  • duration?: number - Listing duration in seconds (0 = no expiry)

Backend Usage:

const result = await sdk.launchpad.listNFT({
  nftContract: "0x742d35Cc6631C0532925a3b8D2D28A1D28f5b",
  tokenId: BigInt(1),
  price: ethers.parseEther("5"), // 5 ETH
  paymentToken: ethers.ZeroAddress, // ETH
  duration: 86400 * 7 // 7 days
});

console.log('Listing ID:', result.listingId);
console.log('Transaction Hash:', result.hash);

Frontend Usage:

const listingCall = await sdk.launchpad.listNFT({
  nftContract,
  tokenId,
  price,
  paymentToken,
  duration
});
writeContract(listingCall);

purchaseNFT()

Purchase an NFT directly from a listing with automatic royalty distribution.

Parameters:

  • listingId: bigint - ID of the listing to purchase
  • value?: bigint - ETH value to send (for ETH payments)

cancelNFTListing()

Cancel an active NFT listing.

Fractional Token Methods

listFractionalTokens()

List fractional tokens for sale with integrated verification.

Parameters:

  • fractionalTokenContract: string - Fractional token contract address
  • tokenAmount: bigint - Amount of tokens to sell
  • pricePerToken: bigint - Price per token in wei
  • paymentToken?: string - Payment token address
  • duration?: number - Listing duration

Backend Usage:

const result = await sdk.launchpad.listFractionalTokens({
  fractionalTokenContract: "0x...",
  tokenAmount: BigInt(1000), // 1000 tokens
  pricePerToken: ethers.parseEther("0.01"), // 0.01 ETH per token
  paymentToken: usdcAddress,
  duration: 86400 * 30 // 30 days
});

purchaseFractionalTokens()

Purchase fractional tokens with partial purchase support.

Parameters:

  • listingId: bigint - Listing ID
  • tokenAmount: bigint - Amount of tokens to purchase
  • value?: bigint - ETH value for payment

getFractionalTokenPriceInfo()

Get detailed pricing information for fractional token listings.

Returns: FractionalTokenPriceInfo with market premium calculations

Offer System

makeNFTOffer()

Make an offer on an NFT listing with escrow protection.

Parameters:

  • listingId: bigint - Target listing ID
  • offerAmount: bigint - Offer amount
  • paymentToken?: string - Payment token
  • duration?: number - Offer expiration time
  • value?: bigint - ETH value for escrow

acceptNFTOffer()

Accept an offer on your NFT listing.

cancelOffer()

Cancel a pending offer and withdraw escrowed funds.

View Methods

  • getNFTListing(listingId: bigint) - Get NFT listing details
  • getFractionalListing(listingId: bigint) - Get fractional token listing details
  • getOffer(offerId: bigint) - Get offer details
  • getUserNFTListings(user: string) - Get user's NFT listings
  • getUserFractionalListings(user: string) - Get user's fractional token listings
  • getUserOffers(user: string) - Get user's offers
  • getUserPurchases(user: string) - Get user's purchase history
  • getStats() - Get platform statistics

Security & Configuration

  • isVerifiedNFTContract(contractAddress: string) - Check if NFT contract is verified
  • isSupportedPaymentToken(tokenAddress: string) - Check payment token support
  • getPlatformFee() - Get current platform fee
  • getTreasury() - Get treasury address

Utility Methods

  • calculateFractionalTokenPrice(tokenAmount: bigint, pricePerToken: bigint) - Calculate total price
  • calculatePlatformFee(amount: bigint, platformFeeBps: bigint) - Calculate platform fee
  • calculateRoyaltyFee(amount: bigint, royaltyBps: bigint) - Calculate royalty fee
  • formatTimestamp(timestamp: bigint) - Format timestamp to Date
  • isListingExpired(expiresAt: bigint) - Check if listing is expired
  • isOfferExpired(expiresAt: bigint) - Check if offer is expired

AssetFractionalTokenService

The AssetFractionalTokenService provides interaction with individual asset-specific ERC-20 fractional token contracts, each with built-in governance capabilities for democratic reserve price updates.

Overview

Each fractionalized asset gets its own dedicated ERC-20 token contract with:

  • Asset-Specific Identity: Immutable assetId and reservePrice properties
  • Built-in Governance: Token holders can vote on reserve price updates
  • Standard ERC-20: Full compatibility with existing DeFi protocols
  • Security: Prevents asset ID spoofing through contract address verification

Creating Service Instance


## Asset Enumeration

The AssetNFT contract now supports ERC721Enumerable, making it easy to get assets held by users:

### Get All Assets Owned by a User

```typescript
// Get all token IDs owned by a user
const userAddress = "0x123...";
const tokenIds = await sdk.assetNFT.getTokensByOwner(userAddress);
console.log(`User owns ${tokenIds.length} assets:`, tokenIds);

// Get complete asset information for all tokens owned by a user
const userAssets = await sdk.assetNFT.getAssetsByOwner(userAddress);
userAssets.forEach(asset => {
  console.log(`Token ${asset.tokenId}: ${asset.assetType} worth ${asset.appraisalValue}`);
});

// Get assets with pagination (recommended for large collections)
const paginatedAssets = await sdk.assetNFT.getAssetsByOwnerPaginated(
  userAddress, 
  0,    // offset
  10    // limit
);
console.log(`Showing ${paginatedAssets.assets.length} of ${paginatedAssets.totalCount} assets`);
console.log(`Has more: ${paginatedAssets.hasMore}`);

Access Individual Tokens by Index

// Get total supply
const totalSupply = await sdk.assetNFT.getTotalSupply();
console.log(`Total tokens minted: ${totalSupply}`);

// Get token by global index
const firstToken = await sdk.assetNFT.getTokenByIndex(0n);
console.log(`First token ID: ${firstToken}`);

// Get user's token by index
const userTokenCount = await sdk.assetNFT.getBalance(userAddress);
if (userTokenCount > 0n) {
  const userFirstToken = await sdk.assetNFT.getTokenOfOwnerByIndex(userAddress, 0n);
  console.log(`User's first token: ${userFirstToken}`);
}

Get Detailed Token Information

const tokenId = 1n;
const tokenDetails = await sdk.assetNFT.getTokenDetails(tokenId);

console.log({
  tokenId: tokenDetails.tokenId,
  owner: tokenDetails.owner,
  metadataURI: tokenDetails.metadataURI,
  assetType: tokenDetails.assetInfo.assetType,
  appraisalValue: tokenDetails.assetInfo.appraisalValue,
  isAuthenticated: tokenDetails.assetInfo.isAuthenticated
});

Backward Compatibility

The existing getTokensOwnedBy() method still works and now uses the efficient enumerable implementation:

// This method is still available and now more efficient
const tokens = await sdk.assetNFT.getTokensOwnedBy(userAddress);