TypeScript SDK

The Cart.fun TypeScript SDK provides a comprehensive set of utilities for interacting with the Cart.fun protocol on Solana. The SDK enables developers to build applications that leverage the full capabilities of the protocol.

Installation

To use the Cart.fun TypeScript SDK, you'll need to install the package and its dependencies:

npm install @cartdotfun/sdk @solana/web3.js @project-serum/anchor

Then import the SDK in your TypeScript application:

import { CartProtocol } from "@cartdotfun/sdk";
import { Connection, Keypair } from "@solana/web3.js";

Requirements

  • Node.js 14.x or higher
  • TypeScript 4.x or higher
  • Familiarity with Solana development

Configuration

Initialize the SDK with your Solana connection and wallet:

import { Connection, Keypair } from '@solana/web3.js'
import { CartProtocol, NetworkType } from '@cartdotfun/sdk'

// Create a connection to the Solana network
const connection = new Connection('https://api.devnet.solana.com', 'confirmed')

// Load a wallet (in production, use a more secure method)
const wallet = Keypair.fromSecretKey(/* your secret key */)

// Initialize the Cart.fun SDK
const cartProtocol = new CartProtocol({
  connection,
  wallet, // Optional: only needed for transactions that require signing
  network: NetworkType.Devnet, // Or NetworkType.Mainnet for production
})

Network Types

The SDK supports different network environments:

  • Name
    NetworkType.Devnet
    Type
    enum
    Description

    Solana's development network for testing.

  • Name
    NetworkType.Testnet
    Type
    enum
    Description

    Solana's test network for pre-production validation.

  • Name
    NetworkType.Mainnet
    Type
    enum
    Description

    Solana's main production network.

  • Name
    NetworkType.Localnet
    Type
    enum
    Description

    Local development network running on your machine.

Core Concepts

Accounts

All data in the Cart.fun protocol is stored in Solana accounts. These accounts follow a specific structure:

interface Account {
  publicKey: PublicKey // The account's public key
  data: any // The account's deserialized data
}

PDAs (Program Derived Addresses)

The protocol uses PDAs to derive deterministic addresses for accounts:

// Example: Finding a marketplace PDA
const [marketplacePDA] = await PublicKey.findProgramAddress(
  [
    Buffer.from('marketplace'),
    platformPublicKey.toBuffer(),
    Buffer.from(marketplaceId),
  ],
  programId,
)

Transactions

Most operations in the SDK return a transaction that must be signed and sent to the network:

// Create a new product
const { transaction } = await cartProtocol.product.createProduct({
  marketplaceId: 'your-marketplace-id',
  productData: {
    name: 'Digital Product',
    description: 'A digital product on Cart.fun',
    price: 1000000000, // In lamports (1 SOL)
    // Additional product data...
  },
})

// Sign and send the transaction
const signature = await cartProtocol.sendAndConfirmTransaction(transaction)
console.log('Product created:', signature)

Protocol Operations

The Protocol module provides core functionality for interacting with the Cart.fun protocol.

Initialization

// Initialize the Protocol module
const protocol = cartProtocol.protocol;

// Check if the protocol is initialized
const isInitialized = await protocol.isInitialized();

// Get protocol settings
const settings = await protocol.getSettings();

Treasury Management

// Get protocol fee account
const feeAccount = await protocol.getFeeAccount();

// Get protocol treasury balance
const balance = await protocol.getTreasuryBalance();

// Withdraw from treasury (admin only)
const { transaction } = await protocol.withdrawFromTreasury({
  amount: 1000000000, // 1 SOL in lamports
  destination: recipientPublicKey,
});

Platform Operations

The Platform module allows you to create and manage commerce platforms within the protocol.

// Initialize the Platform module
const platform = cartProtocol.platform

// Create a new platform
const { transaction: createTransaction } = await platform.createPlatform({
  name: 'My Commerce Platform',
  description: 'A platform for digital products',
  feePercentage: 2.5, // 2.5% platform fee
  owner: ownerPublicKey, // Optional, defaults to wallet.publicKey
})

// Get all platforms
const platforms = await platform.getAllPlatforms()

