<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by T.Q.D. Pham on Medium]]></title>
        <description><![CDATA[Stories by T.Q.D. Pham on Medium]]></description>
        <link>https://medium.com/@pqducthinhbka?source=rss-47a2f9185fbc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IQwrmsdXBSjN1CVhC1B17g.jpeg</url>
            <title>Stories by T.Q.D. Pham on Medium</title>
            <link>https://medium.com/@pqducthinhbka?source=rss-47a2f9185fbc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:40:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pqducthinhbka/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Let’s Build a Web3 Portfolio Management Together: Part II — Back-end Development]]></title>
            <link>https://medium.com/@pqducthinhbka/lets-build-a-web3-portfolio-management-together-part-ii-back-end-development-c3b68c54444c?source=rss-47a2f9185fbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b68c54444c</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[T.Q.D. Pham]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 16:22:14 GMT</pubDate>
            <atom:updated>2024-01-05T16:54:48.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Build a Web3 Portfolio Management Together: Part II — Back-end Development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*My_hEraeSM6YH-fQcvQBCw.png" /><figcaption>Screenshot from my previous <a href="https://medium.com/p/6233bd972fe7">post</a>.</figcaption></figure><p>Welcome back, fellow builders! In Part I, we explored the foundational concepts and the vision of our Web3 Portfolio Management system. Now, it’s time to roll up our sleeves and dive into the heart of the matter — backend development.</p><p>If you missed the overview and want to catch up, don’t worry! You can find Part I here.</p><p><a href="https://medium.com/p/6233bd972fe7">https://medium.com/p/6233bd972fe7</a></p><p>Now, let’s continue our coding journey and bring our Web3 portfolio to life by API. Ready? Let’s get started!</p><p><strong>Table of contents for this article</strong></p><ol><li><a href="#f9fe">Preparation essential</a></li><li><a href="#33af">API lists we need to build</a></li><li><a href="#66a9">Leveraging Ankr Advanced APIs</a></li><li><a href="#d675">API creation process</a></li><li><a href="#ea1f">Cyclic cloud deployment</a></li></ol><p><strong>I. Preparation essential</strong></p><p>In order to duplicate the back-end development process, you need to have the following:</p><ul><li><strong>Github</strong>: Serves as the repository for storing our code, facilitating seamless cloud deployment. You can easily create one <a href="https://github.com/">here</a>.</li><li><strong>NestJS</strong>: Acts as the cornerstone for our backend development. Installation is a breeze; simply follow <a href="https://docs.nestjs.com/cli/overview">link</a>. In summary, with the below two lines of codes, you are ready to go.</li></ul><pre>npm install -g @nestjs/cli<br>nest new my-nest-project</pre><ul><li><strong>Cyclic cloud: </strong>Functions as the cloud environment for backend deployment. Creating an account is hassle-free; you can get started <a href="https://www.cyclic.sh/">here</a>.</li><li><strong>Ankr Advanced API: </strong>Unlock the full potential of our data with Ankr’s Advanced API. To begin, sign up <a href="https://www.ankr.com/remote-procedure-call/">here</a>. While accessing their node services is free, diving into advanced data comes with a minimum charge of $10. It’s an investment worth considering for enriched functionalities.</li></ul><p>That’s all we need to kickstart the development of the backend for our Web3 products. Now, let’s dive into a comprehensive review of the features and finalize the API components we need to build.</p><p><strong>II. API lists we need to build</strong></p><p>Lets go through each of the features of our Web3 product and finalize its related API.</p><blockquote>Note: You can see the detailed description of each features in <a href="https://medium.com/p/6233bd972fe7#78c4">here</a></blockquote><ol><li><em>Market Summary</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRFr9sQZXWPNqyy390TXCQ.png" /><figcaption>UI of Market Summary</figcaption></figure><p>As illustrated in the figure above, these six components form the backbone of various market insight projects, such as Coinmarketcap, Coingecko, Klarda, and more. Since these are essentially numeric data sets, a single GET API is sufficient.</p><pre>GET /api/v1/portfolio/market-summary<br><br>export interface MarketSummaryIF {<br>    coins: number,<br>    market_cap: number,<br>    volume: number,<br>    market_cap_percentage: number,<br>    defi_market_cap: number,<br>    trading_volume_24h: number<br>}</pre><p><em>2. Balance and Daily PnL Chart</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8CTlplGxv4z0KG7VfnFpg.png" /><figcaption>UI for Balance &amp; Daily PnL.</figcaption></figure><p>When crafting the GET API for Balance data, the choice of frontend chart library becomes pivotal. In this instance, I’ve opted for the “react-apexcharts” library. Additionally, since Daily PnL can be derived directly from the balance, simplifying the process, you’ll only require two arrays — x-axis and y-axis — to effortlessly render the chart using the following interface.</p><pre>GET /api/v1/portfolio/history<br><br>export interface HistoryIF {<br>  dates: string[],<br>  balances: number[]<br>}</pre><p><em>3. and 4. Balance Distribution and Transaction count</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy-J_RiwEMdYk5mNztw6Zw.png" /><figcaption>UI for Balance Distribution and Transaction Count.</figcaption></figure><p>These two features share similarities in terms of data, allowing us to streamline the discussion into a unified section. By obtaining the total token holding from a wallet, extracting these numbers becomes a straightforward process. Below, discover the essential GET APIs and their corresponding interfaces.</p><pre>GET /api/v1/portfolio/balance  // For Balance Distribution<br>GET /api/v1/portfolio/transaction // For Transaction Count<br><br>export interface BalanceIF {<br>  balanceNow: number,<br>  balanceLastYear: number,<br>  nativeToken: number,<br>}<br>export interface TransactionCountIF {<br>  txnCountNow: number,<br>  txnCountLastYear: number<br>}</pre><p><em>5. Latest Token Transfers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*z7lCnHBUUIMaaeyvVK_ccQ.png" /><figcaption>UI for real-time latest token transfers.</figcaption></figure><p>While this demonstration utilizes a straightforward UI for the latest token transfers, it’s essential to note that practical scenarios often require more complicated information. Details such as transaction method, hash, and transaction decoding become crucial. For those proficient in transaction decoding, extracting comprehensive details from raw transaction data is possible. Stay tuned for an upcoming series where we delve into decoding complexities. For now, let’s keep it simple for this demonstration. Here is the API needed.</p><pre>GET /api/v1/portfolio/token-transfers<br><br>export interface TokenTransfersIF {<br>  fromAddress: string,<br>  toAddress: string,<br>  contractAddress: string,<br>  value: string,<br>  valueRawInteger: string,<br>  blockchain: string,<br>  tokenName: string,<br>  tokenSymbol: string,<br>  tokenDecimals: number,<br>  thumbnail: string,<br>  transactionHash: string,<br>  blockHeight: number,<br>  timestamp: number<br>}</pre><p><em>6. Token Holding</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrU0AEoD3npLLNcRxDL0nw.png" /><figcaption>UI for the Token Holding table.</figcaption></figure><p>To construct a token holding table, a paging and limiting query parameter is typically employed. However, for the sake of simplicity, we’ll bypass this complexity and send all token holdings for this wallet to the front end. Leveraging the capabilities of the `@mui/material` library, we’ll seamlessly create a table. In summary, here is the essential API for this functionality.</p><pre>GET /api/v1/portfolio/token-holding<br><br>export interface TableTokenHoldingIF {<br>  thumbnail: string,<br>  tokenSymbol: string,<br>  balance: number,<br>  balanceUsd: number,<br>  tokenPrice: number,<br>  contractAddress: string,<br>}</pre><p><em>7. NFT Holding</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpYC9iK5hQppLtacnPoEGA.png" /><figcaption>UI for NFT Holding.</figcaption></figure><p>Finally, similar to Token Holding, the creation of the NFT Holding feature requires a straightforward GET API. This fundamental API is the building block for bringing this distinctive aspect of our Web3 Portfolio Management system to life.</p><pre>GET /api/v1/portfolio/nft-holding<br><br>export interface NFTResultIF {<br>  blockchain: string,<br>  name: string,<br>  tokenId: string,<br>  tokenUrl: string,<br>  imageUrl: string,<br>  collectionName: string,<br>  symbol: string,<br>  contractType: string,<br>  contractAddress: string,<br>  quantity: string<br>}</pre><p>In summary, here are the API lists for building our web3 product.</p><pre>GET /api/v1/portfolio/market-summary // For Market Summary<br>GET /api/v1/portfolio/history // For Balance Chart<br>GET /api/v1/portfolio/balance  // For Balance Distribution<br>GET /api/v1/portfolio/transaction // For Transaction Count<br>GET /api/v1/portfolio/token-transfers // For Token Transfers<br>GET /api/v1/portfolio/token-holding // For Token Holding Table<br>GET /api/v1/portfolio/nft-holding // For NFT Holding</pre><p><strong>III. Leveraging Ankr Advanced APIs</strong></p><p>In the construction of this product, the utilization of Ankr Advanced APIs is not a strict requirement. While decoding transactions from an inactive wallet poses minimal challenges, the scenario shifts with active wallets — where a multitude of transaction types executes rapidly. Decoding all transactions becomes a complex process, resulting in potential delays in API response time, limited generalizability across wallets, and challenges in extension to other chains.</p><p>To mitigate these complexities and ensure a robust foundation, integrating advanced APIs from other projects is considered a best practice. Among the available options, Ankr stands out as a premier solution, offering clean data and an affordable pricing model. More details of the response and its usage can be seen in the <a href="https://api-docs.ankr.com/reference/introduction">Ankr Documentation</a>.</p><pre>POST /?ankr_getAccountBalance<br>POST /?ankr_getAccountBalanceHistorical<br>POST /?ankr_getTokenTransfers<br>POST /?ankr_getNFTsByOwner</pre><p><strong>IV. API Creation Process</strong></p><p>Let&#39;s get started to creating API from the backend NestJS</p><ol><li><strong><em>Create NestJS modules for coding</em></strong></li></ol><p>For best practices, it’s suggested to structure your code into separate modules, each catering to distinct features. Given that NestJS is inherently a microservices-oriented framework, the importation of each module into the others ensures an extremely systematic coding approach. For our Web3 product, let’s architect two separate modules:</p><ul><li>blockchain-api: Dedicated to fetching data from blockchain, Ankr, and other sources.</li><li>portfolio: Focuses on preprocessing the data retrieved from the blockchain-api into a clean and structured response format for the API.</li></ul><p>Creating these two modules becomes a straightforward process assuming you’ve successfully installed NestJS. Use the following commands in your console:</p><pre>// For blockchain-api module<br>nest g service blockchain-api<br>nest g module blockchain-api<br>nest g controller blockchain-api<br><br>// For portfolio<br>nest g service portfolio<br>nest g module portfolio<br>nest g controller portfolio</pre><p>Then, if you see the following in your project folder, you are good to go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*mW-WE0OO5owPeO8oqrXz3w.png" /><figcaption>Successfully creating blockchain-api and portfolio modules.</figcaption></figure><p><strong><em>2. Environment variable: .env</em></strong></p><p>At the forefront of your application setup is the imperative task of defining your .env file. This step is crucial for securing sensitive key data and ensuring a robust foundation for your product. In this context, three key elements need to be defined:</p><pre>ANKR_ENDPOINT = https://rpc.ankr.com/multichain/...<br>ANKR_ENDPOINT_ETH = https://rpc.ankr.com/eth/...<br>WALLET = 0x8C8D7C46219D9205f056f28fee5950aD564d7465</pre><p>To integrate your Ankr key and wallet, simply navigate to the three dots and fill in the required details. For illustrative purposes, I’ve opted to use the wallet “0x8C8D7C46219D9205f056f28fee5950aD564d7465,” chosen randomly from the blockchain for reference. This particular wallet is noteworthy for its high activity, engaging in numerous transactions per hour. While you have the flexibility to create an API for wallet input, for the sake of simplicity in this series, we’ll be working with a single wallet defined in the environment.</p><p>In NestJS, managing environment variables with .env is both simple and straightforward. After creating and defining your .env file, a single line of code needs to be imported into the app.module.ts. Essentially, your app.module.ts should resemble the following (refer to the comments in the code for guidance):</p><pre>/app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { BlockchainApiService } from &#39;./blockchain-api/blockchain-api.service&#39;;<br>import { BlockchainApiModule } from &#39;./blockchain-api/blockchain-api.module&#39;;<br>import { PortfolioService } from &#39;./portfolio/portfolio.service&#39;;<br>import { PortfolioModule } from &#39;./portfolio/portfolio.module&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br><br>@Module({<br>  imports: [<br>    // Use this below line of code for using .env variable with isGlobal:true<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>    }),<br>    // blockchain-api module <br>    BlockchainApiModule,<br>    // portfolio module<br>    PortfolioModule],<br>  controllers: [AppController],<br>  providers: [AppService, BlockchainApiService, PortfolioService],<br>})<br><br>export class AppModule { }</pre><p><strong><em>3. Blockchain-API module</em></strong></p><p>As mentioned above, this module is used mainly for fetching data from blockchain via web3 API. In general, we need to fetch blockchain data from two sources, first, the Ankr Advanced API, and second, the blockchain data API.</p><ul><li><em>Ankr Advanced API</em></li></ul><p>When it comes to fetching data from Ankr, there are two methods at your disposal: (i) installing the Ankr library or (ii) directly fetching data from their RESTful API. In this context, I’ve opted for the second method for its straightforward implementation, eliminating the need for an external library installation.</p><p>To achieve this, leverage the power of ‘<strong>fetch</strong>’ from the ‘<strong>node-fetch</strong>’ library. Begin by defining a function that creates request options. This function takes two inputs:</p><ol><li>Method: A string variable defining the advanced API method you wish to employ (e.g., ankr_getTokenTransfers).</li><li>Query: A query object tailored to the specific method in use.</li></ol><p>This approach ensures a seamless and efficient process for fetching data from Ankr without the need for additional external libraries. Here is the code for creating the request option.</p><pre>getAnkrRequestOption = (params: { method: string, query: any }) =&gt; {<br>    const body = JSON.stringify({<br>        jsonrpc: &#39;2.0&#39;,<br>        method: params.method, // method name<br>        params: params.query, // your query object<br>        id: 1,<br>    });<br>    return {<br>        method: &#39;POST&#39;,<br>        headers: {<br>            accept: &#39;application/json&#39;,<br>            &#39;content-type&#39;: &#39;application/json&#39;,<br>        },<br>        body: body,<br>        redirect: &#39;follow&#39;,<br>    }<br>}</pre><p>Then, from the list of Ankr Advanced API we&#39;ve already defined from <a href="#3ffb">Section III</a>, we can define four functions to get the data of each one.</p><blockquote>Note that it’s considered a best practice to define response interface types for each variable when working with TypeScript. This approach not only aligns with TypeScript’s statically typed nature but also significantly contributes to better code quality. By explicitly defining the expected structure of the response, you enhance readability, maintainability, and overall robustness of your codebase. Embrace this practice to elevate the quality of your TypeScript code.</blockquote><p>Here’s a practical example demonstrating how to retrieve token transfers from a specific address. It’s worth noting that other methods follow a similar pattern. Feel free to define them based on your specific understanding or refer to the GitHub repository linked below for more comprehensive examples and implementations.</p><pre>// Example for get token transfer data<br><br>export interface TokenTransfersIF {<br>    fromAddress: string,<br>    toAddress: string,<br>    contractAddress: string,<br>    value: string,<br>    valueRawInteger: string,<br>    blockchain: string,<br>    tokenName: string,<br>    tokenSymbol: string,<br>    tokenDecimals: number,<br>    thumbnail: string,<br>    transactionHash: string,<br>    blockHeight: number,<br>    timestamp: number<br>}<br><br>export interface AnkrTokenTransfersIF {<br>    jsonrpc: string,<br>    id: number,<br>    result: { transfers: TokenTransfersIF[] }<br>}<br><br>// Get token transfer from a wallet<br>getTokenTransferByAddressAnkr = async (params: {<br>    address: string,<br>    fromTimestamp?: number,<br>    networks: string[],<br>    limit: number,<br>}): Promise&lt;AnkrTokenTransfersIF&gt; =&gt; {<br>    const query = {<br>        descOrder: true,<br>        address: [<br>            params.address<br>        ],<br>        blockchain: params.networks,<br>        pageSize: params.limit<br>    }<br>    if (params.fromTimestamp) {<br>        query[&#39;fromTimestamp&#39;] = params.fromTimestamp<br>    }<br>    <br>    const requestOptions = this.getAnkrRequestOption({ method: &#39;ankr_getTokenTransfers&#39;, query: query })<br>    <br>    // get response<br>    const response = await fetch(<br>        `${process.env.ANKR_ENDPOINT}/?ankr_getTokenTransfers=`,<br>        requestOptions,<br>    );<br><br>    // get response in json format, should have await<br>    const logRes = await response.json();<br><br>    return logRes;<br>};<br><br>// Get token balance from a wallet<br>...<br>// Get balance hsistory from a wallet<br>...<br>/// Get NFT from a wallet<br>...<br></pre><ul><li><em>Web3 and Coingecko API</em></li></ul><p>Utilizing the Ankr Advanced API empowers you with 80% of the essential data required for the Web3 Portfolio Management product in this series. To complement this dataset, the remaining 20% can be effortlessly obtained from free-to-use APIs directly sourced from the Web3 ecosystem and/or Coingecko.</p><p>In particular, they are the transaction count and global market summary features. Here are the function to get them</p><pre>// Get global market summary<br>getMarketData = async () =&gt; {<br>    // It is best practice to define the interface for response<br>    const response = await fetch(&quot;https://api.coingecko.com/api/v3/global&quot;);<br>    const dataJson: { data?: MarketCGCIF } = await response.json();<br>    return dataJson?.data<br>}<br><br>getDefiData = async () =&gt; {<br>    // It is best practice to define the interface for response<br>    const response = await fetch(&quot;https://api.coingecko.com/api/v3/global/decentralized_finance_defi&quot;);<br>    const dataJson: { data?: DeFiCGCIF } = await response.json();<br>    return dataJson?.data<br>}<br><br>// Get Transaction Count. The response from web3 is in BigNumber type, thus, we need to parse the response to number<br>getWalletTransactionCount = async (params: { wallet: string, block?: number }) =&gt; {<br>    const web3 = new Web3(new Web3.providers.HttpProvider(process.env.ANKR_ENDPOINT_ETH));<br>    const txnCount: number = params.block ?<br>        Number(await web3.eth.getTransactionCount(params.wallet, params.block)) :<br>        Number(await web3.eth.getTransactionCount(params.wallet));<br>    return txnCount<br>}</pre><p><strong><em>4. Portfolio module</em></strong></p><p>Once you’ve completed testing and validation of the functions within the blockchain-api module, it&#39;s time to transition to the portfolio module. Here, your focus will be on preprocessing data and crafting the associated APIs.</p><p>A crucial step in this process is importing the blockchain-api module into the portfolio module for the nature of NestJS. This strategic move allows you to harness the full functionality of the blockchain-api module within the portfolio module. Then, import the blockchain-api service to the portfolio one. This intermodule collaboration is pivotal for a streamlined and efficient development workflow.</p><pre>/portfolio.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { BlockchainApiModule } from &#39;src/blockchain-api/blockchain-api.module&#39;;<br>import { PortfolioService } from &#39;./portfolio.service&#39;;<br>import { PortfolioController} from &#39;./portfolio.controller&#39;;<br>// import { MongooseModule } from &#39;@nestjs/mongoose&#39;; // If need mongoDB <br><br>@Module({<br>  imports: [<br>    BlockchainApiModule, // Import to Portfolio module<br>  ],<br>  providers: [PortfolioService],<br>  controllers: [PortfolioController],<br>})<br>export class PortfolioModule { }<br><br><br><br>/portfolio.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { BlockchainApiService, BalanceHistoryIF, AnkrTokenTransfersIF, NFTResponseIF } from &#39;src/blockchain-api/blockchain-api.service&#39;;<br><br>@Injectable()<br>export class PortfolioService {<br>    constructor(<br>        private blockchainApiService: BlockchainApiService<br>    ) { }<br><br>// code logic<br>}</pre><p>Adhering to the predefined response interface for the front-end outlined in <a href="#1489">Section II: API lists we need to build</a> is needed for a systematic flow. Consistency in the returned interface is paramount to keeping your front-end partner delighted! 😄</p><p>As per the established practice, I’m providing you with the code for generating the response for the <strong>Balance Distribution</strong> feature, complete with its corresponding front-end interface. While you have the flexibility to freestyle the code for other functions, it’s crucial to align them with the same interface. For the code of other features, you can take a look at the Github link under this article. Here is the code below and replicate this pattern for other features.:</p><pre>// GET /api/v1/portfolio/history <br><br>// API response interface<br>export interface HistoryIF {<br>  dates: string[],<br>  balances: number[]<br>}<br><br>export interface AssetIF {<br>    blockchain: string,<br>    tokenName: string,<br>    tokenSymbol: string,<br>    tokenDecimals: number,<br>    tokenType: string,<br>    holderAddress: string,<br>    balance: string,<br>    balanceRawInteger: string,<br>    balanceUsd: string,<br>    tokenPrice: string,<br>    thumbnail: string<br>}<br><br>export interface ResultHistoryIF {<br>    totalBalanceUsd: number,<br>    totalCount: number,<br>    assets: AssetIF[]<br>}<br><br>export interface BalanceHistoryIF {<br>    jsonrpc: string,<br>    id: number,<br>    result: ResultHistoryIF<br>}<br><br>getWalletHistoryChartData = async () =&gt; {<br>    const wallet = process.env.WALLET;<br>    const dates = this.getDateLists();<br><br>    const currentBlock: number = await this.blockchainApiService.getDateToBlock(<br>        Math.round(new Date().getTime() / 1000), this.chain_name<br>    );<br>    const blockData: number[] = Array.from(<br>        { length: 7 }, (_, index) =&gt; currentBlock ? currentBlock - index * this.ethBlockPerDay : 0<br>    );<br><br>    const balanceHistory: number[] = await Promise.all(blockData.reverse().map(async (block) =&gt; {<br>        const balance: BalanceHistoryIF = await this.blockchainApiService.getBalanceHistoryAnkr({<br>            wallet: wallet,<br>            networks: [this.chain_ankr],<br>            block: block,<br>            limit: 1,<br>        });<br>        return Number(balance?.result?.totalBalanceUsd);<br>    }));<br><br>    // Return the same interface as defined on top of this code block. Or, you can define another variable with type is the response.<br>    return {<br>        dates: dates,<br>        balances: balanceHistory<br>    }<br>}</pre><p><strong><em>5. Make Portfolio API</em></strong></p><p>Once you’ve verified the correctness of your portfolio functions, crafting APIs in NestJS becomes a straightforward and simple process. Navigate to the portfolio.controller.ts file for this task, ensuring you&#39;ve imported it into the portfolio.module.ts for integration.</p><p>In this endeavor, you’ll be creating up to seven GET APIs. To illustrate, here’s an example of how to create the GET /api/v1/portfolio/token-holding API, as referenced in Section <a href="#1489">2</a>:</p><pre>/portfolio.controller.ts<br><br>import {<br>    Controller,<br>    Get,<br>} from &#39;@nestjs/common&#39;;<br>import {<br>    ApiInternalServerErrorResponse,<br>    ApiOperation,<br>    ApiTags,<br>} from &#39;@nestjs/swagger&#39;;<br>import { PortfolioService } from &#39;./portfolio.service&#39;;<br><br>@Controller(&#39;api/v1/portfolio&#39;)<br>@ApiTags(&#39;Portfolio Balance APIs&#39;)<br>export class PortfolioController {<br>    constructor(<br>        private service: PortfolioService,<br>    ) { }<br><br>    @Get(&#39;/token-holding&#39;)<br>    @ApiOperation({<br>        summary: &#39;Get Wallet Token Holding Transfers&#39;,<br>        description: &#39;Get Wallet Token Holding Transfers&#39;,<br>    })<br>    @ApiInternalServerErrorResponse({<br>        description: &#39;Internal server error&#39;,<br>    })<br>    public async getTokenHoldingAPI(<br>    ) {<br>        return await this.service.getWalletTokenHolding();<br>    }<br><br>    //Other APIs ...<br><br>}</pre><p>Take your API testing to the next level by seamlessly integrating your NestJS framework with Swagger. The process is straightforward; simply install Swagger using npm:</p><pre>npm i @nestjs/swagger</pre><p>Then, define a couple of lines of codes in the main.ts as</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { SwaggerModule, DocumentBuilder } from &#39;@nestjs/swagger&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import { TransformInterceptor } from &#39;./common/interceptors/response-mapping-interceptors&#39;<br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  // For better response form<br>  app.useGlobalInterceptors(new TransformInterceptor());<br><br>  // add enableCors<br>  app.enableCors();<br><br>  // Setup Swagger<br>  const config = new DocumentBuilder()<br>    .setTitle(&#39;Portfolio API&#39;)<br>    .setDescription(&#39;Portfolio API description&#39;)<br>    .setVersion(&#39;1.0&#39;)<br>    .addTag(&#39;portfolio&#39;)<br>    .build();<br>  const document = SwaggerModule.createDocument(app, config);<br><br>  SwaggerModule.setup(&#39;api&#39;, app, document);<br><br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>Congratulations! You’ve successfully completed the process of creating APIs for the Portfolio app. A big shout-out to you for staying engaged throughout this journey. As a final step, validate and explore your APIs using Swagger. Open your terminal and enter the following command:</p><pre>npm run start:dev</pre><p>Next, open your web browser and navigate to <a href="http://localhost:3000/api">http://localhost:3000/api</a>. Voila! You now have the freedom to thoroughly test your APIs through the Swagger interface. This interactive environment empowers you to explore, validate, and fine-tune your APIs with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DIuBa2jxXqXNqXqxKLh0eg.png" /><figcaption>Swagger UI for testing portfolio API.</figcaption></figure><p>Moving forward, let’s take the next step in making your back-end app accessible to the world by deploying it to Cyclic Cloud, as previously discussed.</p><p><strong>V. Cyclic cloud deployment</strong></p><p>At this juncture, I presume you already possess both a GitHub account and access to Cyclic Cloud.</p><p><strong><em>Step 1</em></strong><em>: Keep the right format of </em><em>package.json</em></p><p>To facilitate deployment on Cyclic Cloud, the initial step involves formatting the package.json file to adhere to the supported structure of Cyclic Cloud. Ensure your package.json conforms to the following format. <strong>Pay particular attention to the crucial line of code:</strong></p><blockquote>“start”: “node dist/main&quot;</blockquote><p>For a fluent deployment process, it’s essential to adhere to a standardized script format in your package.json. Here&#39;s the recommended structure:</p><pre>&quot;scripts&quot;: {<br>  &quot;build&quot;: &quot;nest build&quot;,<br>  &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.ts\&quot; \&quot;test/**/*.ts\&quot;&quot;,<br>  &quot;start&quot;: &quot;node dist/main&quot;,<br>  &quot;start:dev&quot;: &quot;nest start --watch&quot;,<br>  &quot;start:debug&quot;: &quot;nest start --debug --watch&quot;,<br>  &quot;start:prod&quot;: &quot;node dist/main&quot;,<br>  &quot;lint&quot;: &quot;eslint \&quot;{src,apps,libs,test}/**/*.ts\&quot; --fix&quot;,<br>  &quot;test&quot;: &quot;jest&quot;,<br>  &quot;test:watch&quot;: &quot;jest --watch&quot;,<br>  &quot;test:cov&quot;: &quot;jest --coverage&quot;,<br>  &quot;test:debug&quot;: &quot;node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand&quot;,<br>  &quot;test:e2e&quot;: &quot;jest --config ./test/jest-e2e.json&quot;<br>},</pre><p><strong><em>Step 2</em></strong><em>: Link the GitHub repo to Cyclic and deploy the app</em></p><p>Then, after uploading your NestJS BE code to GitHub, open your cyclic cloud account. You should see something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQ3ZOjs7p-kjijYk2ZCE7g.png" /></figure><p>Navigate to the figure above and select “Link Your Own.” Choose your NestJS GitHub repository, then proceed to follow the steps provided by Cyclic. Finally, click on “Connect Cyclic” when prompted. Following this, you’ll witness Cyclic initiating the build and deploying your app to their cloud. The process unfolds, culminating in a status similar to the one depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f457xdXsHQYlYTjCQ5PODA.png" /></figure><p>And there you have it — mission accomplished! Surprisingly swift, wasn’t it? In just 46.5 seconds, your NestJS backend API is now successfully deployed to the cloud. Your API is now accessible to the world according to your preferences.</p><p>Before concluding, don’t forget the crucial step of configuring your environment variables. Ensure that they are similar to the ones you’ve set in your local code. Head over to the “<em>variables</em>” tab and set the environment variables accordingly. Additionally, in the “<em>environments</em>” tab, you have the flexibility to define a custom API URL. As an illustration, in this instance, I’ve set my sub-domain as “<em>api-asset-management-tqdpham</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUsSg6_TZQoYN_ZplDzrhQ.png" /></figure><p>There you go, now you can test the API easily by putting it in browser, for example, in my case as</p><blockquote><a href="https://api-asset-management-tqdpham.cyclic.app/hello">https://api-asset-management-tqdpham.cyclic.app/hello</a></blockquote><p>If everything goes well, you should see the response from the browser as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRcFVpDERwWQRGgor6n6UQ.png" /></figure><p>To conclude, the API you’ve created using NestJS and deployed to Cyclic Cloud is ready for testing. Simply replace “/hello” with your API slug to retrieve the desired data. In summary, below outlines the key steps:</p><ul><li>Replace “/hello”: Replace this placeholder with your specific API slug to access the relevant data.</li><li>Testing URL: Copy and paste the link URL into your browser to test the deployed API.</li></ul><p>Feel free to explore and test the functionality of your deployed API!</p><pre>GET /api/v1/portfolio/market-summary // For Market Summary<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/market-summary<br><br>GET /api/v1/portfolio/history // For Balance Chart<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/history<br><br>GET /api/v1/portfolio/balance  // For Balance Distribution<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/balance<br><br>GET /api/v1/portfolio/transaction // For Transaction Count<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/transaction<br><br>GET /api/v1/portfolio/token-transfers // For Token Transfers<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/token-transfers<br><br>GET /api/v1/portfolio/token-holding // For Token Holding Table<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/token-holding<br><br>GET /api/v1/portfolio/nft-holding // For NFT Holding<br>https://api-asset-management-tqdpham.cyclic.app/api/v1/portfolio/nft-holding</pre><p>WOW! What a journey we’ve embarked on together in this extensive article. A heartfelt thank you for your dedication in reading and following along up to this point. Together, we’ve accomplished a significant feat — from defining essential APIs to navigating through modules, services, controllers, cloud deployment, and a multitude of other captivating aspects.</p><p>Given the length of this article, I understand it might have been challenging to follow every detail. No worries! To make things easier, I’ve provided a link to my GitHub repository for this backend. By cloning the repo and following the instructions in the readme, you’ll be all set to explore and leverage the power of this backend.</p><blockquote>GitHub: <a href="https://github.com/tqdpham96/portfolio-management-be">https://github.com/tqdpham96/portfolio-management-be</a></blockquote><p>Get ready for the next chapter as we go into front-end development, crafting a stunning UI for our products. Anticipate a journey filled with creativity and innovation as we bring our vision to life.</p><p>Until then, happy coding and happy new year! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b68c54444c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s build a Web3 Portfolio Management together from end-to-end with NestJS, NextJS, and Ankr…]]></title>
            <link>https://medium.com/@pqducthinhbka/lets-build-a-web3-portfolio-management-together-from-end-to-end-with-nestjs-nextjs-and-ankr-6233bd972fe7?source=rss-47a2f9185fbc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6233bd972fe7</guid>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[portfolio-management]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[T.Q.D. Pham]]></dc:creator>
            <pubDate>Mon, 01 Jan 2024 16:30:05 GMT</pubDate>
            <atom:updated>2024-01-01T16:30:05.201Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Let’s build a Web3 Portfolio Management together from end-to-end with NestJS, NextJS, and Ankr: Part I — Overview.</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVEITZKNMKZU_HQcsNRPQw.png" /><figcaption>Screenshot from <a href="https://home.klarda.com/blogs/how-to-use-klarda-portfolio">this post</a></figcaption></figure><p>Hey there, fellow builders! 👋 I’m Dr. Pham, a tech enthusiast holding a PhD in AI, Mathematics, and Blockchain. Today marks a special occasion — it’s my first foray into the world of sharing knowledge through the written word, and I couldn’t be more thrilled.</p><p>As a firm believer in the philosophy that sharing is a form of learning, I’ve decided to kick off this series by delving into the creation of a Web3 Portfolio Management system. Why, you ask? Well, let’s talk portfolios — those digital diaries of our decentralized endeavors. We’ve seen the likes of Nansen, Zerion, and Klarda doing wonders, but why not craft one uniquely tailored to our needs?</p><p>This series isn’t just about code; it’s about demystifying the process, learning together, and contributing to the ever-evolving web3 community. So, buckle up as we unravel the intricacies of NestJS and NextJS, laying the groundwork for our bespoke Web3 portfolio.</p><p>Enough words! Stick around; this is going to be a long series worth your time. Therefore, I will split the series into three parts as: Overview, Backend, and Frontend. Stay tuned!</p><p><strong>Table of contents for this article</strong></p><ol><li><a href="#8134">How the Products Look</a></li><li><a href="#d3c0">Prerequisites</a></li><li><a href="#78c4">Why Choose NestJS and NextJS Frameworks?</a></li><li><a href="#7b8b">Web3 Node/API Services</a></li><li><a href="#96da">Cloud services for Back-end and Front-end deployment</a></li></ol><p><strong>I. How the Products Look</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XO0URwZnfuPTJvalASO_mg.png" /><figcaption>Products unstructured UI and list of features</figcaption></figure><p>The web-based product is designed for efficient web3 portfolio management. Here is a simple version I&#39;ve deployed for demonstration <a href="https://crypto-portfolio-management-tqdpham.netlify.app/">https://crypto-portfolio-management-tqdpham.netlify.app</a>, featuring:</p><ol><li><strong>Market Summary</strong>: Aggregates key market metrics like total active coins, market cap, 24h volume, DeFi TVL, 24h trading, and BTC dominance percentage.</li><li><strong>Balance and Daily PnL Chart</strong>: Visualizes your balance and daily Profit and Loss (PnL) per day, empowering you to monitor and optimize your portfolio performance.</li><li><strong>Balance Distribution</strong>: Offers a quick overview of your portfolio diversity, including current balance, year-over-year change, and the ratio of native and ERC-20 tokens.</li><li><strong>Transaction Count</strong>: Summarizes your wallet transactions, providing a snapshot of your overall activity.</li><li><strong>Latest Token Transfers</strong>: Keeps you informed with the latest token transfers within your wallet.</li><li><strong>Token Holding</strong>: Details all token holdings, showcasing balance amounts, related values, and current token prices.</li><li><strong>NFT Holding</strong>: Similar to token holding, this feature highlights your top NFTs in the wallet.</li></ol><p>Here we have it — the lineup of features we’ll construct together in this series. While they may be considered basic, they form a solid foundation for venturing into Web3 development. Feel free to infuse your own style and expand upon these features as you see fit! 😊</p><p><strong>II. Prerequisites</strong></p><p>To get the content of this series, a basic understanding of full-stack engineering and blockchain is beneficial. However, worry not; you can still deploy the product easily as I’ve structured the code in a user-friendly manner. Specifically, the following technologies are essential for building the product from scratch.</p><ol><li>NestJS: Backend framework for theproduct.</li><li>NextJS: Frontend framework for the product.</li><li>Ankr: Blockchain node and API services for the product.</li><li>Coingecko API: Global market changes.</li></ol><p><strong>III. Why Choose NestJS and NextJS frameworks for Web3 Product?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r95ucJGNZQYFT0SthXXwzA.png" /><figcaption>Screenshot from <a href="https://medium.com/@yuvrajkakkar1/what-to-choose-application-in-nextjs-with-nestjs-or-nextjs-only-7c087acdb7c9">this post</a>.</figcaption></figure><p>Choosing the right frameworks for the backend and frontend of a Web3 product depends on various factors, including your project requirements, team expertise, and the specific features you want to implement. As per my knowledge, I normally use NestJS (Backend) and NextJS (Frontend) for my products for the following reasons:</p><ol><li>NestJS (Backend): Modular architecture, Reusable and testable modules, Easy testing, Built-in support for common protocols, TypeScript supports.</li><li>NextJS (Frontend): Serverless functioning, SEO benefits, Well structured, Higher flexibility and customization.</li></ol><p>In a nutshell, it highlights the advantages of these two frameworks for software development. While you can delve into more comprehensive details online, it’s worth noting that, especially in the realm of Web3 products, flexibility is paramount. Given the dynamic nature of Web3, where functionalities can be diverse, NestJS and NextJS emerge as particularly well-suited frameworks for crafting innovative and adaptable solutions.</p><p><strong>IV. Web3 Node/API Services</strong></p><p>In the realm of Web3 product development, establishing a reliable connection to a blockchain node for data retrieval is a must. With an array of web node/API services available — such as Ankr Node, Moralis, Quicknode, and more — making the right choice can be challenging. Drawing from my early days navigating the Web3 landscape, I, too, faced the challenge of selecting the ideal Web3 service. After experimenting with various projects, I discovered my go-to best friend 😊— Ankr Node. It has proven to be a steadfast ally in my Web3 endeavors for the following reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ULyYVsdZJzLBSaIw1B2bg.png" /><figcaption>Screenshot from <a href="https://www.ankr.com/about-network/node-provider/">this post</a></figcaption></figure><ol><li>Proven by various big-name in the field, such as, Messari, Binance, Wormhole, etc.</li><li>Legitimate partner, including Google and Microsoft.</li><li>Provide a specifically-tailored collection of JSON-RPC API endpoints built to support the most popular Web3 scenarios on multiple chains at almost instant speeds.</li><li>Robust support and a user-friendly administrator UI for monitoring node performance.</li><li>Cost-effective pricing model with a pay-as-you-go approach.</li></ol><p>Indeed, the third advantage resonates the most. It’s a lifesaver, sparing us the complexities of decoding raw data techniques that are pivotal for the products. But, working with decoding raw data is also fun. I will have another series tackle this problem.</p><p><strong>V. Cloud services for Back-end and Front-end deployment</strong></p><p>Now, let’s talk about hosting our backend and frontend code in the cloud. With the development of cloud services available today, from industry giants like Google and AWS to newer players such as Vercel and Cyclic Cloud, the options are diverse and generally effective for various scenarios. The deployment flow tends to be quite similar across these platforms.</p><p>For the demonstration of our Web3 product, simplicity is key. I’ve opted for a Free-to-use hosting service to ensure everyone can easily test the deployment. Specifically, here’s the one I’ve chosen.</p><ol><li><strong>Backend</strong>: <a href="https://www.cyclic.sh/">Cyclic Cloud</a></li><li><strong>Frontend</strong>: <a href="https://www.netlify.com/">Netlify</a></li></ol><p>In addition, you are free to use other cloud services that you may already have.</p><p>Thanks for joining me in this series of building a Web3 Portfolio Management system with NestJS and NextJS. We’ve covered the overview, laying the groundwork for an exciting journey ahead.</p><p>In the upcoming article, we’ll dive deep into the backend development, where lines of code will bring our product to life. Brace yourself for a coding adventure that will shape the core of our Web3 solution.</p><p>Stay tuned for the next installment, and feel free to share your thoughts and feedback. Your input is invaluable as we embark on this coding odyssey together.</p><p>Until then, happy coding and happy new year! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6233bd972fe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>