@bagel-rwa/sdk
v1.0.16
Published
SDK for integrating with the Bagels Fractionalized NFT DeFi Platform smart contracts
Maintainers
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 compatibilityupdateAppraisalToUSD()- Fix existing NFT appraisals to USD formatvalidateAppraisalForLending()- Check NFT value compatibility and detect unit mismatchesconvertETHToUSDAppraisal()- Convert ETH values to USD formatgetAppraisalValueInFormat()- Convert between different decimal formats
LendingService Enhancements
approveNFTForLending()- Approve NFTs for lending contractisNFTApprovedForLending()- Check NFT approval statusvalidateLoanParameters()- Comprehensive loan validation before creationgetRecommendedLoanAmount()- 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
- Installation & Setup
- Usage Modes
- AssetNFTService
- FractionalizationService
- LendingService
- AuctionService
- IndexVaultService
- LaunchpadService
- AssetFractionalTokenService
- GovernanceService
- ChainlinkService
- Usage Patterns
Installation & Setup
npm install @bagel-rwa/sdk wagmi viem ethersBackend 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 addressassetType: string- Type of asset (e.g., "artwork", "collectible", "real_estate")physicalLocation: string- Physical location/custody informationappraisalValue: bigint- Appraised value in weicustodian: string- Address of the asset custodianauthenticityCertHash: string- IPFS hash of authenticity certificatemetadataURI: 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 IDowner- Current owner addressassetType- Type of assetphysicalLocation- Physical locationappraisalValue- Current appraised valuelastAppraisalDate- Last appraisal timestampisAuthenticated- Authentication statuscustodian- Custodian addressauthenticityCertHash- Certificate hashisCrossChain- Cross-chain statusoriginChain- Original blockchainmetadata- 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 addressgetAppraisalHistory(tokenId: bigint)- Get historical appraisal valuescreateMetadata()- Helper to create properly formatted metadata objectsformatAssetForDisplay()- Format asset information for UI displayapprove(),getApproved(),setApprovalForAll()- Standard NFT approval methodssafeTransferFrom(),transferFrom()- Standard NFT transfer methods
🆕 Enhanced Helper Methods
mintAssetWithUSDAppraisal()
Create NFT with USD appraisal value (recommended for lending compatibility).
Parameters:
to: string- Recipient addressassetType: string- Type of assetphysicalLocation: string- Physical locationappraisalValueUSD: number- USD value as a number (e.g., 10000 for $10,000)custodian: string- Custodian addressauthenticityCertHash: string- Certificate hashmetadataURI: string- Metadata URIloanTokenDecimals?: 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 updateappraisalValueUSD: number- New USD valueloanTokenDecimals?: 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 validateexpectedLoanTokenDecimals?: 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 weiethPriceUSD: number- ETH price in USDloanTokenDecimals?: 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 IDtargetDecimals: 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 addresstokenId: bigint- NFT token IDfractionalSupply: bigint- Total supply of fractional tokensreservePrice: bigint- Minimum price for redemptioncustodianEndpoint: string- API endpoint for custodian verificationoptions?: { 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 votecastVote(assetId: string, inFavor: boolean, shares: bigint)- Cast a voteexecuteVotingResult(assetId: string)- Execute vote result
Administrative Methods
updateAssetStatus(assetId: string, newStatus: AssetStatus)- Update asset statusemergencyFreeze(assetId: string, reason: string)- Emergency freezeupdateReservePrice(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 addresstokenId: bigint- NFT token IDloanToken: string- Loan token address (e.g., USDC)loanAmount: bigint- Requested loan amountinterestRate: 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 addresscollateralAmount: bigint- Collateral amountloanToken: string- Loan token addressloanAmount: bigint- Requested loan amountinterestRate: bigint- Interest rateduration: bigint- Loan duration
createFractionalTokenLoan()
Create a loan using fractional tokens as collateral with enhanced security verification.
Parameters:
fractionalTokenContract: string- Fractional token contract addresscollateralAmount: bigint- Amount of fractional tokens as collateralloanToken: string- Loan token address (e.g., USDC)loanAmount: bigint- Requested loan amountinterestRate: 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 interestisLiquidatable(loanId: bigint)- Check if a loan can be liquidatedgetUserLoans(user: string)- Get all loan IDs for a usergetLoansByBorrower(borrower: string)- Get detailed loan information for a borrowergetActiveLoans()- Get all active loans in the systemcalculateHealthRatio(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 addresstokenId: 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 addresstokenId: 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 addresstokenId: bigint- Token IDloanToken: string- Loan token addressloanAmount: 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 addresstokenId: bigint- Token IDloanToken: string- Loan token addresstargetLtvPercentage?: 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 addressbaseRate: bigint- Base interest rate in basis pointsreserveFactor: bigint- Reserve factor in basis points
depositLiquidity()
Deposit tokens into liquidity pool to earn yield.
Parameters:
token: string- Token addressamount: bigint- Amount to deposit
Returns: Object with LP tokens received and transaction hash
withdrawLiquidity()
Withdraw tokens from liquidity pool.
Parameters:
token: string- Token addresslpTokenAmount: 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 addresstoken: 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 addresscollateralTokenId: bigint- Token IDcollateralAmount: bigint- Amount (for ERC-20s)isNFT: boolean- Whether asset is an NFTstartPrice: bigint- Starting bid pricereservePrice: bigint- Reserve priceduration: bigint- Auction duration in secondspaymentToken: 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 auctiongetUserAuctions(user: string)- Get auctions created by a usergetActiveAuctions()- Get all active auctionsgetAuctionsBySeller(seller: string)- Get auctions by a specific sellergetAuctionsEndingSoon(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 depositreceiver: 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 withdrawreceiver: string- Address to receive the assetsowner: string- Owner of the shares
redeem(shares: bigint, receiver: string, owner: string)
Redeem shares for underlying assets.
Parameters:
shares: bigint- Amount of shares to redeemreceiver: string- Address to receive the assetsowner: 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 addresstokenId: bigint- Token ID (for NFTs)amount: bigint- Amount to add to vaultweight: 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 addressname: string- Vault namesymbol: string- Vault token symboltotalAssets: bigint- Total assets under managementtotalSupply: bigint- Total share supplysharePrice: bigint- Current share pricemanagementFee: bigint- Management fee (basis points)performanceFee: bigint- Performance fee (basis points)manager: string- Vault manager addressisActive: boolean- Whether vault is active
getVaultAssets()
Get all assets in the vault portfolio.
Returns: Array of VaultAsset objects containing:
tokenAddress: string- Asset contract addresstokenId: bigint- Token IDamount: bigint- Amount heldweight: bigint- Portfolio weightlastPrice: bigint- Last recorded pricelastUpdated: 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 percentageannualizedReturn: bigint- Annualized returnsharpeRatio: bigint- Risk-adjusted return metricmaxDrawdown: bigint- Maximum portfolio declinevolatility: bigint- Portfolio volatilityassetsUnderManagement: 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 balancetargetAllocation: 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 IDprice: bigint- Sale price in weipaymentToken?: 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 purchasevalue?: 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 addresstokenAmount: bigint- Amount of tokens to sellpricePerToken: bigint- Price per token in weipaymentToken?: string- Payment token addressduration?: 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 IDtokenAmount: bigint- Amount of tokens to purchasevalue?: 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 IDofferAmount: bigint- Offer amountpaymentToken?: string- Payment tokenduration?: number- Offer expiration timevalue?: 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 detailsgetFractionalListing(listingId: bigint)- Get fractional token listing detailsgetOffer(offerId: bigint)- Get offer detailsgetUserNFTListings(user: string)- Get user's NFT listingsgetUserFractionalListings(user: string)- Get user's fractional token listingsgetUserOffers(user: string)- Get user's offersgetUserPurchases(user: string)- Get user's purchase historygetStats()- Get platform statistics
Security & Configuration
isVerifiedNFTContract(contractAddress: string)- Check if NFT contract is verifiedisSupportedPaymentToken(tokenAddress: string)- Check payment token supportgetPlatformFee()- Get current platform feegetTreasury()- Get treasury address
Utility Methods
calculateFractionalTokenPrice(tokenAmount: bigint, pricePerToken: bigint)- Calculate total pricecalculatePlatformFee(amount: bigint, platformFeeBps: bigint)- Calculate platform feecalculateRoyaltyFee(amount: bigint, royaltyBps: bigint)- Calculate royalty feeformatTimestamp(timestamp: bigint)- Format timestamp to DateisListingExpired(expiresAt: bigint)- Check if listing is expiredisOfferExpired(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
assetIdandreservePriceproperties - 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);