// Get a specific platform
const myPlatform = await platform.getPlatform(platformId)

// Update platform details
const { transaction: updateTransaction } = await platform.updatePlatform({
  platformId: 'your-platform-id',
  name: 'Updated Platform Name',
  description: 'Updated description',
  feePercentage: 3.0,
})

Marketplace Operations

The Marketplace module enables the creation and management of marketplaces within platforms.

// Initialize the Marketplace module
const marketplace = cartProtocol.marketplace

// Create a marketplace
const { transaction: createTransaction } = await marketplace.createMarketplace({
  platformId: 'your-platform-id',
  name: 'NFT Marketplace',
  description: 'A marketplace for NFTs',
  categories: ['art', 'collectibles', 'gaming'],
  feePercentage: 1.5, // 1.5% marketplace fee
})

// Get all marketplaces
const allMarketplaces = await marketplace.getAllMarketplaces()

// Get marketplaces for a specific platform
const platformMarketplaces =
  await marketplace.getMarketplacesByPlatform(platformId)

// Get marketplace details
const myMarketplace = await marketplace.getMarketplace(marketplaceId)

Vendor Operations

The Vendor module allows users to register as vendors and manage their vendor profiles.

// Initialize the Vendor module
const vendor = cartProtocol.vendor

// Register as a vendor
const { transaction: registerTransaction } = await vendor.registerVendor({
  name: 'My Store',
  description: 'Digital products store',
  contactInfo: 'contact@example.com',
  platformId: 'your-platform-id',
})

// Get vendor details
const myVendor = await vendor.getVendor(vendorId)

// Update vendor profile
const { transaction: updateTransaction } = await vendor.updateVendor({
  vendorId: 'your-vendor-id',
  name: 'Updated Store Name',
  description: 'Updated store description',
  contactInfo: 'updated@example.com',
})

// Get all vendors for a platform
const platformVendors = await vendor.getVendorsByPlatform(platformId)

Product Operations

The Product module provides functionality for creating and managing digital products.

// Initialize the Product module
const product = cartProtocol.product

// Create a new product
const { transaction: createTransaction } = await product.createProduct({
  marketplaceId: 'your-marketplace-id',
  vendorId: 'your-vendor-id',
  name: 'Digital Art #1',
  description: 'Limited edition digital artwork',
  price: 1000000000, // 1 SOL in lamports
  inventory: 10, // Optional: limited inventory
  metadata: {
    // Additional metadata
    fileType: 'image/png',
    dimensions: '3000x3000',
    category: 'art',
  },
})

// Get product details
const myProduct = await product.getProduct(productId)

// Update product
const { transaction: updateTransaction } = await product.updateProduct({
  productId: 'your-product-id',
  price: 1500000000, // 1.5 SOL in lamports
  inventory: 5,
  // Other fields to update...
})

// Get products by marketplace
const marketplaceProducts =
  await product.getProductsByMarketplace(marketplaceId)

// Get products by vendor
const vendorProducts = await product.getProductsByVendor(vendorId)

AI Module Integration

The AI module enables integration with Rig AI for enhanced commerce experiences.

// Initialize the AI module
const ai = cartProtocol.ai

// Generate product recommendations
const recommendations = await ai.generateRecommendations({
  userPublicKey: userPublicKey,
  marketplaceId: 'your-marketplace-id',
  limit: 5,
})

// Generate product description
const { description, tags } = await ai.generateProductDescription({
  productName: 'Digital Art Collection',
  category: 'art',
  keyFeatures: ['high resolution', 'animated', 'exclusive'],
})

// Process natural language query
const searchResults = await ai.processQuery({
  marketplaceId: 'your-marketplace-id',
  query: 'animated digital art under 2 SOL',
  limit: 10,
})

Error Handling

The SDK provides standardized error handling with detailed error codes and messages.

import { CartError, ErrorCode } from '@cartdotfun/sdk'

try {
  await cartProtocol.product.getProduct('non-existent-id')
} catch (error) {
  if (error instanceof CartError) {
    console.error(`Error code: ${error.code}, Message: ${error.message}`)

    // Check for specific error types
    if (error.code === ErrorCode.ProductNotFound) {
      console.log('The product was not found')
    } else if (error.code === ErrorCode.InsufficientPermissions) {
      console.log("You don't have permission to perform this action")
    }
  } else {
    console.error('Unknown error:', error)
  }
}

