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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@b3dotfun/p2pswap

v0.2.6

Published

SDK for P2P Asset Swap Protocol

Downloads

80

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.