With these dependencies in place, we are now ready to start building our PariBox component.
Before diving in, let's first prepare a few essential elements under our imports that will be utilized later on:
Create a PariObj interface to store the contest information, including the Long and Short Pools' amounts, odds, and pubkey.
interfacePariObj { longPool:any; // This is how much money is in the Long Pool of the contest shortPool:any; // This is how much money is in the Short Pool of the contest longOdds:string; // This is the weighted odds of the Long Pool shortOdds:string; // This is the weighted odds of the Short Pool pubkey:string; // This is the contest pubkey}Next, create a constant named TimeInterval to store various time intervals for ease of use.
Create a constant named TimeInterval to store various time intervals for ease of use.
Create a constant config that holds the configuration values imported from the Config.tsx file
const { config } = PariConfig;
Create constant **connection** , which handles the connection to Solana depending on the user's wallet, and instantiate a new ParimutuelWeb3 object with config and connection as parameters.
Define the marketPair with **MarketPairEnum** to select the market that we want to get the contests from. For markets , use the **getMarketPubkeys** method to retrieve all of the Pubkeys of the specified market/s, and create a marketsByTime variable that filters the markets based on whether the duration is the same as timeSeconds value so that we get only the contests from the desired time interval.
// To get only the BTC-USD Market ContestsconstmarketPair=MarketPairEnum.BTCUSD; constmarkets=getMarketPubkeys(config, marketPair);constmarketsByTime=markets.filter( (market) =>market.duration === timeSeconds);
Getting contest data
Use the useEffect hook to run a specific effect when the component is rendered. In this case, the effect will fetch data about the contest and set it in the pariObj state.
useEffect(() => {constgetPariData=async () => {// make sure that we don't exceed the localStorage 10MB capacity when // calling our datalocalStorage.clear(); // Fetch contest data and set it in the pariObj state };fetchData();}, []);
Retrieving contests
Use the parimutuelWeb3.getParimutuels method to retrieve the parimutuel data from the parimutuels array marketsByTerm , and retrieve the duration of the selected parimutuel market.
// Assign active long and active short pools and divide them by USDC // decimal size to get the real amountlet longPool:any= (pari_markets[0].info.parimutuel.activeLongPositions.toNumber() /1_000_000_000);let shortPool:any= (pari_markets[0].info.parimutuel.activeShortPositions.toNumber() /1_000_000_000);// Calculate the odds for long and short pools with the // calculateNetOdds(side, totalPool, rake) method from the SDK // by passing it in the respective pool side, total pool size, // and the rake which is the fee that the Parimutuel protocol takes which is 3%constlongOdds=calculateNetOdd(longPool, longPool + shortPool,0.03);constshortOdds=calculateNetOdd(shortPool, longPool + shortPool,0.03);// Get the public key of the selected parimutuel contract and turn it // into a stringconstpubkey= pari_markets[0].pubkey.toString();// Get the lock time of the selected parimutuel contractconstlocksTime= pari_markets[0].info.parimutuel.timeWindowStart.toNumber();// Round the values of long and short pools to 2 decimal places// longPool =longPool.toFixed(2) shortPool =shortPool.toFixed(2)// Now we can update our contest by setting the state of our pariObj // object with this datasetPariObj({ longPool, shortPool, longOdds, shortOdds, pubkey });
Formatting countdown timer to display:
// We declare a variable formattedTime and initialize it with "00:00:00".var formattedTime ="00:00:00";// Next, we have an if statement that checks if locksTime is truthy.if (locksTime) {//If locksTime is truthy, we calculate the difference between locksTime // and the current time in milliseconds. We store this difference in the // timeDiff variable.constcurrentTime=newDate().getTime();consttimeDiff= locksTime - currentTime;// We then use the Math.floor method to calculate the number of hours,// minutes, and seconds from timeDiff.consthours=Math.floor(timeDiff / (1000*60*60));constminutes=Math.floor((timeDiff % (1000*60*60)) / (1000*60));constseconds=Math.floor((timeDiff % (1000*60)) /1000);// Next, we use template literals to format hours, minutes, and seconds// into a string that has the format "hh:mm:ss". If hours, minutes, or// seconds is less than 10, we add a leading "0".formattedTime =`${hours <10?"0"+ hours : hours}:${minutes <10?"0"+ minutes : minutes}:${seconds <10?"0"+ seconds : seconds}`;}// Finally, we can setCountDownTime with formattedTime as its argument.setCountDownTime(formattedTime);};
Here, we can close our getPariStats() function.
Calling our data
To start a recurring function call, use the setInterval() function. The setInterval() function takes two parameters: the first parameter is the function that you want to call repeatedly, and the second parameter is the interval in milliseconds.
Here, we want to call the getPariData() function every second, so the interval is set to 1000 milliseconds or 1 second.
To avoid memory leaks, it's important to clean up any recurring functions when the component that started it unmounts. To do this, return a function that calls clearInterval() and pass in the intervalId.
return () =>clearInterval(intervalId);}, []);
Now, we have a function that updates our data every second until the component unmounts and the interval is cleared.
Rendering Our Data
Let's build the UI of our Pari Box component.
return (// Render contents here);
To make it easier, here is the code you can copy and paste inside of return: