<?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 Burgossrodrigo on Medium]]></title>
        <description><![CDATA[Stories by Burgossrodrigo on Medium]]></description>
        <link>https://medium.com/@burgossrodrigo?source=rss-f997f4ded7f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xv3XyGS-3DBT4hkM</url>
            <title>Stories by Burgossrodrigo on Medium</title>
            <link>https://medium.com/@burgossrodrigo?source=rss-f997f4ded7f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:20:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@burgossrodrigo/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[Best way ever to extract token price from UniswapV2]]></title>
            <link>https://coinsbench.com/best-way-ever-to-extract-token-price-from-uniswapv2-750ef3923f7d?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/750ef3923f7d</guid>
            <category><![CDATA[uniswap]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 19:04:37 GMT</pubDate>
            <atom:updated>2024-11-20T11:49:35.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*cWcCmXtorKqcvy-T_bdTEA.png" /></figure><p>UniswapV2 still relevant, most of the degen games happens there, so here’s my 2024 ultimate guide on how to, perfectly, tested, extract price from a UniswapV2 pair ❤❤❤</p><p><strong>Router instance:</strong></p><p>I’ve used typechain to create a instance for the PairV2 smartcontract. And if you don’t use it, you should (ask me how):</p><pre>const routerInstance = (): RouterV2 =&gt; {<br>    try {<br>        const router = RouterV2__factory.connect(ROUTER_V2_ADDR, providerInstance() ?? getDefaultProvider());<br>        return router;<br>    } catch (error: any) {<br>        insertError({ message: error.message, date: new Date(), method: &#39;routerInstance&#39; });<br>        throw new Error(`Error fetching router instance: ${error}`);<br>    }<br>}</pre><p><strong>Decimals adjustement helper:</strong></p><p>It’s importante to adjust the decimals so you don’t get a fuzzy output. here’s how:</p><pre>export const formatDecimals = (amount: number, decimals: number) =&gt; {<br>    return amount / Math.pow(10, decimals)<br>}</pre><p><strong>The function itself:</strong></p><pre>export const amountOutV2 = async (tokenIn: string, tokenOut: string, amountIn: string, decimal: number): Promise&lt;number&gt; =&gt; {<br>    try {<br>        const router = routerInstance();<br>        const amounts: BigNumber[] = await router.getAmountsOut(amountIn, [tokenIn, tokenOut]);<br><br>        // Format each amount based on the decimals for each token in the path<br>        const formattedAmounts = formatDecimals(Number(amounts[amounts.length - 1]._hex), decimal);<br><br><br>        return Number(formattedAmounts);<br>    } catch (error: any) {<br>        insertError({ message: error, date: new Date(), method: &#39;amountOutV2&#39; });<br>        throw new Error(`Error fetching amount out: ${error}`);<br>    }<br>}</pre><p>Things to considerate.</p><p>The return of the method can be examined thankfully to typechain, and its type is BigNumber[] and it will consist of an array with the same length of the path used as the second input of the `getAmountsOut`method from the pair.</p><p>Since we are using a strict route for our swap, the first entry, the index 0 of that array must be the amountIn attribute. Meanwhile the second one is the output of our interest, the amount i’ll be receiving (counting fees and so on) from the transaction.</p><p>Pretty simple, no?</p><p>So that’s how we should call it:</p><pre>const main = async () =&gt; {<br>    const [uniDecimals, wethDecimals] = await Promise.all([<br>        getTokenDecimals(UNI),<br>        getTokenDecimals(WETH)<br>    ])<br><br>    const amount = formatDecimalsTo(1, uniDecimals)<br>    const amountOut = await amountOutV2(UNI, WETH, String(amount), uniDecimals)<br>    console.log(amountOut, &#39;amountOut&#39;)<br><br>}<br><br>main().then(() =&gt; console.log(&#39;done&#39;)).catch(console.error)</pre><p>The is pretty similar to formatDecimals, excepts it multiply insteed of divides:</p><pre>export const formatDecimalsTo = (amount: number, decimals: number) =&gt; {<br>    return amount * Math.pow(10, decimals)<br>}</pre><p>With no further due, i think that now you will be able to extract price from PairV2 of the UniswapV2 periphery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=750ef3923f7d" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/best-way-ever-to-extract-token-price-from-uniswapv2-750ef3923f7d">Best way ever to extract token price from UniswapV2</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a NestJS Service to Interact with the Polymarket Protocol]]></title>
            <link>https://coinsbench.com/building-a-nestjs-service-to-interact-with-the-polymarket-protocol-ef175593cb65?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef175593cb65</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[polymarket]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 08:25:07 GMT</pubDate>
            <atom:updated>2024-09-25T14:51:45.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vArrhosSSDbYAYcP3UXjUg.jpeg" /></figure><p>In the rapidly evolving world of decentralized finance (DeFi), protocols like <a href="https://polymarket.com/">Polymarket</a> offer innovative ways to engage with prediction markets. To interact seamlessly with the Polymarket protocol, especially its Central Limit Order Book (CLOB), building a robust backend service is essential. In this article, we’ll walk through building a NestJS service that leverages the Polymarket CLOB client to perform various operations such as managing API keys, placing orders, and handling order statuses.</p><h3>Table of Contents</h3><ol><li><a href="#introduction-to-polymarket-and-clob">Introduction to Polymarket and CLOB</a></li><li><a href="#prerequisites">Prerequisites</a></li><li><a href="#setting-up-the-nestjs-project">Setting Up the NestJS Project</a></li><li><a href="#installing-dependencies">Installing Dependencies</a></li><li><a href="#building-the-clobservice">Building the ClobService</a></li><li>Error Handling</li><li>Usage Example</li><li>Conclusion</li></ol><h3>Introduction to Polymarket and CLOB</h3><p><a href="https://polymarket.com/">Polymarket</a> is a decentralized information markets platform that allows users to bet on the outcomes of real-world events. The Central Limit Order Book (CLOB) is a mechanism that facilitates the matching of buy and sell orders in a transparent and efficient manner. Interacting with the CLOB programmatically enables developers to automate trading strategies, manage orders, and integrate Polymarket functionalities into their applications.</p><h3>Prerequisites</h3><p>Before diving into the implementation, ensure you have the following:</p><ul><li><strong>Node.js</strong> (v14 or later)</li><li><strong>NestJS CLI</strong> installed globally (npm install -g @nestjs/cli)</li><li>Basic understanding of TypeScript and NestJS</li><li>Familiarity with Ethereum wallets and private keys</li></ul><h3>Setting Up the NestJS Project</h3><p>First, let’s create a new NestJS project.</p><pre>npm install ethers @polymarket/clob-client<br>npm install --save-dev @types/node</pre><ul><li><strong>ethers</strong>: A library for interacting with the Ethereum blockchain.</li><li><strong>@polymarket/clob-client</strong>: The official Polymarket CLOB client for interacting with the CLOB.</li></ul><h3>Building the ClobService</h3><p>Create a new service called ClobService that will encapsulate all interactions with the Polymarket CLOB.</p><pre>nest generate service clob</pre><p>Replace the generated clob.service.ts with the following implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c408c1e473835dfcf61c8f21adcf66f/href">https://medium.com/media/7c408c1e473835dfcf61c8f21adcf66f/href</a></iframe><h3>Detailed Explanation of ClobService Methods</h3><p>Let’s delve into the key methods of the ClobService:</p><p><strong>initClobClient</strong>: Initializes the ClobClient using the provided RPC URL and Ethereum wallet or signer. It retrieves the chain ID dynamically to ensure compatibility with different Ethereum networks.</p><p><strong>API Key Management</strong>:</p><ul><li><strong>createApiKey</strong>: Generates a new API key for authenticating future requests.</li><li><strong>getApiKey</strong>: Fetches all existing API keys associated with the wallet.</li><li><strong>deleteApiKey</strong>: Removes a specific API key.</li></ul><p><strong>Order Operations</strong>:</p><ul><li><strong>placeOrder</strong>: Creates and posts a new order to the CLOB. It handles parameters like token ID, price, side (buy/sell), size, fee rate, and nonce.</li><li><strong>getOrder</strong>: Retrieves details of a specific order using its unique ID.</li><li><strong>isOrderScoring</strong>: Checks the scoring status of an order, which is crucial for understanding if an order is still active or has been resolved.</li><li><strong>getActiveOrders</strong>: Fetches all open orders for a particular market, allowing users to monitor their trading activity.</li><li><strong>cancelOrder</strong>: Cancels a specific order by its ID.</li><li><strong>cancelAllOrders</strong>: Cancels all active orders associated with the wallet, providing a quick way to exit all positions.</li></ul><h3>Error Handling</h3><p>Effective error handling is crucial for building reliable services. In the ClobService, errors are caught using try-catch blocks. When an error occurs, a descriptive message is thrown, incorporating the relevant error enumeration from ERRORS_ENUM.</p><pre>catch (error) {<br>    throw new Error(`Error placing order: ${error}`);<br>}</pre><h3>Usage Example</h3><p>Here’s how you can utilize the ClobService within a NestJS controller to expose endpoints for interacting with the Polymarket CLOB.</p><h3>Creating the Controller</h3><p>Generate a new controller:</p><pre>import { Controller, Post, Get, Delete, Body, Query } from &#39;@nestjs/common&#39;;<br>import { ClobService } from &#39;./clob.service&#39;;<br><br>@Controller(&#39;clob&#39;)<br>export class ClobController {<br>    constructor(private readonly clobService: ClobService) { }<br><br>    @Post(&#39;create-api-key&#39;)<br>    async createApiKey(@Body() body: { rpcUrl: string; privateKey: string }) {<br>        const { rpcUrl, privateKey } = body;<br>        return await this.clobService.createApiKey(rpcUrl, privateKey);<br>    }<br><br>    @Get(&#39;get-api-keys&#39;)<br>    async getApiKeys(@Query() query: { rpcUrl: string; privateKey: string }) {<br>        const { rpcUrl, privateKey } = query;<br>        return await this.clobService.getApiKey(rpcUrl, privateKey);<br>    }<br><br>    @Delete(&#39;delete-api-key&#39;)<br>    async deleteApiKey(@Body() body: { rpcUrl: string; privateKey: string }) {<br>        const { rpcUrl, privateKey } = body;<br>        return await this.clobService.deleteApiKey(rpcUrl, privateKey);<br>    }<br><br>    @Post(&#39;place-order&#39;)<br>    async placeOrder(@Body() body: {<br>        rpcUrl: string;<br>        privateKey: string;<br>        tokenID: string;<br>        price: number;<br>        side: string;<br>        size: number;<br>        feeRateBps: number;<br>        nonce: number;<br>    }) {<br>        const { rpcUrl, privateKey, tokenID, price, side, size, feeRateBps, nonce } = body;<br>        return await this.clobService.placeOrder(rpcUrl, privateKey, tokenID, price, side, size, feeRateBps, nonce);<br>    }<br><br>    @Get(&#39;get-order&#39;)<br>    async getOrder(@Query() query: { rpcUrl: string; privateKey: string; orderID: string }) {<br>        const { rpcUrl, privateKey, orderID } = query;<br>        return await this.clobService.getOrder(rpcUrl, privateKey, orderID);<br>    }<br><br>    @Get(&#39;is-order-scoring&#39;)<br>    async isOrderScoring(@Query() query: { rpcUrl: string; privateKey: string; orderID: string }) {<br>        const { rpcUrl, privateKey, orderID } = query;<br>        return await this.clobService.isOrderScoring(rpcUrl, privateKey, orderID);<br>    }<br><br>    @Get(&#39;active-orders&#39;)<br>    async getActiveOrders(@Query() query: { rpcUrl: string; privateKey: string; market: string }) {<br>        const { rpcUrl, privateKey, market } = query;<br>        return await this.clobService.getActiveOrders(rpcUrl, privateKey, market);<br>    }<br><br>    @Delete(&#39;cancel-order&#39;)<br>    async cancelOrder(@Body() body: { rpcUrl: string; privateKey: string; orderID: string }) {<br>        const { rpcUrl, privateKey, orderID } = body;<br>        return await this.clobService.cancelOrder(rpcUrl, privateKey, orderID);<br>    }<br><br>    @Delete(&#39;cancel-all-orders&#39;)<br>    async cancelAllOrders(@Body() body: { rpcUrl: string; privateKey: string }) {<br>        const { rpcUrl, privateKey } = body;<br>        return await this.clobService.cancelAllOrders(rpcUrl, privateKey);<br>    }<br>}</pre><h3>Integrating the Controller and Service</h3><p>Ensure that both the ClobService and ClobController are registered in your module.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ClobService } from &#39;./clob.service&#39;;<br>import { ClobController } from &#39;./clob.controller&#39;;<br><br>@Module({<br>  controllers: [ClobController],<br>  providers: [ClobService],<br>})<br>export class ClobModule {}</pre><h3>Conclusion</h3><p>Building a NestJS service to interact with the Polymarket CLOB protocol empowers developers to automate trading strategies, manage API keys, and handle orders efficiently within their applications. By leveraging powerful libraries like ethers and the official @polymarket/clob-client, integrating decentralized prediction markets becomes a streamlined process.</p><p>This service can be further extended with features such as real-time order monitoring, enhanced security measures for handling private keys, and integration with frontend applications to provide a complete trading interface. As DeFi continues to grow, services like this will play a pivotal role in bridging traditional applications with decentralized protocols.</p><p>Feel free to customize and expand upon this service to fit your specific use cases and to contribute back to the developer community!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef175593cb65" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-a-nestjs-service-to-interact-with-the-polymarket-protocol-ef175593cb65">Building a NestJS Service to Interact with the Polymarket Protocol</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting the Sender from a Transaction with Go-Ethereum]]></title>
            <link>https://coinsbench.com/extracting-the-sender-from-a-transaction-with-go-ethereum-bf5e4b36bd31?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf5e4b36bd31</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 22:57:00 GMT</pubDate>
            <atom:updated>2024-06-14T21:20:45.603Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UC2tGzsceyRA9TNWaz5hPQ.png" /></figure><p>When working with Ethereum transactions in Go, extracting the sender (the address that initiated the transaction) is not straightforward. The go-ethereum library provides the necessary tools, but you need to follow a specific process to get the sender&#39;s address. This post will guide you through the steps required to extract the sender from a transaction using go-ethereum.</p><h4>Prerequisites</h4><p>Before we dive in, make sure you have the following:</p><ol><li>Go installed on your machine.</li><li>The go-ethereum package installed. If not, you can install it using:</li></ol><pre>go get github.com/ethereum/go-ethereum</pre><h4>Step-by-Step Guide</h4><ol><li><strong>Import Necessary Packages</strong></li></ol><p>Start by importing the necessary packages in your Go file:</p><pre>package main<br><br>import (<br>    &quot;log&quot;<br>    &quot;github.com/ethereum/go-ethereum/core/types&quot;<br>    &quot;github.com/ethereum/go-ethereum/ethclient&quot;<br>)</pre><p><strong>2. Get the Chain ID</strong></p><p>The chain ID is essential for signing and verifying transactions. Here’s a helper function to get the chain ID:</p><pre>func getChainId() (*big.Int, error) {<br>    client, err := ethclient.Dial(&quot;https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID&quot;)<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    chainID, err := client.NetworkID(context.Background())<br>    if err != nil {<br>        return nil, err<br>    }<br><br>    return chainID, nil<br>}</pre><p><strong>3. Extract the Sender</strong></p><p>Here’s the core function to extract the sender from a transaction:</p><pre>func getTxSender(tx *types.Transaction) (string, error) {<br>    chainId, err := getChainId()<br>    if err != nil {<br>        log.Fatal(&quot;Failed to get chainId:&quot;, err)<br>        return &quot;&quot;, err<br>    }<br><br>    sender, err := types.Sender(types.NewLondonSigner(chainId), tx)<br>    if err != nil {<br>        log.Fatal(&quot;Not able to retrieve sender:&quot;, err)<br>        return &quot;&quot;, err<br>    }<br><br>    return sender.Hex(), nil<br>}</pre><p>This function retrieves the chain ID, and then uses the types.Sender function with a NewLondonSigner to get the sender’s address. The NewLondonSigner is used to handle transactions post-EIP-1559 (the London hard fork).</p><p><strong>4. Usage Example</strong></p><p>Here’s an example of how to use the getTxSender function:</p><pre>func main() {<br>    // Example transaction hash<br>    txHash := &quot;0x...&quot;<br><br>    // Connect to Ethereum client<br>    client, err := ethclient.Dial(&quot;https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID&quot;)<br>    if err != nil {<br>        log.Fatal(&quot;Failed to connect to the Ethereum client:&quot;, err)<br>    }<br><br>    // Get the transaction<br>    tx, _, err := client.TransactionByHash(context.Background(), common.HexToHash(txHash))<br>    if err != nil {<br>        log.Fatal(&quot;Failed to retrieve transaction:&quot;, err)<br>    }<br><br>    // Get the sender<br>    sender, err := getTxSender(tx)<br>    if err != nil {<br>        log.Fatal(&quot;Failed to get transaction sender:&quot;, err)<br>    }<br><br>    log.Printf(&quot;Transaction was sent by: %s&quot;, sender)<br>}</pre><h3>Conclusion</h3><p>Extracting the sender from a transaction in Go using go-ethereum involves retrieving the chain ID and using the appropriate signer. This method ensures compatibility with transactions after the London hard fork. With the provided code snippets, you should be able to implement this functionality in your Go applications easily.</p><p>Feel free to leave comments or ask questions if you encounter any issues. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf5e4b36bd31" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/extracting-the-sender-from-a-transaction-with-go-ethereum-bf5e4b36bd31">Extracting the Sender from a Transaction with Go-Ethereum</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting and Converting Ethereum Transaction Input Data in Go]]></title>
            <link>https://coinsbench.com/extracting-and-converting-ethereum-transaction-input-data-in-go-5f88b653418c?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f88b653418c</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 21:18:17 GMT</pubDate>
            <atom:updated>2024-06-14T21:20:38.751Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3vXu3iy92FeZVrt_" /><figcaption>Photo by <a href="https://unsplash.com/@drawkit?utm_source=medium&amp;utm_medium=referral">DrawKit Illustrations</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Prerequisites</strong></p><ul><li>Go installed on your machine.</li><li>An Ethereum client (like Infura or a local node) and an RPC URL.</li><li>A basic understanding of Go and Ethereum transactions.</li></ul><p><strong>Step 1: Set Up Your Go Project</strong></p><p>First, create a new Go project and initialize it:</p><pre>mkdir go-ethereum-tx<br>cd go-ethereum-tx<br>go mod init go-ethereum-tx</pre><p>Next, install the required dependencies:</p><pre>go get github.com/ethereum/go-ethereum<br>go get github.com/joho/godotenv</pre><p><strong>Step 2: Create a .env File</strong></p><p>Create a .env file to store your RPC URL:</p><pre>touch .env</pre><p>Add your RPC URL to the .env file:</p><pre>RPC_URL=https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID</pre><p><strong>Step 3: Write the Go Code</strong><br>Create a main.go file and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/437d7b81df9a1f6b37cdd6ddbef35cd7/href">https://medium.com/media/437d7b81df9a1f6b37cdd6ddbef35cd7/href</a></iframe><p><strong>Step 4: Run the Go Code</strong></p><p>Run the Go code with:</p><p><strong>The output</strong></p><pre>Data (hex): de05e6a0000000000000000000000000000000000000000000000000056e62be0f8ea86100000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006655feb400000000000000000000000000000000000000000000000000000000000000640000000000000000000000000000000000000000000000000000000000000002000000000000000000000000030c5379b31b9910dcad606a0f1baa480ae6fbe4000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2</pre><p><strong>Explanation</strong></p><ol><li>Loading the RPC URL: We use the godotenv package to load environment variables from the .env file. The getRpcUrl function fetches the RPC URL for connecting to the Ethereum network.</li><li>Connecting to the Ethereum Client: The getBlockchainClient function establishes a connection to the Ethereum client using the RPC URL.</li><li>Fetching Transaction Data: The getTransactionData function retrieves transaction details using the transaction hash. It fetches the transaction from the Ethereum network and extracts relevant information such as the hash, value, gas, gas price, nonce, input data, sender, and recipient.</li><li>Converting Data to Hex String: The input data from the transaction is in byte format. We use the common.Bytes2Hex function to convert this byte data to a hexadecimal string, which is a readable and standard format for Ethereum transaction input data.</li><li>Printing the Results: The input data and the Keccak-256 hash of the data are printed in the console.</li></ol><p><strong>Conclusion</strong></p><p>In this tutorial, you learned how to extract transaction input data from a transaction hash in Go and convert the data from UTF-8 to a hexadecimal string. This approach ensures that the data is readable and can be compared with other sources like Etherscan.</p><p><strong>Github link</strong></p><p><a href="https://github.com/burgossrodrigo/go-transaction-data">https://github.com/burgossrodrigo/go-transaction-data</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f88b653418c" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/extracting-and-converting-ethereum-transaction-input-data-in-go-5f88b653418c">Extracting and Converting Ethereum Transaction Input Data in Go</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating 0x API with FastHTTP and Gin in Go]]></title>
            <link>https://coinsbench.com/integrating-0x-api-with-fasthttp-and-gin-in-go-125b4872c11a?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/125b4872c11a</guid>
            <category><![CDATA[fasthttp]]></category>
            <category><![CDATA[gin]]></category>
            <category><![CDATA[0x]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Thu, 16 May 2024 18:14:01 GMT</pubDate>
            <atom:updated>2024-05-17T14:09:35.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8w7LfH4K8zJCOjgOf4IgBA.jpeg" /></figure><p>In this article, we’ll explore how to build a simple service in Go that interacts with the 0x API to fetch various data such as sources, price, and quotes. We’ll use the fasthttp package for handling HTTP requests and the gin framework for setting up our web server.</p><h3>Setting Up the Project</h3><p>First, let’s set up our project structure. We’ll create the following directories and files:</p><p>aggregator/<br>│<br>├── pkg/<br>│ ├── zerox/<br>│ │ └── zerox.go<br>│ ├── models/<br>│ │ └── models.go<br>│ └── config/<br>│ └── config.go<br>├── main.go<br>├── .env<br>└── go.mod</p><h3>Installing Dependencies</h3><p>We’ll use fasthttp for fast HTTP requests, gin for the web framework, and godotenv for loading environment variables. Install these dependencies using the following commands:</p><pre>go get -u github.com/valyala/fasthttp<br>go get -u github.com/gin-gonic/gin<br>go get -u github.com/joho/godotenv</pre><h3>Configuration</h3><p>Create a .env file to store your 0x API key:</p><pre>ZEROXAPIKEY=your_api_key_here</pre><p>Next, let’s load this configuration in our Go code. Create a config.go file:</p><pre>package config<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br><br> models &quot;aggregator/pkg/models&quot;<br><br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>func LoadEnv() (cfg models.Configs) {<br> err := godotenv.Load()<br> if err != nil {<br>  log.Printf(&quot;Error loading .env file: %v&quot;, err)<br> }<br><br> cfg.ZeroXAPIKey = os.Getenv(&quot;ZEROXAPIKEY&quot;)<br><br> return cfg<br>}</pre><h3>Defining Models</h3><p>In models.go, define the structures for the data we&#39;ll be handling:</p><pre>package models<br><br>type Sources struct {<br> Records []string `json:&quot;records&quot;`<br>}<br><br>type Configs struct {<br> ZeroXAPIKey string `json:&quot;zeroXAPIKey&quot;`<br>}<br><br>type PriceResponse struct {<br> Price string `json:&quot;price&quot;`<br> Value string `json:&quot;value&quot;`<br> Gas string `json:&quot;gas&quot;`<br> EstimateGas string `json:&quot;estimateGas&quot;`<br> Sources []PriceResponseSources `json:&quot;sources&quot;`<br>}<br><br>type PriceResponseSources struct {<br> Name string `json:&quot;name&quot;`<br> Proportion string `json:&quot;proportion&quot;`<br>}<br><br>type QuoteResponse struct {<br> Price string `json:&quot;price&quot;`<br> To string `json:&quot;to&quot;`<br> Data string `json:&quot;data&quot;`<br> Value string `json:&quot;value&quot;`<br> EstimateGas string `json:&quot;estimateGas&quot;`<br> AllowanceTarget string `json:&quot;allowanceTarget&quot;`<br>}</pre><h3>Fetching Data from 0x API</h3><p>In zerox.go, implement functions to fetch sources, prices, and quotes from the 0x API:</p><pre>package zerox<br><br>import (<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;github.com/valyala/fasthttp&quot;<br> models &quot;aggregator/pkg/models&quot;<br> config &quot;aggregator/pkg/config&quot;<br>)<br><br>func FetchSources(chain string) (models.Sources, error) {<br> var url string<br> var sources models.Sources<br> cfg := config.LoadEnv()<br><br> switch chain {<br> case &quot;ethereum&quot;:<br>  url = &quot;https://api.0x.org/swap/v1/sources&quot;<br> default:<br>  url = fmt.Sprintf(&quot;https://%s.api.0x.org/swap/v1/sources&quot;, chain)<br> }<br><br> req := fasthttp.AcquireRequest()<br> req.SetRequestURI(url)<br> req.Header.SetMethod(&quot;GET&quot;)<br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> req.Header.Set(&quot;0x-api-key&quot;, cfg.ZeroXAPIKey)<br> defer fasthttp.ReleaseRequest(req)<br><br> resp := fasthttp.AcquireResponse()<br> defer fasthttp.ReleaseResponse(resp)<br><br> client := fasthttp.Client{}<br> err := client.Do(req, resp)<br> if err != nil {<br>  fmt.Println(err, &quot;error from client.Do&quot;)<br>  return models.Sources{}, err<br> }<br><br> if err := json.Unmarshal(resp.Body(), &amp;sources); err != nil {<br>  fmt.Println(err, &quot;error from json.Unmarshal&quot;)<br>  return models.Sources{}, err<br> }<br><br> return sources, err<br>}<br><br>func FetchPrice(chain, sellToken, buyToken, sellAmount string) (models.PriceResponse, error) {<br> var url string<br> var responsePrice models.PriceResponse<br> cfg := config.LoadEnv()<br><br> switch chain {<br> case &quot;ethereum&quot;:<br>  url = fmt.Sprintf(&quot;https://api.0x.org/swap/v1/price?sellToken=%s&amp;buyToken=%s&amp;sellAmount=%s&quot;,<br>   sellToken, buyToken, sellAmount)<br> default:<br>  url = fmt.Sprintf(&quot;https://%s.api.0x.org/swap/v1/price?sellToken=%s&amp;buyToken=%s&amp;sellAmount=%s&quot;,<br>   chain, sellToken, buyToken, sellAmount)<br> }<br><br> req := fasthttp.AcquireRequest()<br> req.SetRequestURI(url)<br> req.Header.SetMethod(&quot;GET&quot;)<br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> req.Header.Set(&quot;0x-api-key&quot;, cfg.ZeroXAPIKey)<br> defer fasthttp.ReleaseRequest(req)<br><br> resp := fasthttp.AcquireResponse()<br> defer fasthttp.ReleaseResponse(resp)<br><br> client := fasthttp.Client{}<br> err := client.Do(req, resp)<br> if err != nil {<br>  fmt.Println(err, &quot;error from client.Do&quot;)<br>  return models.PriceResponse{}, err<br> }<br><br> if err := json.Unmarshal(resp.Body(), &amp;responsePrice); err != nil {<br>  fmt.Println(err, &quot;error from json.Unmarshal&quot;)<br>  return models.PriceResponse{}, err<br> }<br><br> return responsePrice, err<br>}<br><br>func FetchQuote(chain, sellToken, buyToken, sellAmount, takerAddress, feeRecipient, buyTokenPercentageFee string) (models.QuoteResponse, error) {<br> var url string<br> var quoteResponse models.QuoteResponse<br> cfg := config.LoadEnv()<br><br> switch chain {<br> case &quot;ethereum&quot;:<br>  url = fmt.Sprintf(&quot;https://api.0x.org/swap/v1/quote?buyToken=%s&amp;sellToken=%s&amp;sellAmount=%s&amp;takerAddress=%s&amp;feeRecipient=%s&amp;buyTokenPercentageFee=%s&quot;,<br>   sellToken, buyToken, sellAmount, takerAddress, feeRecipient, buyTokenPercentageFee)<br> default:<br>  url = fmt.Sprintf(&quot;https://%s.api.0x.org/swap/v1/quote?buyToken=%s&amp;sellToken=%s&amp;sellAmount=%s&amp;takerAddress=%s&amp;feeRecipient=%s&amp;buyTokenPercentageFee=%s&quot;,<br>   chain, buyToken, sellToken, sellAmount, takerAddress, feeRecipient, buyTokenPercentageFee)<br> }<br><br> req := fasthttp.AcquireRequest()<br> req.SetRequestURI(url)<br> req.Header.SetMethod(&quot;GET&quot;)<br> req.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br> req.Header.Set(&quot;0x-api-key&quot;, cfg.ZeroXAPIKey)<br> defer fasthttp.ReleaseRequest(req)<br><br> resp := fasthttp.AcquireResponse()<br> defer fasthttp.ReleaseResponse(resp)<br><br> client := fasthttp.Client{}<br> err := client.Do(req, resp)<br> if err != nil {<br>  fmt.Println(err, &quot;error from client.Do&quot;)<br>  return models.QuoteResponse{}, err<br> }<br><br> if err := json.Unmarshal(resp.Body(), &amp;quoteResponse); err != nil {<br>  fmt.Println(err, &quot;error from json.Unmarshal&quot;)<br>  return models.QuoteResponse{}, err<br> }<br><br> return quoteResponse, err<br>}</pre><h3>Creating the Gin Server</h3><p>In main.go, set up the Gin server and define the routes to handle requests:</p><pre>package main<br><br>import (<br> zeroxservice &quot;aggregator/pkg/zerox&quot;<br> &quot;github.com/gin-gonic/gin&quot;<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> router := gin.Default()<br> router.GET(&quot;/zerox/sources/:chain&quot;, getZeroxSource)<br> router.GET(&quot;/zerox/price/:chain/:sellToken/:buyToken/:sellAmount&quot;, getZeroxPrice)<br> router.GET(&quot;/zerox/quote/:chain/:sellToken/:buyToken/:sellAmount/:takerAddress/:feeRecipient/:buyTokenPercentageFee&quot;, getZeroxQuote)<br> router.Run(&quot;:8080&quot;)<br>}<br><br>func getZeroxSource(c *gin.Context) {<br> chain := c.Param(&quot;chain&quot;)<br> sources, err := zeroxservice.FetchSources(chain)<br> if err != nil {<br>  fmt.Println(err, &quot;error from getZeroxSource&quot;)<br>  c.JSON(500, gin.H{&quot;error&quot;: err})<br> } else {<br>  c.JSON(200, sources)<br> }<br>}<br><br>func getZeroxPrice(c *gin.Context) {<br> chain := c.Param(&quot;chain&quot;)<br> sellToken := c.Param(&quot;sellToken&quot;)<br> buyToken := c.Param(&quot;buyToken&quot;)<br> sellAmount := c.Param(&quot;sellAmount&quot;)<br> price, err := zeroxservice.FetchPrice(chain, sellToken, buyToken, sellAmount)<br> if err != nil {<br>  fmt.Println(err, &quot;error from getZeroxPrice&quot;)<br>  c.JSON(500, gin.H{&quot;error&quot;: err})<br> } else {<br>  c.JSON(200, price)<br> }<br>}<br><br>func getZeroxQuote(c *gin.Context) {<br> chain := c.Param(&quot;chain&quot;)<br> sellToken := c.Param(&quot;sellToken&quot;)<br> buyToken := c.Param(&quot;buyToken&quot;)<br> sellAmount := c.Param(&quot;sellAmount&quot;)<br> takerAddress := c.Param(&quot;takerAddress&quot;)<br> feeRecipient := c.Param(&quot;feeRecipient&quot;)<br> buyTokenPercentageFee := c.Param(&quot;buyTokenPercentageFee&quot;)<br> quote, err := zeroxservice.FetchQuote(chain, sellToken, buyToken, sellAmount, takerAddress, feeRecipient, buyTokenPercentageFee)<br> if err != nil {<br>  fmt.Println(err, &quot;error from getZeroxQuote&quot;)<br>  c.JSON(500, gin.H{&quot;error&quot;: err})<br> } else {<br>  c.JSON(200, quote)<br> }<br>}</pre><h3>Running the Server</h3><p>To run the server, simply execute:</p><pre>go run main.go</pre><p>The server will start on port 8080, and you can test the endpoints using tools like Postman or cURL.</p><h3>Conclusion</h3><p>In this article, we’ve set up a simple Go service that interacts with the 0x API to fetch sources, prices, and quotes. Using fasthttp for fast HTTP requests and gin for routing, we created a robust and efficient service. This is a great starting point for building more complex services that interact with various APIs in the blockchain space.</p><p>You can find the whole project:</p><p><a href="https://github.com/burgossrodrigo/aggregator">https://github.com/burgossrodrigo/aggregator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=125b4872c11a" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/integrating-0x-api-with-fasthttp-and-gin-in-go-125b4872c11a">Integrating 0x API with FastHTTP and Gin in Go</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Balancer Price Retrieval API with NestJS]]></title>
            <link>https://coinsbench.com/building-a-balancer-price-retrieval-api-with-nestjs-5ad53e72e2cf?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad53e72e2cf</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[balancer]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Tue, 07 May 2024 15:10:15 GMT</pubDate>
            <atom:updated>2024-05-08T10:23:36.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*s7z335eC4cnrX_16NGXqhg.png" /></figure><p>In this tutorial, we will develop a simple API using NestJS that interacts with the Balancer Protocol to retrieve pool IDs and token prices. The Balancer Protocol enables automated market-making on the Ethereum blockchain, and our application will leverage its subgraph API and SDK.</p><h3>Prerequisites</h3><ul><li>Node.js installed (version 12.x or later)</li><li>NestJS CLI installed (npm i -g @nestjs/cli)</li><li>Basic understanding of TypeScript and asynchronous programming</li></ul><h3>Step 1: Setup Your NestJS Project</h3><p>First, create a new NestJS project if you haven’t already:</p><pre>nest new balancer-api<br>cd balancer-api</pre><h3>Step 2: Install Dependencies</h3><p>You’ll need the graphql-request library to make GraphQL requests and the @balancer-labs/sdk for interacting with the Balancer SDK.</p><pre>npm install graphql-request @balancer-labs/sdk</pre><h3>Step 3: Setting Up Enums and Interfaces</h3><p>Define necessary enums and interfaces to help with type safety and readability.</p><pre>export enum BalancerSubgraphUrl {<br>    MAINNET = &#39;https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-v2&#39;,<br>    POLYGON = &#39;https://api.thegraph.com/subgraphs/name/balancer-labs/balancer-polygon-v2&#39;<br>}</pre><pre>export interface BalancerPoolsResponse {<br>    id: string;<br>    poolType: string;<br>    poolTypeVersion: string;<br>}</pre><h3>Step 4: Ethereum Service</h3><p>This service will provide an RPC URL for the Balancer SDK configuration. Here’s a simple setup:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class EthereumService {<br>    async getWorkingProviderUrl(chainId: number): Promise&lt;string&gt; {<br>        // Mock function: replace with actual logic to retrieve RPC URL<br>        return &#39;https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID&#39;;<br>    }<br>}</pre><h3>Step 5: Balancer Service</h3><p>This service interacts with the Balancer subgraph and SDK.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { BalancerSubgraphUrl } from &#39;./balancer.enum&#39;;<br>import { BalancerPoolsResponse } from &#39;./balancer.interface&#39;;<br>import { GraphQLClient } from &#39;graphql-request&#39;;<br>import { BalancerSDK, BalancerSdkConfig } from &#39;@balancer-labs/sdk&#39;;<br>import { EthereumService } from &#39;../ethereum/ethereum.service&#39;;<br><br>@Injectable()<br>export class BalancerService {<br>    constructor(private readonly ethereumService: EthereumService) {}<br><br>    private subgraphUrl = (chainId: number) =&gt; BalancerSubgraphUrl[chainId];<br><br>    private graphQlClient = (chainId: number) =&gt; new GraphQLClient(this.subgraphUrl(chainId));<br><br>    private balanceSDKInstance = async (chainId: number) =&gt; {<br>        const config: BalancerSdkConfig = {<br>            network: chainId,<br>            rpcUrl: await this.ethereumService.getWorkingProviderUrl(chainId),<br>        };<br>        return new BalancerSDK(config);<br>    };<br><br>    async getPoolId(chainId: number, token0: string, token1: string): Promise&lt;BalancerPoolsResponse&gt; {<br>        const query = `{ pools(first: 100, where: { tokensList_contains: [&quot;${token0}&quot;, &quot;${token1}&quot;] }) { id poolType poolTypeVersion } }`;<br>        const client = this.graphQlClient(chainId);<br>        return client.request(query);<br>    }<br><br>    async getPoolPrice(chainId: number, token0: string, token1: string): Promise&lt;any&gt; {<br>        const balancer = await this.balanceSDKInstance(chainId);<br>        const poolId = await this.getPoolId(chainId, token0, token1);<br>        const pool = await balancer.pools.find(poolId.pools[0].id);<br>        return pool.calcSpotPrice(token0, token1);<br>    }<br>}</pre><h3>Step 6: Create Controller</h3><p>The controller will expose endpoints to interact with the Balancer service.</p><pre>import { Body, Controller, Post, UsePipes, ValidationPipe } from &#39;@nestjs/common&#39;;<br>import { ApiOperation, ApiResponse, ApiTags } from &#39;@nestjs/swagger&#39;;<br>import { BalancerService } from &#39;./balancer.service&#39;;<br>import { BalancerPoolIdRequestDto } from &#39;./dto/BalancerPoolIdRequest.dto&#39;;<br>import { BalancerPoolPriceRequestDto } from &#39;./dto/BalancerPoolPriceRequest.dto&#39;;<br><br>@ApiTags(&#39;balancer&#39;)<br>@Controller(&#39;balancer&#39;)<br>export class BalancerController {<br>    constructor(public readonly balancerService: BalancerService) {}<br><br>    @Post(&#39;get-pool-id&#39;)<br>    @ApiOperation({ summary: &#39;Get pool ID&#39;, description: &#39;Retrieve the pool ID for a given pair of tokens.&#39; })<br>    @ApiResponse({ status: 200, description: &#39;The pool ID has been successfully retrieved.&#39; })<br>    @ApiResponse({ status: 400, description: &#39;Invalid input.&#39; })<br>    @UsePipes(new ValidationPipe({ transform: true }))<br>    async getPoolId(@Body() body: BalancerPoolIdRequestDto) {<br>        return this.balancerService.getPoolId(Number(body.chainId), body.token0, body.token1);<br>    }<br><br>    @Post(&#39;get-pool-price&#39;)<br>    @ApiOperation({ summary: &#39;Get pool price&#39;, description: &#39;Retrieve the price of a given pair of tokens.&#39; })<br>    @ApiResponse({ status: 200, description: &#39;The pool price has been successfully retrieved.&#39; })<br>    @ApiResponse({ status: 400, description: &#39;Invalid input.&#39; })<br>    @UsePipes(new ValidationPipe({ transform: true }))<br>    async getPoolPrice(@Body() body: BalancerPoolPriceRequestDto) {<br>        return this.balancerService.getPoolPrice(Number(body.chainId), body.token0, body.token1);<br>    }<br>}</pre><h3>Step 7: Testing</h3><p>Create unit tests to ensure your services are functioning correctly.</p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { BalancerService } from &#39;./balancer.service&#39;;<br>import { EthereumService } from &#39;../ethereum/ethereum.service&#39;;<br><br>describe(&#39;BalancerService&#39;, () =&gt; {<br>    let service: BalancerService;<br><br>    beforeEach(async () =&gt; {<br>        const module: TestingModule = await Test.createTestingModule({<br>            providers: [BalancerService, EthereumService],<br>        }).compile();<br><br>        service = module.get&lt;BalancerService&gt;(BalancerService);<br>    });<br><br>    it(&#39;should be defined&#39;, () =&gt; {<br>        expect(service).toBeDefined();<br>    });<br><br>    it(&#39;should return a pool ID for given tokens on Polygon&#39;, async () =&gt; {<br>        const chainId = 137; // Polygon<br>        const token0 = &#39;0x4eD141110F6EeeAbA9A1df36d8c26f684d2475Dc&#39;;<br>        const token1 = &#39;0xf2f77FE7b8e66571E0fca7104c4d670BF1C8d722&#39;;<br>        const result = await service.getPoolId(chainId, token0, token1);<br>        const poolId = result.pools[0].id;<br>        expect(poolId).toEqual(&#39;0x42942cdec85078cf0e28e9cb5acd40cb53997ed6000000000000000000000bea&#39;);<br>    });<br>});</pre><p>This tutorial provided a foundation for building a NestJS application that interacts with the Balancer Protocol using GraphQL and the Balancer SDK. You can expand upon this by integrating additional functionality like handling more complex queries or supporting additional blockchain networks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad53e72e2cf" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-a-balancer-price-retrieval-api-with-nestjs-5ad53e72e2cf">Building a Balancer Price Retrieval API with NestJS</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Buiding Curve Finance Interactions with typescript and typechain]]></title>
            <link>https://coinsbench.com/buiding-curve-finance-interactions-with-typescript-and-typechain-7c50bcf144b3?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c50bcf144b3</guid>
            <category><![CDATA[typechain]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[curve-finance]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Fri, 03 May 2024 14:04:37 GMT</pubDate>
            <atom:updated>2024-05-06T14:55:21.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3sEIY35FZHQ6PbGQ4AUzQ.png" /></figure><h3>Using TypeChain for Ethereum Smart Contracts</h3><p>TypeChain generates TypeScript bindings for Ethereum smart contracts, providing static typing, autocompletion, and up-to-date contract ABIs. This ensures safer, faster development cycles by catching errors at compile time.</p><p>You can find more info about typechain in their github page. The command that we used to build the types was:</p><pre>npx typechain --target==ethers-v6</pre><p>Don’t forget to have the abi’s inside the root folder of the project.</p><h3>Key Components of CurveService</h3><p>Here are the crucial methods in CurveService along with code examples:</p><ol><li>Connecting to a Curve Pool Contract</li></ol><pre>public curvePoolInstance = async (poolAddress: string, chainId: number): Promise&lt;CurvePool&gt; =&gt; {<br>    return CurvePool__factory.connect(<br>        poolAddress,<br>        await this.ethereumService.chooseRpc(chainId)<br>    )<br>}</pre><p>2. Fetching Pool Data</p><pre>public async getCurvePoolData(poolAddress: string, chainId: number, numCoins: number): Promise&lt;CurvePoolData&gt; {<br>    const pool = await this.curvePoolInstance(poolAddress, chainId);<br>    const coins: string[] = [];<br>    const balances: number[] = [];<br><br>    for (let i = 0; i &lt; numCoins; i++) {<br>        const coin = await pool.coins(BigInt(i));<br>        const [amount, decimals] = await Promise.all([<br>            pool.balances(BigInt(i)),<br>            this.erc20Service.getDecimals(coin, chainId)<br>        ]);<br>        const formattedBalance = await this.erc20Service.formatUnitsFrom(Number(amount), decimals);<br><br>        coins.push(coin);<br>        balances.push(formattedBalance);<br>    }<br>    return { coins, balances };<br>}</pre><p>3. Finding Pool Address</p><pre>public async getCurvePoolAddress(registryAddress: string, token0: string, token1: string, chainId: number): Promise&lt;string&gt; {<br>    const registry = await this.curvePoolRegistryInstance(registryAddress, chainId);<br>    return registry[&#39;find_pool_for_coins(address,address)&#39;](token0, token1);<br>}</pre><p>4. Fetching pool price</p><pre>    public async getPriceBetweenTokens(poolAddress: string, chainId: number, token0: number, token1: number, amount: number): Promise&lt;bigint&gt; {<br>        try {<br>            const pool = await this.curvePoolInstance(poolAddress, chainId)<br>            return await pool.get_dy(token0, token1, amount)<br>        } catch (error) {<br>            throw new Error(`getPriceBetweenTokens: ${error.message}`)<br>        }<br>    }</pre><p>Clarifing that the token0 and token’ aren’t the addresses of these tokens, but the position (index) they represent inside the pool aka [0, 1, 2]</p><h3>Testing with NestJS</h3><p>Testing ensures our API behaves as expected. Here’s how we test the functionality of fetching a pool address:</p><pre>describe(&#39;CurveController&#39;, () =&gt; {<br>  let controller: CurveController;<br>  let service: CurveService;<br><br>  beforeEach(async () =&gt; {<br>    const module: TestingModule = await Test.createTestingModule({<br>      controllers: [CurveController],<br>      providers: [CurveService, Erc20Service, EthereumService]<br>    }).compile();<br><br>    controller = module.get&lt;CurveController&gt;(CurveController);<br>    service = module.get&lt;CurveService&gt;(CurveService);<br>  });<br><br>  it(&#39;should return a hardcoded address&#39;, async () =&gt; {<br>    expect(await service.getCurvePoolAddress(<br>      &#39;0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5&#39;,<br>      &#39;0xdAC17F958D2ee523a2206206994597C13D831ec7&#39;,<br>      &#39;0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&#39;,<br>      1<br>    )).toBe(&#39;0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7&#39;);<br>  })<br>});</pre><p>This article is a overviewn but don’t get shy in asking me for more profound insights :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c50bcf144b3" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/buiding-curve-finance-interactions-with-typescript-and-typechain-7c50bcf144b3">Buiding Curve Finance Interactions with typescript and typechain</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a NestJS API to Extract Prices from Thena Protocol]]></title>
            <link>https://coinsbench.com/building-a-nestjs-api-to-extract-prices-from-thena-protocol-e1763fe35343?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1763fe35343</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Thu, 02 May 2024 16:34:52 GMT</pubDate>
            <atom:updated>2024-05-03T12:08:40.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Meaq_9SP6M8p7yLB0CF-0Q.jpeg" /></figure><p>This tutorial will guide you through setting up a NestJS API that interacts with Ethereum-based contracts to fetch and process token prices from the Thena protocol. By the end, you’ll have a service that can retrieve and compute the prices of tokens in a given liquidity pool.</p><h3>Prerequisites</h3><ul><li>Basic understanding of TypeScript and Node.js.</li><li>Familiarity with Ethereum blockchain concepts like smart contracts.</li><li>Node.js and NestJS installed on your machine.</li><li>An Ethereum wallet with some test ETH for deploying contracts (optional).</li><li>Familarity with typechain cli</li></ul><h3>Setup</h3><p>Create a new NestJS project if you haven’t already:</p><pre>nest new thena-price-api</pre><p>Navigate into your project directory:</p><pre>cd thena-price-api</pre><p>You will need ethers.js to interact with Ethereum blockchain:</p><pre>npm install ethers</pre><p>Install additional TypeScript definitions for development:</p><pre>npm install --save-dev @types/ethers</pre><p>Install also typechain and typechain ethers-v6 targer:</p><pre>npm install --save-dev typechain &amp;&amp; @typechain/ethers-v6</pre><h3>Ethereum Service</h3><p>You can find how to build the ethereum service here:</p><p><a href="https://medium.com/coinsbench/automated-test-for-ethereum-service-on-nestjs-a217a1676807">https://medium.com/coinsbench/automated-test-for-ethereum-service-on-nestjs-a217a1676807</a></p><h3>ERC20 Service:</h3><p>First we will need the ERC20 abi, you can find it in this gist:</p><p><a href="https://gist.github.com/veox/8800debbf56e24718f9f483e1e40c35c">https://gist.github.com/veox/8800debbf56e24718f9f483e1e40c35c</a></p><p>Right after i need to save the content of the file in a folder named abi, inside the folder from erc20 service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*aGsRSwVfDBl4XPttDGhdlw.png" /></figure><p>In the root folder of the nest app i need you to run the following command:</p><pre>npx typechain --target=ethers-v6</pre><p>The output should be this:</p><pre>Successfully generated n typings!</pre><p>Then we proceed to the code. The general aspect of the class should be somthing like this:</p><pre>@Injectable()<br>export class Erc20Service { ... }</pre><p><strong>Our first method should be this one, getTokenInstance:</strong></p><pre>    getTokenInstance = async (tokenAddress: string, chainId: number): Promise&lt;ERC20&gt; =&gt; {<br>        return ERC20__factory.connect(<br>            tokenAddress,<br>            await this.ethereumService.chooseRpc(chainId)<br>        )<br>    }</pre><p>The ERC20__factory were generated by typechain, it includes a couple of methods, but the one that is of our interest at the moment is the connect(). which takes two arguments, the address of the contract aka address of the token and an runner, that for our purpose means an json rpc provider (but would required an wallet if we are planning to sign transactions).</p><h4>Our second method, getTokenData():</h4><pre>    public async getTokenData(tokenAddress: string, chainId: number): Promise&lt;ITokenData&gt; {<br>        try {<br>            const token = await this.getTokenInstance(tokenAddress, chainId)<br>            const [decimals, symbol, name] = await Promise.all([<br>                token.decimals(),<br>                token.symbol(),<br>                token.name()<br>            ])<br>            return { decimals, symbol, name }<br>        } catch (error) {<br>            throw new Error(`getTokenData: ${error.message}`)<br>        }<br>    }</pre><p>It’s a generic method to extract sensible data from a ERC20 smartcontract. These are decimals, symbol and name. Let’s hold with this for now.</p><p>We also need two methods to adapt decimals from the smart contract when we are extracting decimals data and to the smart contract when we are sending transactions:</p><pre>    public formatUnitsFrom(amount: number, decimals: number): number {<br>        return amount / Math.pow(10, decimals)<br>    }<br><br>    public formatUnitsTo(amount: number, decimals: number): number {<br>        return amount * Math.pow(10, decimals)<br>    }</pre><h3>THENA Service:</h3><p>We will need to reproduce the same process with the ERC20 abi to generate types with typechain. Here goes the ABI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3a18c70c80834afb9a556690733132/href">https://medium.com/media/0d3a18c70c80834afb9a556690733132/href</a></iframe><p>Copy the content of this gist in an Pool.abi file and save it inside the folder from the Thena service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*J47vFjpumkf9D3UnemB8Xg.png" /></figure><p>Again, execute this line on the root of the nestjs:</p><pre>npx typechain --target=ethers-v6</pre><p>The output:</p><pre>Successfully generated ntypings!</pre><p>First let’s declare the constructor of our class import the additional services:</p><pre>    constructor(<br>        public readonly ethereumService: EthereumService,<br>        public readonly erc20Service: Erc20Service<br>    ) { }</pre><p>Then we proceed to instanciate the contract we want to deal with using the class generated with typechain:</p><pre>    public getPoolInstance = async (poolAddress: string, chainId: number): Promise&lt;Pool&gt; =&gt; {<br>        return Pool__factory.connect(<br>            poolAddress,<br>            await this.ethereumService.chooseRpc(chainId)<br>        )<br>    }</pre><p>The main method to extract the pool data:</p><pre>    public async getPoolData(poolAddress: string, chainId: number): Promise&lt;IRawPoolData&gt; {<br>        try {<br>            const pool = await this.getPoolInstance(poolAddress, chainId)<br><br>            const [reserves, token0, token1] = await Promise.all([<br>                pool.getReserves(),<br>                pool.token0(),<br>                pool.token1()<br>            ])<br><br>            return { token0: token0, token1: token1, reserves: reserves }<br><br>        } catch (error) {<br>            throw new Error(`getPoolData: ${error.message}`)<br>        }<br>    }</pre><p>A second method to process raw data to a more human redable format:</p><pre>    public async processPoolData(poolAddress: string, chainId: number): Promise&lt;IPoolData&gt; {<br>        try {<br>            const { token0, token1, reserves } = await this.getPoolData(poolAddress, chainId)<br>            console.log(reserves._reserve0, reserves._reserve1, &#39;here&#39;)<br>            const token0Data = await this.ethereumService.getTokenData(chainId, token0)<br>            const token1Data = await this.ethereumService.getTokenData(chainId, token1)<br>            const price0 = this.erc20Service.formatUnitsFrom(Number(reserves._reserve0), Number(token0Data.decimals)) / this.erc20Service.formatUnitsFrom(Number(reserves._reserve1), Number(token1Data.decimals))<br>            const price1 = 1 / price0<br>            return { token0, token1, price0, price1 }<br>        } catch (error) {<br>            throw new Error(`processPoolData: ${error.message}`)<br>        }<br>    }</pre><p>And last, a controller to deliver the data from the api:</p><pre>  @Post(&#39;/get-pool-data&#39;)<br>  @ApiOperation({ summary: &#39;Get raw pool data from the blockchain&#39; })<br>  @ApiResponse({ status: 200, description: &#39;The pool data&#39;, type: PoolDataResponseDto })<br>  @UsePipes(new ValidationPipe({ transform: true }))<br>  async getPoolData(<br>    @Body(&#39;poolAddress&#39;, ValidateEthereumAddressPipe) poolAddress: string,<br>    @Body() poolDataRequestDto: PoolDataRequestDto<br>  ): Promise&lt;PoolDataResponseDto&gt; {<br>    const { chainId } = poolDataRequestDto;<br>    const data = await this.thenaService.processPoolData(poolAddress, chainId);<br>    return {<br>      token0: data.token0,<br>      token1: data.token1,<br>      price0: data.price0,<br>      price1: data.price1,<br>    };<br>  }</pre><p>This way you will be able to interact with the api through swagger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0O0V0iQE3pc2HaGX502pg.png" /></figure><p>That’s all folk. Obviously i will not deliver everything thus you will work on it, try for yourselves and overcome the challenges that may appear but fell free to ask me for help :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1763fe35343" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/building-a-nestjs-api-to-extract-prices-from-thena-protocol-e1763fe35343">Building a NestJS API to Extract Prices from Thena Protocol</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated test for Ethereum service on NestJS]]></title>
            <link>https://coinsbench.com/automated-test-for-ethereum-service-on-nestjs-a217a1676807?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a217a1676807</guid>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 04:10:51 GMT</pubDate>
            <atom:updated>2024-04-30T15:53:12.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1lFC2sUIVRC5RmQGEW70w.png" /></figure><p>The use case of this approach is to avoid breaking your app in production due to basic errors on your script. It obviously can be extended but it’s an excelent starting point.</p><h3>Ethereum Service</h3><blockquote>Next we will see a very basic class in typescript with three methods:</blockquote><pre>getProvider(providerUrl: string): ethers.JsonRpcProvider</pre><blockquote>Which only returns an instance for an ethers v6 <strong>JsonRpcProvider</strong>.</blockquote><pre>async getWorkingProvider(providerUrls: string[]): Promise&lt;ethers.JsonRpcProvider&gt;</pre><blockquote>A bit more complex due an loop that interacts with an array of url’s and verify if any of then are responsive using asyncronous <strong>provider.getNetwork()</strong> method within the provider instance.</blockquote><pre>chooseRpcUrl(network: string): Promise&lt;ethers.JsonRpcProvider&gt;</pre><blockquote>This last method, also very simple is only an interaction through an enum with an switch statement to choose which chain to perform <strong>getWorkingProvider()</strong></blockquote><h3>Test script</h3><pre>  describe(&#39;getWorkingProvider&#39;, () =&gt; {<br>    it(&#39;should return a provider for the mainnet&#39;, async () =&gt; {<br>      const provider = await service.getWorkingProvider(ETHEREUM_MAINNET_URL);<br>      expect(provider).toBeDefined();<br>      expect((await provider.getNetwork()).chainId).toBe(BigInt(1));<br>    });<br>  });</pre><p>Basically we invoke the <strong>getNetwork() </strong>method from the provider (which comes in BigInt format in ethers v6) knowing that it should be 1 for ethereum mainnet and then we comparte it with the <strong>toBe</strong> method from the expect.</p><p>The same can be reproduced within the other chains:</p><pre>  describe(&#39;getWorkingProvider&#39;, () =&gt; {<br>    it(&#39;should return a provider for the mainnet&#39;, async () =&gt; {<br>      const provider = await service.getWorkingProvider(BSC_MAINNET_URL);<br>      expect(provider).toBeDefined();<br>      expect((await provider.getNetwork()).chainId).toBe(BigInt(56));<br>    });<br>  })</pre><p>The output from the test should be like this:</p><pre> PASS  src/ethereum/ethereum.service.spec.ts (11.012 s)<br>  EthereumService<br>    √ should be defined (47 ms)<br>    chooseRpcUrl<br>      √ should return a provider for the mainnet (235 ms)<br>    getWorkingProvider<br>      √ should return a provider for the mainnet (159 ms)<br>      √ should return a provider for the mainnet (953 ms)</pre><p>The whole code (service and test):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083f71b7411bb60320f9ac8ad8f88a8d/href">https://medium.com/media/083f71b7411bb60320f9ac8ad8f88a8d/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a217a1676807" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/automated-test-for-ethereum-service-on-nestjs-a217a1676807">Automated test for Ethereum service on NestJS</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An approach on fetching ethereum block data with Go]]></title>
            <link>https://coinsbench.com/an-approach-on-fetching-ethereum-block-data-with-go-2f82f8358fd7?source=rss-f997f4ded7f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f82f8358fd7</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Burgossrodrigo]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 02:52:40 GMT</pubDate>
            <atom:updated>2024-04-26T10:33:27.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0dvLzeOPKBhh8AwztkxsQ.png" /></figure><p>Between low level programing languages available for buiding your blockchain project, Go is the one with more resources and community, feature that make it a great choice when building your blockchain application.</p><p>In this tutorial we will find one among a couple of approaches avaiable out there to fetch block data from ethereum.</p><p>First of all, we need to run our project:</p><pre>go mod init fetch-block-data</pre><p>Since the project is created, we need to move foward and install the main library the we will be using, which is Geth client from Go-Ethereum:</p><pre>go get github.com/ethereum/go-ethereum/ethclient</pre><p>Right after we proceed to install godotenv` which is usefull to extract enviroments variables:</p><pre>go get github.com/joho/godotenv</pre><p>Another library which will be usefull is the core from Geth, from where we will be extracting our types:</p><pre>go get github.com/ethereum/go-ethereum/core/</pre><p>Let’s cut to the next phase whom we will be writing the foundation of our script:</p><p>A method to extract the RPC url from the enviroment:</p><pre>func getRpcUrl() string {<br><br> if err := godotenv.Load(); err != nil {<br>  log.Fatal(err, `for getRpcUrl`)<br> }<br><br> rpcUrl := os.Getenv(&quot;RPC_URL&quot;)<br> fmt.Println(&quot;RPC_URL: v%&quot;, rpcUrl)<br> return rpcUrl<br>}</pre><p>Another method to instanciate our blockchain client:</p><pre>func getBlockchainClient() *ethclient.Client {<br> client, err := ethclient.Dial(getRpcUrl())<br> if err != nil {<br>  log.Fatal(err, `for getBlockchainClient`)<br> }<br> return client<br>}</pre><p>This method is important to retrieve the last block from the chain:</p><pre>func getLastBlock() *big.Int {<br> client := getBlockchainClient()<br> blockNumber, err := client.HeaderByNumber(context.Background(), nil)<br> if err != nil {<br>  log.Fatal(err, `for getLastBlock`)<br> }<br> return blockNumber.Number<br>}</pre><p>Is smart of ours to declare struct to declare the properties that we want to extract from the block. along with each type:</p><pre>type BlockData struct {<br> Number       *big.Int<br> Hash         string<br> ParentHash   string<br> Nonce        uint64<br> Sha3Uncles   string<br> Miner        string<br> Difficulty   *big.Int<br> ExtraData    string<br> Size         uint64<br> GasLimit     uint64<br> GasUsed      uint64<br> Timestamp    uint64<br> Transactions []string<br>}</pre><p>Covering that, we can proceed to write the method that will actually extract and format our block info:</p><pre>func getBlockData() *BlockData {<br> lastBlock := getLastBlock()<br> client := getBlockchainClient()<br> block, err := client.BlockByNumber(context.Background(), lastBlock)<br> if err != nil {<br>  log.Fatal(err, `for getBlockData`)<br> }<br><br> return &amp;BlockData{<br>  Number:       block.Number(),<br>  Hash:         block.Hash().Hex(),<br>  ParentHash:   block.ParentHash().Hex(),<br>  Nonce:        block.Nonce(),<br>  Sha3Uncles:   block.UncleHash().Hex(),<br>  Miner:        block.Coinbase().Hex(),<br>  Difficulty:   block.Difficulty(),<br>  ExtraData:    string(block.Extra()),<br>  Size:         block.Size(),<br>  GasLimit:     block.GasLimit(),<br>  GasUsed:      block.GasUsed(),<br>  Timestamp:    block.Time(),<br>  Transactions: getTransactions(block),<br> }<br>}</pre><p>Last but not least, a method to handle the transactions:</p><pre>func getTransactions(block *ethGotypes.Block) []string {<br> var transactions []string<br> for _, tx := range block.Transactions() {<br>  transactions = append(transactions, tx.Hash().Hex())<br> }<br> return transactions<br>}</pre><p>You will be able to output the data through:</p><pre>func main() {<br> fmt.Println(getBlockData())<br>}</pre><p>The whole code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6931a55fb74ab2c1889ebd1c9f4405cb/href">https://medium.com/media/6931a55fb74ab2c1889ebd1c9f4405cb/href</a></iframe><p>Feel free to reach me through the links:</p><p>Telegram: @burgossrodrigo<br>Linkeding: in/burgossrodrigo</p><p>Tips: 0xe25bf122bc1369754edEC5318AF399EB9D0857CB</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f82f8358fd7" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/an-approach-on-fetching-ethereum-block-data-with-go-2f82f8358fd7">An approach on fetching ethereum block data with Go</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>