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
export const CONTRACT_ADDRESSES = {
MAINNET: {
address: '0x...',
chainId: 1
},
BASE_SEPOLIA: {
address: '0x37adC0e3fd070365CE7A0C385A5d0DB69F405Fa0',
chainId: 84532
},
B3_TESTNET: {
address: '0xcD5758669D2732B9a00d168329d55cE7Ff4B745B',
chainId: 1993
}
}
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
const makerAssets = [{
contractAddress: '0xTOKEN1',
amount: 1000000000000000000n,
assetType: 0,
chainId: 84532n,
tokenId: 0n
}];
const takerAssets = [{
contractAddress: '0xTOKEN2',
amount: 5000000000000000000n,
assetType: 0,
chainId: 1993n,
tokenId: 0n
}];
await sdk.lockAssets(sessionId, makerAssets, 84532);
const hash = await sdk.createTrade(
sessionId,
makerAddress,
takerAddress,
makerAssets,
takerAssets,
1993n
);
sdk.watchTrade(sessionId, (status) => {
console.log('Trade status:', status);
});
3. Relayer Setup and Usage
import { CrossChainRelayer } from 'tran-p2pswap';
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 }
});
await relayer.executeTradeAcrossChains(sessionId);
Relayer Key Management
Encrypting Private Key
import { encrypt } from 'tran-p2pswap/utils';
const password = process.env.KEY_PASSWORD;
const privateKey = process.env.RELAYER_PRIVATE_KEY;
const encryptedKey = await encrypt(privateKey, password);
Decrypting Private Key
import { decrypt } from 'tran-p2pswap/utils';
const decryptedKey = await decrypt(encryptedKey, password);
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') {
await relayer.handleFailedExecution(sessionId);
} else if (error.code === 'INVALID_PROOF') {
console.error('Invalid proof:', error);
}
}
Event Monitoring
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
yarn install
yarn build
yarn test
yarn lint
Contributing
- Fork the repository
- Create feature branch
- Commit changes
- Push to branch
- Create Pull Request
License
Copyright © 2025 NPC Labs, Inc. All rights reserved.