UNPKG

@goequitize/rwa-token-sdk

Version:

SDK for creating and managing RWA token transactions with compliance features

346 lines (265 loc) 9.13 kB
# @goequitize/rwa-token-sdk A comprehensive SDK for creating and managing RWA (Real World Asset) token transactions with compliance features. This SDK provides a straightforward way to interact with RWA tokens without needing to understand the underlying smart contracts. ## Features - Create unsigned transactions for mint, burn, transfer, and admin operations - Validate transactions against compliance rules (whitelist, paused state, roles) - Sign transactions server-side or pass them to client-side for signing - Broadcast signed transactions and track their status - **Unified EVM chain support** with configurable parameters for any EVM-compatible blockchain - Gas estimation and optimization - Cross-chain transfers using LayerZero's OFT standard ## Installation ```bash npm install @goequitize/rwa-token-sdk # or yarn add @goequitize/rwa-token-sdk ``` ## Usage ### Initializing the SDK ```typescript import { RwaTokenSDK } from '@goequitize/rwa-token-sdk'; // Initialize the SDK with your network configuration const rwaTokenSDK = new RwaTokenSDK( { rpcUrl: 'https://mainnet.infura.io/v3/YOUR_INFURA_KEY', chainId: 1, // Ethereum Mainnet apiKey: 'YOUR_API_KEY' // Optional }, '0xYourRWATokenContractAddress', // Token address '0xYourWalletAddress' // Sender address for building transactions ); ``` ### Custom Chain Configuration For non-standard EVM chains or to override default behavior: ```typescript import { RwaTokenSDK, EvmChainConfig } from '@goequitize/rwa-token-sdk'; // Custom chain configuration const customConfig: Partial<EvmChainConfig> = { explorerUrl: 'https://explorer.customchain.com/tx/${txHash}', chainName: 'My Custom Chain', gasModel: 'legacy', // 'legacy', 'eip1559', or 'custom' functionNames: { // If your contract uses different function names forceTransfer: 'adminTransfer', isWhitelisted: 'isAllowed', paused: 'isPaused' } }; const rwaTokenSDK = new RwaTokenSDK( { rpcUrl: 'https://rpc.customchain.com', chainId: 1234 }, '0xYourRWATokenContractAddress', '0xYourWalletAddress', customConfig ); ``` ### Getting Token Information ```typescript // Get token decimals const decimals = await rwaTokenSDK.getDecimals(); // Get token symbol const symbol = await rwaTokenSDK.getSymbol(); // Get token balance const balance = await rwaTokenSDK.getTokenBalance('0xAddress'); console.log(`Balance: ${balance} ${symbol}`); ``` ### Building Transactions #### Mint Transaction ```typescript const mintResult = await rwaTokenSDK.buildMintTxn({ to: '0xRecipientAddress', amount: '100' // Human-readable amount (e.g., 100 tokens) }); if (!mintResult.isError) { const { rawTx, gasCost, gasPrice, gasLimit } = mintResult.data; console.log(`Estimated gas cost: ${gasCost} ETH`); // Pass rawTx to frontend for signing or sign server-side } else { console.error(`Error: ${mintResult.errorMsg}`); } ``` #### Burn Transaction ```typescript const burnResult = await rwaTokenSDK.buildBurnTxn({ from: '0xAddressToBurnFrom', amount: '50' // Human-readable amount (e.g., 50 tokens) }); if (!burnResult.isError) { const { rawTx } = burnResult.data; // Handle transaction } ``` #### Transfer Transaction ```typescript const transferResult = await rwaTokenSDK.buildTransferTxn({ to: '0xRecipientAddress', amount: '25' // Human-readable amount (e.g., 25 tokens) }); if (!transferResult.isError) { const { rawTx } = transferResult.data; // Handle transaction } ``` #### Admin Operations ```typescript // Pause all transfers const pauseResult = await rwaTokenSDK.buildPauseTxn(); // Unpause transfers const unpauseResult = await rwaTokenSDK.buildUnpauseTxn(); // Force transfer between addresses (admin override) const forceTransferResult = await rwaTokenSDK.buildForcedTransferTxn({ from: '0xFromAddress', to: '0xToAddress', amount: '10' }); ``` ### Cross-Chain Transfers The SDK supports cross-chain transfers using LayerZero's OFT (Omnichain Fungible Token) standard: ```typescript import { RwaTokenSDK } from '@goequitize/rwa-token-sdk'; // Initialize the SDK const sdk = new RwaTokenSDK( { rpcUrl: 'https://mainnet.infura.io/v3/YOUR_KEY', chainId: 1 // Ethereum Mainnet }, '0xYourTokenAddress', '0xYourSenderAddress' ); // LayerZero chain IDs const LAYERZERO_CHAIN_IDS = { ETHEREUM: 101, BSC: 102, POLYGON: 109, AVALANCHE: 106, ARBITRUM: 110, OPTIMISM: 111, FANTOM: 112, }; // Build a cross-chain transfer transaction const result = await sdk.buildCrossChainTransferTxn({ to: '0xYourSenderAddress', // The address that will send the tokens amount: '100', // Amount in human-readable format destinationChainId: LAYERZERO_CHAIN_IDS.BSC, // BSC on LayerZero destinationAddress: '0xRecipientOnBSC', // The address that will receive the tokens on BSC }); if (!result.isError && result.data) { // Use the transaction console.log('Raw transaction:', result.data.rawTx); console.log('Gas cost:', result.data.gasCost, 'ETH'); // Sign and broadcast the transaction const signedTx = await sdk.signTxn(result.data.rawTx, privateKey); const txResponse = await sdk.broadcast(signedTx); console.log(`Transaction hash: ${txResponse.hash}`); console.log(`Explorer URL: ${txResponse.explorerURL}`); } ``` ### Signing and Broadcasting ```typescript // For server-side signing const privateKey = 'YOUR_PRIVATE_KEY'; // Handle securely! const signedTxn = await rwaTokenSDK.signTxn(rawTx, privateKey); // Broadcast the signed transaction const txResponse = await rwaTokenSDK.broadcast(signedTxn); console.log(`Transaction hash: ${txResponse.hash}`); console.log(`Explorer URL: ${txResponse.explorerURL}`); ``` ### Transaction Tracking ```typescript // Get transaction status and logs const txStatus = await rwaTokenSDK.getTxnLogs(txResponse.hash); if (txStatus.status === 'success') { console.log('Transaction successful!'); console.log('Logs:', txStatus.logs); } else if (txStatus.status === 'pending') { console.log('Transaction is still pending...'); } else { console.log('Transaction failed!'); } ``` ## Advanced Usage ### Gas Estimation ```typescript const gasInfo = await rwaTokenSDK.getGasInfo('mint'); console.log('Market Gas Prices:'); console.log(`Gas Price: ${gasInfo.market.gasPrice} gwei`); console.log(`Max Fee Per Gas: ${gasInfo.market.maxFeePerGas} gwei`); console.log('Recommended Gas Prices (with markup):'); console.log(`Gas Price: ${gasInfo.recommended.gasPrice} gwei`); console.log(`Max Fee Per Gas: ${gasInfo.recommended.maxFeePerGas} gwei`); ``` ## API Reference ### Main SDK Class - `RwaTokenSDK` - Primary class for interacting with RWA tokens ### Token Information Methods - `getDecimals(tokenAddress?)` - Get token decimals - `getSymbol(tokenAddress?)` - Get token symbol - `getTokenBalance(address, tokenAddress?)` - Get token balance for an address ### Transaction Building Methods - `buildMintTxn({ to, amount })` - Build a mint transaction - `buildBurnTxn({ from, amount })` - Build a burn transaction - `buildTransferTxn({ to, amount })` - Build a transfer transaction - `buildForcedTransferTxn({ from, to, amount })` - Build a forced transfer transaction - `buildPauseTxn()` - Build a pause transaction - `buildUnpauseTxn()` - Build an unpause transaction - `buildCrossChainTransferTxn(params: { to: string; amount: string; destinationChainId: number; destinationAddress: string; adapterParams?: string; }): Promise<TxBuildResult>` - Build a cross-chain transfer transaction ### Transaction Handling Methods - `signTxn(rawTx, privateKey)` - Sign a transaction with a private key - `broadcast(signedTxn)` - Broadcast a signed transaction - `getTxnLogs(txHash)` - Get transaction logs and status - `getGasInfo(txnType?)` - Get gas price information ## Development ### Setup ```bash git clone https://github.com/goequitize/rwa-token-sdk.git cd rwa-token-sdk npm install ``` ### Build ```bash npm run build ``` ### Test ```bash npm test ``` ### Run Example ```bash npm run example ``` ## Chain Support The SDK uses a unified EVM implementation that works across all EVM-compatible chains with appropriate configuration. Default configurations are included for: - Ethereum (Mainnet, Goerli, Sepolia) - Binance Smart Chain (Mainnet, Testnet) - Polygon (Mainnet, Mumbai) Any other EVM-compatible chain can be used by providing a custom configuration: ```typescript const avalancheConfig: Partial<EvmChainConfig> = { explorerUrl: 'https://snowtrace.io/tx/${txHash}', chainName: 'Avalanche C-Chain', gasModel: 'eip1559' }; const arbitrumConfig: Partial<EvmChainConfig> = { explorerUrl: 'https://arbiscan.io/tx/${txHash}', chainName: 'Arbitrum One', gasModel: 'eip1559' }; ``` ## Extending the SDK The SDK is designed to be easily extensible for other blockchain ecosystems beyond EVM chains. The architecture uses an abstract base class that can be implemented for any blockchain: ```typescript // For example, to add Solana support in the future: class SolanaRwaToken extends RwaTokenBase { // Implement Solana-specific methods } ``` ## License MIT