JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 67
  • Score
    100M100P100Q57333F
  • License Copyright © 2025 NPC Labs, Inc. All rights reserved.

SDK for P2P Asset Swap Protocol

Package Exports

  • @b3dotfun/p2pswap
  • @b3dotfun/p2pswap/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@b3dotfun/p2pswap) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Cross-Chain P2P Swap SDK

A TypeScript SDK for executing secure peer-to-peer asset swaps across different blockchains with relayer support.

Overview

The Cross-Chain P2P Swap SDK enables secure and trustless asset swaps between different blockchain networks. It supports:

  • Cross-chain and single-chain asset swaps
  • Multiple asset types (ERC20, ERC721, ERC1155, Native tokens)
  • Multi-relayer verification system
  • Automatic trade execution and monitoring
  • Failure recovery and automatic rollbacks
  • Secure relayer key management

Installation

yarn add tran-p2pswap

Core Components

CrossChainSwapSDK

The main SDK for users to interact with the swap protocol:

Key Features

  • Asset locking and unlocking
  • Trade creation and monitoring
  • Status tracking and event handling
  • Proof generation and verification
  • Multi-chain support

Methods

  • lockAssets: Lock assets on specified chain
  • createTrade: Create new trade with locked assets
  • unlockAssets: Unlock assets if trade fails
  • watchTrade: Monitor trade execution status
  • getTrade: Get trade details
  • getTradeStatus: Check current trade status
  • isTradeValid: Validate trade conditions
  • generateLockProof: Generate proof of locked assets

CrossChainRelayer

Automated relayer service for executing cross-chain trades:

Key Features

  • Automated trade execution
  • Multi-chain transaction handling
  • Failure recovery
  • Status monitoring
  • Secure key management

Methods

  • createTrade: Create trades on both chains
  • executeTradeAcrossChains: Execute cross-chain trades
  • trackExecutionStatus: Monitor execution status
  • handleFailedExecution: Handle and recover from failures
  • generateCancelProof: Generate proof for trade cancellation

Supported Networks

// Contract addresses for supported networks
export const CONTRACT_ADDRESSES = {
    MAINNET: {
        address: '0x...',
        chainId: 1
    },
    BASE_SEPOLIA: {
        address: '0x37adC0e3fd070365CE7A0C385A5d0DB69F405Fa0',
        chainId: 84532
    },
    B3_TESTNET: {
        address: '0xcD5758669D2732B9a00d168329d55cE7Ff4B745B',
        chainId: 1993
    }
    // ... other networks
}

Usage Examples

1. Initialize SDK

import { CrossChainSwapSDK, CONTRACT_ADDRESSES } from 'tran-p2pswap';
import { createPublicClient, http } from 'viem';

const sdk = new CrossChainSwapSDK({
    sourceChain: {
        contractAddress: CONTRACT_ADDRESSES.BASE_SEPOLIA.address,
        chainId: 84532,
        publicClient: createPublicClient({
            chain: baseSepolia,
            transport: http()
        })
    },
    targetChain: {
        contractAddress: CONTRACT_ADDRESSES.B3_TESTNET.address,
        chainId: 1993,
        publicClient: createPublicClient({
            chain: b3Testnet,
            transport: http()
        })
    },
    walletClient
});

2. Create and Execute Trade

// Define assets
const makerAssets = [{
    contractAddress: '0xTOKEN1',
    amount: 1000000000000000000n,
    assetType: 0, // ERC20
    chainId: 84532n,
    tokenId: 0n
}];

const takerAssets = [{
    contractAddress: '0xTOKEN2',
    amount: 5000000000000000000n,
    assetType: 0, // ERC20
    chainId: 1993n,
    tokenId: 0n
}];

// Lock assets
await sdk.lockAssets(sessionId, makerAssets, 84532);

// Create trade
const hash = await sdk.createTrade(
    sessionId,
    makerAddress,
    takerAddress,
    makerAssets,
    takerAssets,
    1993n
);

// Monitor status
sdk.watchTrade(sessionId, (status) => {
    console.log('Trade status:', status);
});

3. Relayer Setup and Usage

import { CrossChainRelayer } from 'tran-p2pswap';

// Initialize relayer with encrypted private key
const relayer = new CrossChainRelayer({
    sourceClient,
    targetClient,
    sourceWalletClient,
    targetWalletClient,
    sourceAddress: CONTRACT_ADDRESSES.BASE_SEPOLIA.address,
    targetAddress: CONTRACT_ADDRESSES.B3_TESTNET.address,
    sourceChain: { id: 84532 },
    targetChain: { id: 1993 }
});

// Execute cross-chain trade
await relayer.executeTradeAcrossChains(sessionId);

Relayer Key Management

Encrypting Private Key

import { encrypt } from 'tran-p2pswap/utils';

// Encrypt relayer's private key
const password = process.env.KEY_PASSWORD;
const privateKey = process.env.RELAYER_PRIVATE_KEY;

const encryptedKey = await encrypt(privateKey, password);
// Store encryptedKey securely

Decrypting Private Key

import { decrypt } from 'tran-p2pswap/utils';

// Decrypt when needed
const decryptedKey = await decrypt(encryptedKey, password);

// Use decrypted key to create wallet client
const walletClient = createWalletClient({
    account: privateKeyToAccount(decryptedKey),
    chain: baseChain,
    transport: http()
});

Security Best Practices

  • Never store unencrypted private keys
  • Use environment variables for sensitive data
  • Implement key rotation
  • Clear decrypted keys from memory
  • Use secure key storage solutions
  • Regular security audits

Error Handling

try {
    await relayer.executeTradeAcrossChains(sessionId);
} catch (error) {
    if (error.code === 'EXECUTION_FAILED') {
        // Handle execution failure
        await relayer.handleFailedExecution(sessionId);
    } else if (error.code === 'INVALID_PROOF') {
        // Handle invalid proof error
        console.error('Invalid proof:', error);
    }
    // Handle other errors
}

Event Monitoring

// Watch trade execution events
sdk.watchTrade(sessionId, (status) => {
    switch (status.status) {
        case 'completed':
            console.log('Trade completed successfully');
            break;
        case 'failed':
            console.log('Trade failed:', status.reason);
            break;
        case 'pending':
            console.log('Trade in progress');
            break;
    }
});

Development

# Install dependencies
yarn install

# Build
yarn build

# Test
yarn test

# Lint
yarn lint

Contributing

  1. Fork the repository
  2. Create feature branch
  3. Commit changes
  4. Push to branch
  5. Create Pull Request

License

Copyright © 2025 NPC Labs, Inc. All rights reserved.