Common Error Codes

  • Name
    ErrorCode.InvalidInput
    Type
    enum
    Description

    Input parameters are invalid or missing.

  • Name
    ErrorCode.InsufficientFunds
    Type
    enum
    Description

    Not enough funds to complete the transaction.

  • Name
    ErrorCode.InsufficientPermissions
    Type
    enum
    Description

    User lacks permission to perform the action.

  • Name
    ErrorCode.NotInitialized
    Type
    enum
    Description

    The protocol or component is not initialized.

  • Name
    ErrorCode.AlreadyExists
    Type
    enum
    Description

    The entity already exists.

  • Name
    ErrorCode.NotFound
    Type
    enum
    Description

    The requested entity was not found.

  • Name
    ErrorCode.TransactionFailed
    Type
    enum
    Description

    Transaction failed to execute.

Advanced Usage

Transaction Simulation

Simulate transactions before sending them to check for errors:

const { transaction } = await cartProtocol.product.createProduct({
  // Product parameters...
})

// Simulate the transaction
const simulationResult = await cartProtocol.simulateTransaction(transaction)

if (simulationResult.success) {
  console.log('Simulation successful, sending transaction...')
  const signature = await cartProtocol.sendAndConfirmTransaction(transaction)
  console.log('Transaction successful:', signature)
} else {
  console.error('Simulation failed:', simulationResult.error)
}

Batch Transactions

Combine multiple operations into a single transaction:

// Create a transaction batch
const batch = cartProtocol.createBatch()

// Add operations to the batch
await batch.add(
  cartProtocol.product.createProductInstruction({
    /* product params */
  }),
)

await batch.add(
  cartProtocol.marketplace.updateMarketplaceInstruction({
    /* marketplace params */
  }),
)

// Build and send the transaction
const { transaction } = await batch.build()
const signature = await cartProtocol.sendAndConfirmTransaction(transaction)

Examples

Complete Marketplace Setup

async function setupMarketplace() {
  // 1. Create a platform
  const { transaction: platformTx, platformId } =
    await cartProtocol.platform.createPlatform({
      name: 'Digital Art Platform',
      description: 'Platform for digital art and collectibles',
      feePercentage: 2.0,
    })
  await cartProtocol.sendAndConfirmTransaction(platformTx)
  console.log('Platform created with ID:', platformId)

  // 2. Create a marketplace
  const { transaction: marketplaceTx, marketplaceId } =
    await cartProtocol.marketplace.createMarketplace({
      platformId,
      name: 'Premium Art Collection',
      description: 'Curated digital art marketplace',
      categories: ['premium', 'art', 'collectible'],
      feePercentage: 1.5,
    })
  await cartProtocol.sendAndConfirmTransaction(marketplaceTx)
  console.log('Marketplace created with ID:', marketplaceId)

  // 3. Register as a vendor
  const { transaction: vendorTx, vendorId } =
    await cartProtocol.vendor.registerVendor({
      platformId,
      name: 'Creative Studios',
      description: 'Digital art creator collective',
      contactInfo: 'studio@example.com',
    })
  await cartProtocol.sendAndConfirmTransaction(vendorTx)
  console.log('Vendor registered with ID:', vendorId)

  // 4. Create a product
  const { transaction: productTx, productId } =
    await cartProtocol.product.createProduct({
      marketplaceId,
      vendorId,
      name: 'Cosmic Horizons #1',
      description: 'Limited edition digital artwork exploring space themes',
      price: 2500000000, // 2.5 SOL
      metadata: {
        fileType: 'image/png',
        dimensions: '4000x4000',
        edition: '1 of 10',
      },
    })
  await cartProtocol.sendAndConfirmTransaction(productTx)
  console.log('Product created with ID:', productId)

  return { platformId, marketplaceId, vendorId, productId }
}

For more examples and detailed usage, refer to the Example Applications documentation.

Was this page helpful?