🍁Deposit/Withdraw from Foreign Chain (BSC) and Add Order , Buy and Sell Token, Just a 277 Code Lines!
Below sample explained how to build a simple exchange operation using with PSce
The provided code is an example of a trading and order management system designed to operate on the Pirichain Smart Scenario platform. It handles the swap of BNB and PIRI coins, and includes functions for liquidity management, placing and removing orders, and checking wallet balances.
Key Features
Transaction Initialization and Status Check:
The swapInitialize function initializes the order books (asks and bids) and price data for a specific trading pair (BNB_PIRI).
Wallet Balance Check:
Functions like checkMyBNBDeposit and depositToken check the balances of BNB and PIRI tokens in the user’s wallet and, if sufficient, add liquidity to the pool.
Wallet Blocking:
The blockWallet and unBlockWallet functions allow the blocking and unblocking of wallet addresses based on specific conditions.
Buy/Sell Orders:
The buyToken and sellToken functions search for orders with a given timestamp (ask or bid), check if the user has enough balance, and if so, execute the buy or sell order.
Order Management:
Users can create and remove buy (addBid) and sell (addAsk) orders. These functions also handle order removal (removeMyBid, removeMyAsk).
Withdrawal of Liquidity:
The withdrawBnbWallet and withdrawToken functions allow users to withdraw their BNB or PIRI token balances from the platform to their own wallets.
Usage
Liquidity Management in Exchanges:
This system can be applied in decentralized exchanges (DEX) or liquidity pools to manage the liquidity for BNB and PIRI tokens.
Wallet Status and Security:
Security mechanisms, such as blocking wallets and suspending transactions, are integrated into the system.
Example Use Cases
Initializing Trading for a BNB and PIRI Pair:
Users can call the swapInitialize function to set up the liquidity and order books for BNB and PIRI coins.
Placing and Removing Orders:
Users can place bids and asks at a specific level (level) and quantity (quantity), or remove them if needed.
Withdrawing Liquidity:
Users can withdraw their available BNB or PIRI token balances from the system using withdrawBnbWallet or withdrawToken functions.
This structure can be used to build a DEX protocol on Pirichain, or enhance existing exchange integrations by providing automated, blockchain-based trading and liquidity management.
// PIRICHAIN SWAP INTEGRATION FOR BNB CHAIN BNB COINconstparity='BNB_PIRI';constslippage=0.15;asyncfunctionswapInitialize(){PSDATA[parity]={};PSDATA[parity].asks=[];PSDATA[parity].bids=[];PSDATA['lastPrice']=0;PSDATA['volumeDaily']=[];PSDATA['slippageFeeCrypto']=0;PSDATA['slippageFeeToken']=0;constresult=awaitMap.saveMap(JSON.stringify(PSDATA));return result;}asyncfunctioncheckMyBNBDeposit(){constmyBalanceObj=awaitgetBnbWalletBalance();constmyBalance=parseFloat(myBalanceObj.data);consthasTx=awaitTransaction.checkPoolTransaction(EXECUTER_ADDRESS);if (hasTx.data)return {error:1,message:'There is a transaction processing... System cannot start a new transaction..'};if (myBalance>0) {let withdrawalResultForPSCE={};checkWalletInitialization();if (ORIGINFLAG) {constscenarioWeb3WalletAddress=awaitcreatePSceBnbWallet(); withdrawalResultForPSCE=awaitwithdrawBnbWallet(scenarioWeb3WalletAddress.data); }PSDATA[EXECUTER_ADDRESS].liquidityCrypto+=myBalance;constdepositLiqResult=awaitMap.saveMap(JSON.stringify(PSDATA));return {depositLiqResult:depositLiqResult,withdrawalResultForPSCE:withdrawalResultForPSCE}; }elsereturn {error:1,message:'There is no BNB at your address'};}asyncfunctiondepositToken(){if (isNaN(ASSETID))return {error:-1,message:'AssetID Must be declared,cannot be NAN!'};if (ASSETID!==-1)return {error:-1,message:'AssetID Must be -1 for PIRI Coin!'};if (isNaN(AMOUNT))return {error:-1,message:'Amount Must be declared,cannot be NAN!'};if (AMOUNT<=0)return {error:-1,message:'Amount Must be declared, cannot be zero or negative!'};checkWalletInitialization();PSDATA[EXECUTER_ADDRESS].liquidityToken+=AMOUNT;constdepositTokenResult=awaitMap.saveMap(JSON.stringify(PSDATA));return depositTokenResult;}asyncfunctiongetMyDepositWallet(){returnawaitcreateBnbWallet();}asyncfunctioncheckWalletInitialization(){if (PSDATA[EXECUTER_ADDRESS]==undefined) {PSDATA[EXECUTER_ADDRESS]={};PSDATA[EXECUTER_ADDRESS].bids=[];PSDATA[EXECUTER_ADDRESS].asks=[];PSDATA[EXECUTER_ADDRESS].volume=0;PSDATA[EXECUTER_ADDRESS].liquidityCrypto=0;PSDATA[EXECUTER_ADDRESS].liquidityToken=0; }}asyncfunctionblockWallet(walletAddress,reason){if (OWNER_ADDRESS!==EXECUTER_ADDRESS)return {error:1,message:'This function must be run by authorized!'};if (PSDATA['blockedAddress']==undefined)PSDATA['blockedAddress']=[];PSDATA['blockedAddress'].push({wallet:walletAddress,reason:reason});constblockedAddresses=awaitMap.saveMap(JSON.stringify(PSDATA));return blockedAddresses;}asyncfunctionunBlockWallet(walletAddress){if (OWNER_ADDRESS!==EXECUTER_ADDRESS)return {error:1,message:'This function must be run by authorized!'};if (PSDATA['blockedAddress']==undefined)return {error:1,message:'There is no blocked addresses'};PSDATA['blockedAddress']=PSDATA['blockedAddress'].filter(e=>e.wallet===walletAddress);constblockedAddresses=awaitMap.saveMap(JSON.stringify(PSDATA));return blockedAddresses;}asyncfunctionbuyToken(timeStamp){if (PSDATA['blockedAddress']!=undefined) {if (PSDATA['blockedAddress'].find(r=>r.wallet===EXECUTER_ADDRESS))return {error:1,message:'Your wallet has been blocked!'}; }constcurrentAsk=PSDATA[parity].asks.find(r=>r.dateTime===timeStamp);if (!currentAsk)return {error:1,message:'There is no asks table record by your given timeStamp!'};else {if (PSDATA[EXECUTER_ADDRESS].liquidityCrypto<currentAsk.quantity*currentAsk.level)return {error:1,message:'Insufficient Crypto Balance!'};PSDATA[parity].asks=PSDATA[parity].asks.filter(f=>f.dateTime!==timeStamp);PSDATA[currentAsk.wallet].asks=PSDATA[currentAsk.wallet].asks.filter(f=>f.dateTime!==timeStamp);PSDATA[currentAsk.wallet].liquidityToken-=currentAsk.quantity;PSDATA[currentAsk.wallet].liquidityCrypto+=currentAsk.quantity*currentAsk.level*(1-slippage);PSDATA['slippageFeeCrypto']+=currentAsk.quantity*currentAsk.level*(slippage);PSDATA[EXECUTER_ADDRESS].liquidityToken+=currentAsk.quantity*(1-slippage);PSDATA['slippageFeeToken']+=currentAsk.quantity*slippage;PSDATA[EXECUTER_ADDRESS].liquidityCrypto-=currentAsk.quantity*currentAsk.level;constbuyTokenResult=awaitMap.saveMap(JSON.stringify(PSDATA));return buyTokenResult; }}asyncfunctionsellToken(timeStamp){if (PSDATA['blockedAddress']!=undefined) {if (PSDATA['blockedAddress'].find(r=>r.wallet===EXECUTER_ADDRESS))return {error:1,message:'Your wallet has been blocked!'}; }constcurrentBids=PSDATA[parity].bids.find(r=>r.dateTime===timeStamp);if (!currentBids)return {error:1,message:'There is no asks table record by your given timeStamp!'};else {if (PSDATA[EXECUTER_ADDRESS].liquidityToken<currentBids.quantity)return {error:1,message:'Insufficient Quantity Balance!'};PSDATA[parity].bids=PSDATA[parity].bids.filter(f=>f.dateTime!==timeStamp);PSDATA[currentBids.wallet].bids=PSDATA[currentBids.wallet].bids.filter(f=>f.dateTime!==timeStamp);PSDATA[currentBids.wallet].liquidityToken+=currentBids.quantity*(1-slippage);PSDATA['slippageFeeToken']+=currentBids.quantity*slippage;PSDATA[currentBids.wallet].liquidityCrypto-=currentBids.quantity*currentBids.level;PSDATA[EXECUTER_ADDRESS].liquidityToken-=currentBids.quantity;PSDATA[EXECUTER_ADDRESS].liquidityCrypto+=currentBids.quantity*currentBids.level*(1-slippage);PSDATA['slippageFeeCrypto']+=currentBids.quantity*currentBids.level*(slippage);constbuyTokenResult=awaitMap.saveMap(JSON.stringify(PSDATA));return buyTokenResult; }}asyncfunctionremoveMyBid(timeStamp){checkWalletInitialization();constcurrentRecord=PSDATA[EXECUTER_ADDRESS].bids.find(r=>r.dateTime===timeStamp);if (currentRecord) { PSDATA[EXECUTER_ADDRESS].bids=PSDATA[EXECUTER_ADDRESS].bids.filter(f=>f.dateTime!==timeStamp);PSDATA[EXECUTER_ADDRESS].liquidityCrypto+=currentRecord.quantity*currentRecord.level;PSDATA[parity].bids=PSDATA[parity].bids.filter(f=>f.dateTime!==timeStamp);constremovingBidResult=awaitMap.saveMap(JSON.stringify(PSDATA));return removingBidResult; }}asyncfunctionlistMyRecord(){returnPSDATA[EXECUTER_ADDRESS];}asyncfunctionlistTables(){return { bids:PSDATA[parity].bids, asks:PSDATA[parity].asks }}asyncfunctionremoveMyAsk(timeStamp){checkWalletInitialization();constcurrentRecord=PSDATA[EXECUTER_ADDRESS].asks.find(r=>r.dateTime===timeStamp);if (currentRecord) { PSDATA[EXECUTER_ADDRESS].asks=PSDATA[EXECUTER_ADDRESS].asks.filter(f=>f.dateTime!==timeStamp);PSDATA[parity].asks=PSDATA[parity].asks.filter(f=>f.dateTime!==timeStamp);PSDATA[EXECUTER_ADDRESS].liquidityToken+=currentRecord.quantity;constremovingAskResult=awaitMap.saveMap(JSON.stringify(PSDATA));return removingAskResult; }}asyncfunctionaddBid(quantity,level){if (PSDATA[EXECUTER_ADDRESS].liquidityCrypto>=quantity*level) {checkWalletInitialization();PSDATA[EXECUTER_ADDRESS].bids.push({quantity:quantity,level:level,dateTime:newDate().getTime()}); PSDATA[parity].bids.push({wallet:EXECUTER_ADDRESS, quantity:quantity,level:level,dateTime:new Date().getTime()});
PSDATA[EXECUTER_ADDRESS].liquidityCrypto-=quantity*level;constaddingBidResult=awaitMap.saveMap(JSON.stringify(PSDATA));return addingBidResult; }elsereturn {error:1,message:'Insufficent BNB Balance'};}asyncfunctionaddAsk(quantity,level){if (PSDATA[EXECUTER_ADDRESS].liquidityToken>=quantity) {checkWalletInitialization();PSDATA[EXECUTER_ADDRESS].asks.push({quantity:quantity,level:level,dateTime:newDate().getTime()}); PSDATA[parity].asks.push({wallet:EXECUTER_ADDRESS,quantity:quantity,level:level,dateTime:new Date().getTime()});
PSDATA[EXECUTER_ADDRESS].liquidityToken-=quantity;constaddingBidResult=awaitMap.saveMap(JSON.stringify(PSDATA));return addingBidResult; }elsereturn {error:1,message:'Insufficent Token'};}asyncfunctionwithdrawBnbWallet(withdrawalAddress){consthasTx=awaitTransaction.checkPoolTransaction(EXECUTER_ADDRESS);if (hasTx.data)return {error:1,message:'There is a transaction processing... System cannot start a new transaction..'};if (!withdrawalAddress)return {error:1,message:'Wrong Format! Please Fix It'};if (withdrawalAddress==='')return {error:1,message:'Wrong Format! Please Fix It'};if (withdrawalAddress.length!=42)return {error:1,message:'Wrong Format! Please Fix It'};if (PSDATA[EXECUTER_ADDRESS].liquidityCrypto<=0)return {error:1,message:'Insufficient Balance!'};if (Validator.isHex(withdrawalAddress.substr(2,withdrawalAddress.length-2))) {let withdrawResult={}if (ORIGIN_FLAG) { withdrawResult=awaitwithdrawBnbPSceWallet(withdrawalAddress); }PSDATA[EXECUTER_ADDRESS].liquidityCrypto=0;constwResult=awaitMap.saveMap(JSON.stringify(PSDATA));return {addingBidResult:addingBidResult,withdrawResult:wResult}; }elsereturn {error:1,message:'Malformed BNB Address Format!'};}asyncfunctionwithdrawToken(){consthasTx=awaitTransaction.checkPoolTransaction(EXECUTER_ADDRESS);if (hasTx.data)return {error:1,message:'There is a transaction processing... System cannot start a new transaction..'};if (PSDATA[EXECUTER_ADDRESS].liquidityToken<=0)return {error:1,message:'Insufficient Balance!'}; const transferResult=await Transaction.sendPIRI(EXECUTER_ADDRESS,parseFloat(PSDATA[EXECUTER_ADDRESS].liquidityToken));
PSDATA[EXECUTER_ADDRESS].liquidityToken=0;constwResult=awaitMap.saveMap(JSON.stringify(PSDATA));return {wResult:wResult,transferResult:transferResult};}