<?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 Néstor Nicolás Campos Rojas on Medium]]></title>
        <description><![CDATA[Stories by Néstor Nicolás Campos Rojas on Medium]]></description>
        <link>https://medium.com/@n.campos.rojas?source=rss-f6dfc08284ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1llnWyrHzQVAtirK</url>
            <title>Stories by Néstor Nicolás Campos Rojas on Medium</title>
            <link>https://medium.com/@n.campos.rojas?source=rss-f6dfc08284ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:12:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@n.campos.rojas/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[El fin de las suscripciones en la IA: La alianza Sui + Alibaba Cloud y la era del “Pay-per-Call”]]></title>
            <link>https://medium.com/@n.campos.rojas/el-fin-de-las-suscripciones-en-la-ia-la-alianza-sui-alibaba-cloud-y-la-era-del-pay-per-call-8b96f970d8f5?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b96f970d8f5</guid>
            <category><![CDATA[sui-network]]></category>
            <category><![CDATA[alibabacloud]]></category>
            <category><![CDATA[pay-per-call]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 23:11:57 GMT</pubDate>
            <atom:updated>2026-10-10T23:11:57.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M23lUVAUUDsKeY6nq8dIqQ.jpeg" /><figcaption>M2M Payments</figcaption></figure><p>El modelo de monetización del software tradicional no fue concebido para la inteligencia artificial autónoma. Durante años, hemos adaptado la infraestructura web mediante suscripciones SaaS mensuales y cobros recurrentes con tarjetas de crédito. Sin embargo, cuando un agente de IA necesita consumir recursos de cómputo en la nube, llamar a una API de inferencia de LLM o acceder a datos en tiempo real, depender de una tarjeta de crédito o una factura recurrente genera fricción operativa y riesgos de seguridad inaceptables.</p><p>Durante el evento <strong>Sui Basecamp</strong> en Singapur, <strong>Mysten Labs (Sui)</strong> anunció una alianza estratégica con <strong>Alibaba Cloud</strong> para integrar su framework <strong>Sui Agent Payments</strong>. Esta colaboración introduce un cambio de paradigma: la transición hacia <strong>pagos de máquina a máquina (<em>Machine-to-Machine</em> o M2M) bajo el esquema de pago por llamada a API (<em>pay-per-call</em>) en <em>stablecoins</em></strong>.</p><p>A continuación, analizamos la arquitectura técnica de este modelo, las ventajas operativas de Sui y los desafíos que la industria deberá resolver.</p><h3>1. El Paradigma “Pay-per-Call”: De las Tarjetas de Crédito a las Stablecoins</h3><p>El flujo tradicional de consumo de APIs en la nube obliga a las empresas a prepagar créditos, contratar planes corporativos o asociar tarjetas de crédito a claves de API (<em>API keys</em>). Para un agente de IA autónomo, esto presenta dos limitantes principales:</p><ol><li><strong>Falta de granularidad:</strong> Se paga por rangos o planes fijos en lugar del consumo exacto de tokens.</li><li><strong>Riesgo de exposición de credenciales:</strong> Dar acceso directo a una línea de crédito o tarjeta bancaria a un proceso automatizado expone la tesorería a cobros indeseados o vulnerabilidades de seguridad.</li></ol><p>La integración de Sui Agent Payments con la infraestructura de Alibaba Cloud permite que las cargas de trabajo de IA liquiden en tiempo real cada ejecución de cómputo, almacenamiento o inferencia directamente <em>on-chain</em>.</p><pre>[ Agente de IA ] ──( 1. Llama a API de Cómputo )──&gt; [ Alibaba Cloud ]<br>       │                                                   │<br>       ├──( 2. Pago micropago en Stablecoin )──────────────┘<br>       └─&gt; [ Contrato Delegado / Sui Blockchain ]</pre><h3>2. Arquitectura Técnica y Capacidades Clave de Sui</h3><p>Para que los micropagos M2M sean viables a gran escala, la red blockchain subyacente debe cumplir con criterios estrictos de latencia, costo y usabilidad. La propuesta de Sui se apoya en tres pilares fundamentales:</p><h4>Presupuestos Programables y Wallets Delegadas</h4><p>En lugar de dar firma ilimitada al agente, la tesorería asigna una <strong>wallet delegada con permisos restringidos</strong>. El contrato inteligente define un tope máximo de gasto (por ejemplo, 50 USDC al día) o reglas específicas de uso. El agente ejecuta solicitudes de forma autónoma, pero el protocolo bloquea cualquier intento de exceso sobre el presupuesto programado sin requerir intervención humana en cada transacción.</p><h4>Transacciones Gasless y Pagos en Stablecoins</h4><p>Un problema recurrente en las transacciones automatizadas en blockchain es la gestión del token nativo para cubrir las tarifas de red (<em>gas fees</em>). Si una wallet se queda sin saldo nativo (en este caso, <em>SUI</em>), la ejecución del agente se interrumpe inmediatamente.</p><p>A través de esquemas de patrocinio de transacciones (<em>Sponsored Transactions</em>), las transacciones en Sui pueden ser <strong>gasless para el agente</strong>: este solo transacciona la <em>stablecoin</em> acordada (como USDC), mientras que el patrocinador o la propia infraestructura absorbe o liquida el costo de red en segundo plano.</p><h4>Rendimiento Paralelo (Parallel Execution) y Baja Latencia</h4><p>El procesamiento de transacciones orientadas a objetos de Sui permite ejecutar micropagos en paralelo sin cuellos de botella en la memoria (<em>mempool</em>). Esto garantiza que la confirmación del pago ocurra en subsegundos, evitando retrasos en la respuesta de las llamadas a la API.</p><h3>3. Desafíos de Ingeniería y Gestión de Riesgos</h3><p>A pesar del potencial transformador de este modelo, existen varios retos operativos y de arquitectura que deben abordarse antes de su adopción masiva en entornos de producción:</p><ul><li><strong>Infección por bucles infinitos (<em>Loop Infections</em>):</strong> Un error de código o un fallo de lógica en un agente de IA puede generar un bucle repetitivo de llamadas a una API. En un esquema <em>pay-per-call</em> sin supervisión, esto podría agotar el presupuesto asignado en cuestión de segundos. Se requiere la implementación de mecanismos estrictos de <em>circuit breakers</em>, <em>rate-limiting</em> a nivel de contrato inteligente y alertas programáticas.</li><li><strong>Integración con Infraestructuras Existentes:</strong> Las empresas requerirán SDKs modulares y middleware para conectar sus pipelines actuales de CI/CD e IA con las wallets de Sui sin reescribir su arquitectura backend.</li></ul><h3>Conclusión</h3><p>La alianza entre Sui y Alibaba Cloud es un hito clave hacia la <strong>economía de agentes autónomos</strong>. Al combinar infraestructura en la nube de alta disponibilidad con liquidaciones programables y transparentes <em>on-chain</em>, la industria da un paso decisivo para sustituir las fricciones de la banca tradicional por protocolos M2M eficientes, seguros y escalables.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b96f970d8f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[La Batalla por la IA Soberana: Del Poder Geopolítico a los Modelos Pequeños y Blockchain]]></title>
            <link>https://medium.com/@n.campos.rojas/la-batalla-por-la-ia-soberana-del-poder-geopol%C3%ADtico-a-los-modelos-peque%C3%B1os-y-blockchain-c7de7472f477?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7de7472f477</guid>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 23:21:05 GMT</pubDate>
            <atom:updated>2026-08-15T23:21:05.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qnOiiad_YosSoOXD71rEw.jpeg" /><figcaption>IA soberana</figcaption></figure><p>En los últimos años, la inteligencia artificial ha dejado de ser únicamente un tema de innovación tecnológica para convertirse en el epicentro de la política mundial. Así como en el siglo XX el petróleo y el poder militar definieron a las superpotencias, en el siglo XXI la soberanía tecnológica sobre los modelos de IA está reconfigurando el mapa geopolítico.</p><h3>El Nuevo Tablero Geopolítico: La Carrera por la Autonomía Tecnológica</h3><p>Hoy presenciamos una auténtica “guerra fría digital”. Las naciones han comprendido que depender exclusivamente de infraestructura o modelos desarrollados por terceros implica ceder el control sobre sus datos, sus valores culturales y, en última instancia, su seguridad nacional.</p><p>Estados Unidos ha liderado el mercado comercial de la mano de gigantes tecnológicos como OpenAI, Google y Anthropic, respaldados por la concentración de chips de última generación de NVIDIA. Por otro lado, la Unión Europea ha apostado fuertemente por la regulación, buscando equilibrar la protección de la privacidad con la soberanía digital de los países miembros. Sin embargo, depender de soluciones “llave en mano” extranjeras conlleva riesgos obvios: censura, sesgos culturales ajenos e interrupciones en la cadena de suministro tecnológico si las tensiones internacionales aumentan. Por ello, el concepto de <strong>IA Soberana, </strong>es decir, la capacidad de un país o región para crear, entrenar y desplegar sus propios sistemas de IA, se ha transformado en un imperativo de estado.</p><h3>La Estrategia de China: Apertura Táctica y Dominio Industrial</h3><p>Para entender cómo un país busca su soberanía tecnológica, el ejemplo de China es uno de los más claros. Enfrentando bloqueos comerciales y restricciones en la exportación de chips avanzados por parte de Estados Unidos, China adoptó una doble estrategia: desarrollo masivo de hardware local y una agresiva apuesta por el modelo <em>Open Source.</em></p><p>Empresas chinas como Alibaba (con su familia de modelos Qwen) o la comunidad investigadora local han lanzado modelos de altísima calidad disponibles para el mundo entero. Esta “apertura táctica” busca dos objetivos principales:</p><ol><li><strong>Reducir la brecha tecnológica:</strong> Al permitir que millones de desarrolladores globales adopten y optimicen sus modelos, fortalecen su propio ecosistema informático.</li><li><strong>Crear estándares propios:</strong> Si los sistemas de empresas mundiales corren sobre la arquitectura de modelos chinos, la dependencia geopolítica cambia de sentido.</li></ol><p>Además, China ha integrado sus modelos directamente en su capacidad industrial y manufacturera, orientando la IA hacia problemas productivos reales antes que a meras aplicaciones de entretenimiento o chatbots generales.</p><h3>Los Modelos Pequeños (SLMs): La Llave de la Soberanía Democrática</h3><p>Tradicionalmente se pensaba que para tener un modelo de IA útil se necesitaban supercomputadores con miles de tarjetas gráficas que cuestan decenas de millones de dólares, algo inalcanzable para pequeñas naciones, startups o instituciones locales.</p><p>Aquí es donde entran los <strong>Modelos Pequeños de Lenguaje</strong> (o <em>SLMs</em>, por sus siglas en inglés: <em>Small Language Models</em>).</p><p>A diferencia de los Grandes Modelos de Lenguaje (LLMs) como GPT-4, los SLMs son inteligencias artificiales optimizadas que contienen menos parámetros, pero que han sido entrenadas con datos altamente especializados e idóneos. Sus ventajas para la IA soberana son enormes:</p><ul><li><strong>Soberanía real de datos:</strong> Al ser livianos, estos modelos pueden ejecutarse de forma local (<em>on-premises</em>), en servidores nacionales o incluso en teléfonos y computadores portátiles. Los datos nunca salen del país ni de la organización.</li><li><strong>Eficiencia y bajo costo:</strong> Requieren una fracción del consumo eléctrico y de la potencia de cómputo que exigen los modelos masivos, permitiendo que gobiernos locales o pequeñas empresas los entrenen y operen con presupuestos moderados.</li><li><strong>Alineación cultural y de dominio:</strong> Un modelo pequeño entrenado específicamente en las leyes, la historia, la medicina local o el idioma propio de una región responderá mucho mejor a las necesidades específicas de su comunidad que un modelo masivo entrenado con datos predominantemente anglosajones.</li></ul><p>Los SLMs están democratizando la IA Soberana, ya que demuestran que no se necesita ser una megacorporación para ser tecnológicamente independiente.</p><h3>El valor de Blockchain en la IA: La Capa de Confianza, Transparencia e Inmutabilidad</h3><p>Si la IA Soberana nos permite controlar la tecnología y los SLMs nos dan la eficiencia para operarla localmente, ¿cómo garantizamos la transparencia y la descentralización de estos sistemas? La respuesta está en la tecnología <strong>Blockchain</strong>.</p><p>Aunque suele asociársela únicamente con las criptomonedas, Blockchain es, en esencia, un libro contable digital, descentralizado, inalterable y transparente. Al integrar Blockchain con la IA Soberana, obtenemos beneficios fundamentales:</p><ol><li><strong>Trazabilidad y procedencia de los datos:</strong> Uno de los mayores riesgos de la IA son los sesgos y las “alucinaciones”. Mediante la blockchain, se puede registrar de manera inmutable el origen exacto de los datos utilizados para entrenar un modelo soberano, garantizando que no se usó información manipulada o sesgada.</li><li><strong>Propiedad y gobernanza descentralizada:</strong> En lugar de que un solo gobierno o entidad controle el modelo soberano, una red descentralizada en blockchain permite una gobernanza transparente mediante contratos inteligentes, donde la comunidad verifica las reglas del juego.</li><li><strong>Redes de Cómputo Descentralizadas (DePIN):</strong> Gracias a incentivos criptográficos, hoy es posible sumar la potencia de cómputo de miles de computadores independientes alrededor del mundo para entrenar o ejecutar modelos de IA, eliminando la necesidad de depender de los grandes centros de datos de las ‘Big Tech’.</li><li><strong>Verificación de Identidad y Contenido:</strong> En un mundo inundado por <em>deepfakes</em> y contenido sintético, registrar las firmas digitales de los modelos soberanos en la blockchain permite verificar al instante si un documento, audio o respuesta proviene de una fuente oficial y confiable.</li></ol><h3>El Camino Hacia el Futuro</h3><p>La soberanía en la era digital no se logrará aislándonos ni tratando de competir a ciegas con los presupuestos multimillonarios de Silicon Valley. El verdadero camino hacia una IA libre, segura e independiente pasa por la convergencia de tecnologías: <strong>Modelos Pequeños (SLMs)</strong> adaptados a necesidades locales concretas, combinados con la infraestructura transparente e inalterable de <strong>Blockchain</strong>.</p><p>Construir una IA Soberana no es solo una decisión tecnológica, es una estrategia vital para garantizar la autonomía, la privacidad y la identidad cultural de las sociedades del mañana.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7de7472f477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending my agent to any SIP010 token]]></title>
            <link>https://medium.com/@n.campos.rojas/extending-my-agent-to-any-sip010-token-fdffd42fb24c?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdffd42fb24c</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[fungible-tokens]]></category>
            <category><![CDATA[sip010]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Fri, 02 May 2025 19:51:12 GMT</pubDate>
            <atom:updated>2025-05-02T19:51:12.739Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>With everything that has been built so far with the <a href="https://github.com/nescampos/PoXAgents"><strong>PoXAgents</strong></a> project, we can now optimize it so that it can send any token, and not just <strong>sBTC</strong>, as we saw in a <a href="https://medium.com/@n.campos.rojas/interacting-with-sip-010-tokens-with-stacks-js-2bf91218fd61">previous post</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*0kQHLEdXVgKQyxV-vgBIeA.png" /><figcaption>Sending any fungible token using Stacks.js</figcaption></figure><h3>What was necessary to send any token?</h3><p>Basically, we needed to know all the available tokens, both in the agent’s wallet balance and also information on many more tokens on the Stacks network. Adding them one by one didn’t make sense (it’s neither sustainable nor scalable), but after adding the <a href="https://medium.com/@n.campos.rojas/getting-info-from-velar-protocol-with-ai-052fee5b081c"><strong>Velar</strong></a> and <a href="https://medium.com/@n.campos.rojas/integrating-the-alex-sdk-in-my-ai-agent-f059a702eb15"><strong>Alex</strong></a> protocols, we now have information on many more tokens (and their contract IDs, which is what’s important for sending them).</p><p><a href="https://medium.com/@n.campos.rojas/why-i-built-an-ai-agent-toolkit-to-interact-with-stacks-and-bitcoin-1577a292401c">Why I built an AI agent toolkit to interact with Stacks and Bitcoin</a></p><p>Next, we need to adjust the <a href="https://github.com/nescampos/PoXAgents/blob/main/src/stacks/executeTransactions.ts#L30C23-L30C40"><em>sendFungibleToken</em></a> method to accept any token, using the contract ID:</p><pre>export async function sendFungibleToken(tokenId:string, amount:string, to_address:string) {<br>    // Check if the mnemonic environment variable is set<br>    if (!process.env.WALLET_MNEMONIC) {<br>        throw new Error(<br>        &quot;WALLET_MNEMONIC environment variable is not set. You need to set it to create a wallet client.&quot;<br>        );<br>    }<br>    // Create a wallet from the mnemonic<br>    const wallet = await generateWallet({<br>        secretKey: process.env.WALLET_MNEMONIC,<br>        password: &#39;&#39;,<br>    });<br>    const tokenData = tokenId.split(&quot;.&quot;);<br>    const address = privateKeyToAddress(wallet.accounts[0].stxPrivateKey, &#39;mainnet&#39;);<br>    const decimalResult = await fetchCallReadOnlyFunction({<br>        contractName: tokenData[1],<br>        contractAddress: tokenData[0],<br>        functionName: &quot;get-decimals&quot;,<br>        functionArgs:[],<br>        senderAddress:address,<br>        network:&quot;mainnet&quot;<br>      });<br>    const formattedAmount =  Number(amount) * 10**Number(decimalResult.value.value);<br>    const postConditions = Pc.principal(address)<br>        .willSendEq(formattedAmount)<br>        .ft(tokenId, tokenData[1]);<br><br>    const transaction = await makeContractCall({<br>        contractName: tokenData[1],<br>        contractAddress: tokenData[0],<br>        functionName: &quot;transfer&quot;,<br>        functionArgs:[<br>            Cl.uint(formattedAmount), // amount to transfer<br>            Cl.principal(address), // sender address<br>            Cl.principal(to_address), // recipient address<br>            Cl.none()], // optional memo - passing none<br>        senderKey: wallet.accounts[0].stxPrivateKey,<br>        validateWithAbi: true,<br>        network: &quot;mainnet&quot;,<br>        postConditions: [postConditions],<br>        postConditionMode: PostConditionMode.Deny,<br>      });<br><br>    const tx_result = await broadcastTransaction({ transaction, network:&quot;mainnet&quot; });<br>    return tx_result;<br>}</pre><p><strong>But what’s different about accepting only sBTC?</strong><br>First, since the method receives the full contract ID, we need to split the ID and the name, since the fetchCallReadOnlyFunction and makeContractCall functions in <strong>Stacks.js</strong> require such data as parameters in two different properties:</p><pre>const tokenData = tokenId.split(&quot;.&quot;);<br>const address = privateKeyToAddress(wallet.accounts[0].stxPrivateKey, &#39;mainnet&#39;);<br>const decimalResult = await fetchCallReadOnlyFunction({<br>    contractName: tokenData[1],<br>    contractAddress: tokenData[0],<br>    functionName: &quot;get-decimals&quot;,<br>    functionArgs:[],<br>    senderAddress:address,<br>    network:&quot;mainnet&quot;<br>  });<br>const formattedAmount =  Number(amount) * 10**Number(decimalResult.value.value);<br>const postConditions = Pc.principal(address)<br>    .willSendEq(formattedAmount)<br>    .ft(tokenId, tokenData[1]);<br><br>const transaction = await makeContractCall({<br>    contractName: tokenData[1],<br>    contractAddress: tokenData[0],<br>    functionName: &quot;transfer&quot;,<br>....</pre><p>And then, setting the agent <a href="https://github.com/nescampos/PoXAgents/blob/main/src/constants/prompt.ts"><strong>prompt</strong></a> indicated that it can send any token, and if it needs to know what the full ID of the token is (since the user will only specify <em>sBTC</em>, <em>WELSH</em>, <em>LEO</em>, or any symbol), it uses the protocols functions to get access to all the data (and from there, the agent will do an automatic lookup of the ID concerning the symbol):</p><pre>..<br>- Send any coins and tokens using send_transaction<br>.. <br>6. ALWAYS be concerned about tokens and coins in every action:<br>   - If no token is specified, use the native coin (STX)<br>   - Check if you have the balance to send (in any token or coin)<br>   - To users, show the token name, and to send/make transactions, use the contract id (token id). <br>   - If you need the token id, check the balance of tokens to get the id.</pre><p><strong>And without further ado and extra work, your agent can now send all types of fungible tokens in Stacks (thanks to the SIP010 standard) without having to hardcode the ID of each token, so if the wallet receives a new token in the future, it can immediately use it.</strong></p><p><a href="https://medium.com/@n.campos.rojas/interacting-with-sip-010-tokens-with-stacks-js-2bf91218fd61">Interacting with SIP-010 tokens with Stacks.js</a></p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdffd42fb24c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting info from Velar Protocol with AI]]></title>
            <link>https://medium.com/@n.campos.rojas/getting-info-from-velar-protocol-with-ai-052fee5b081c?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/052fee5b081c</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[velar-protocol]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Fri, 02 May 2025 19:00:41 GMT</pubDate>
            <atom:updated>2025-05-02T19:00:41.777Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In my <a href="https://medium.com/@n.campos.rojas/integrating-the-alex-sdk-in-my-ai-agent-f059a702eb15">previous posts</a>, I’ve explained how to integrate various Stacks protocols into my toolkit to execute actions with AI. This time, I’ll explain how I did it with the <a href="https://velar.com/"><strong>Velar Protocol</strong></a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*8l8ajCfUjc8PCx9KR_NOtA.png" /><figcaption><a href="https://github.com/nescampos/PoXAgents">PoxAgents </a>using Velar Protocol</figcaption></figure><h3>Why another protocol?</h3><p>In a <a href="https://medium.com/@n.campos.rojas/integrating-the-alex-sdk-in-my-ai-agent-f059a702eb15">previous post</a>, I explained how I integrated <a href="https://alexlab.co/"><strong>Alex</strong></a> to query information about available tokens for swapping. So why would I add yet another protocol? (And why would I add as many as necessary?)<br>For at least two important reasons:</p><h4>To give more options to users</h4><p>If I only allow one protocol to interact with, I’m leaving aside other protocols with high liquidity, other tokens, and a large user base. In a world where we’re not just looking for decentralization, but also for more options, limiting it to just one doesn’t provide any added value to users.</p><h4>To do things that could not be done with a single protocol</h4><p>With various protocols, such as decentralized exchanges, in the toolkit, users can do things like arbitrage (buying a token on one platform and selling it on another) to generate income, quote where to buy or sell, and much more.</p><h3>Integrating Velar</h3><p>Now we’re going to use Velar, specifically, through <a href="https://docs.velar.com/velar/developers/velar-api"><strong>its API</strong></a> to query available tokens (name, contract, price, and other data) and available liquidity pools for swaps.</p><p>First, I create a folder and file for the functions we’ll run through the agent, which in turn call the various API endpoints. The file is called <a href="https://github.com/nescampos/PoXAgents/blob/main/src/velar/platformInformation.ts"><em>platformInformation.ts</em></a>, and below I show what I do to obtain the tokens information:</p><pre>import { VELAR_BASE_URL } from &quot;../constants/stackseco&quot;;<br>import axios from &quot;axios&quot;;<br><br><br>export async function getTokensAvailable(symbol?:string) {<br>    if(symbol == undefined || symbol == null || symbol == &quot;&quot;) {<br>        symbol = &quot;all&quot;;<br>    }<br><br>    const targetPath = `${VELAR_BASE_URL}/tokens?symbol=${symbol}`;<br>  <br>      try {<br>          const {data} = await axios.get(<br>              targetPath<br>          );<br>          return data.map((token) =&gt; `Symbol: ${token.symbol}, Name: ${token.name}, Address: ${token.contractAddress}, Price: ${token.price}, Website: ${token.socialLinks.website}`);<br>  <br>      } catch (error) {<br>          throw(error);<br>      };<br>}</pre><p>The above is very simple: you call the endpoint to get all the information for each token. If you only want one token, you specify the symbol to filter it out. Then, it returns a string with all the information for the agent to interpret.</p><p>Now we get the information about the available pools:</p><pre>export async function getPoolsAvailable(token0?:string, token1?:string) {<br><br>  let targetPath = `${VELAR_BASE_URL}/pools`;<br><br>  if(token0 !== undefined &amp;&amp; token1 !== undefined) {<br>    targetPath = `${targetPath}/${token0}/${token1}`;<br>  }<br><br>    try {<br>        const {data} = await axios.get(<br>            targetPath<br>        );<br>        return data.data.map((pool) =&gt; `Symbol: ${pool.symbol}, Token 0: ${pool.token0Symbol}, Token 1: ${pool.token1Symbol}, Total value locked (in USD): ${pool.stats.tvl_usd.value}`);<br><br>    } catch (error) {<br>        throw(error);<br>    };<br>}</pre><p>As in the previous function, we return all the pools or filter them by a pair of tokens that are specified by the user through the agent.</p><h3>Connecting the tools</h3><p>As I explained in <a href="https://medium.com/@n.campos.rojas/registering-tools-to-interact-with-stacks-with-my-agent-f76057f227f7">one of my posts</a>, we now need to create the tools (following the OpenAI framework) so that users can use the functions we’ve created.<br>Here’s the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/getTokenInformation.ts"><em>getTokenInformation.ts</em></a> tool:</p><pre>import { getTokensAvailable } from &quot;../src/velar/platformInformation&quot;;<br>import type { ToolConfig } from &quot;./allTools.js&quot;;<br><br>import type { GetTokenInformationArgs } from &quot;../interface/index.js&quot;;<br><br>/**<br> * Get token information from Velar platform<br> *<br> * This tool takes a single optional parameter, the token symbol<br> * from.<br> */<br>export const getTokenInformationVelarTool: ToolConfig&lt;GetTokenInformationArgs&gt; = {<br>  definition: {<br>    type: &quot;function&quot;,<br>    function: {<br>      name: &quot;get_token_information_velar&quot;,<br>      description: &quot;Get information about tokens available in Velar Protocol&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          token: {<br>            type: &quot;string&quot;,<br>            //pattern: &quot;^0x[a-fA-F0-9]{40}$&quot;,<br>            description: &quot;The symbol of the token to look for&quot;,<br>          },<br>        },<br>        required: [],<br>      },<br>    },<br>  },<br>  handler: async ({ token }) =&gt; {<br>    return await getInformation(token);<br>  },<br>};<br><br>async function getInformation(token?: string) {<br>  const tokens = await getTokensAvailable(token);<br>  return tokens;<br>}</pre><p>And here is the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/getPoolInformationFromVelar.ts"><em>getPoolInformationFromVelar.ts</em></a> tool:</p><pre>import { getPoolsAvailable } from &quot;../src/velar/platformInformation&quot;;<br>import type { ToolConfig } from &quot;./allTools.js&quot;;<br><br>import type { GetPoolInformationArgs } from &quot;../interface/index.js&quot;;<br><br>/**<br> * Get pool information from Velar platform<br> *<br> * This tool takes a single optional parameter, the token symbol<br> * from.<br> */<br>export const getPoolInformationVelarTool: ToolConfig&lt;GetPoolInformationArgs&gt; = {<br>  definition: {<br>    type: &quot;function&quot;,<br>    function: {<br>      name: &quot;get_pool_information_velar&quot;,<br>      description: &quot;Get information about pools available in Velar Protocol&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          token0: {<br>            type: &quot;string&quot;,<br>            //pattern: &quot;^0x[a-fA-F0-9]{40}$&quot;,<br>            description: &quot;The contract Id for the first token in the pool&quot;,<br>          },<br>          token1: {<br>            type: &quot;string&quot;,<br>            //pattern: &quot;^0x[a-fA-F0-9]{40}$&quot;,<br>            description: &quot;The contract Id for the second token in the pool&quot;,<br>          },<br>        },<br>        required: [],<br>      },<br>    },<br>  },<br>  handler: async ({ token0,token1 }) =&gt; {<br>    return await getInformation(token0,token1);<br>  },<br>};<br><br>async function getInformation(token0?: string, token1?: string) {<br>  const tokens = await getPoolsAvailable(token0, token1);<br>  return tokens;<br>}</pre><p>Finally, we register these tools in the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/allTools.ts"><em>allTools.ts</em></a> file to be used when the new agent is created:</p><pre>...<br>/**<br> * Get information about the tokens available in Velar protocol<br> */<br>get_token_information_velar: getTokenInformationVelarTool,<br><br> /**<br> * Get information about the tokens available in Velar protocol<br> */<br>get_pool_information_velar: getPoolInformationVelarTool,<br>...</pre><p>And so, you now have Velar integrated into your broker to view information available for swaps.</p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=052fee5b081c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing multiple instructions with AI in Stacks]]></title>
            <link>https://medium.com/@n.campos.rojas/executing-multiple-instructions-with-ai-in-stacks-c018a847bea7?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/c018a847bea7</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Fri, 02 May 2025 15:54:29 GMT</pubDate>
            <atom:updated>2025-05-02T15:54:29.051Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>After all the construction of my AI agent to interact with the Stacks network, <a href="https://medium.com/@n.campos.rojas/registering-tools-to-interact-with-stacks-with-my-agent-f76057f227f7">including the tools to register with OpenAI</a>, now something important is missing: allowing one or more tools and on-chain actions to be executed with just one instruction from the user, which is what I will do now in a simple way.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*b-2JNfXRTomlnNJn.png" /><figcaption>PoXAgents working</figcaption></figure><h3>Why multiple instructions?</h3><p>So far, to execute some actions, I need to know the contract ID on the network for the token I’m interacting with. For example, if I want to send sBTC, I need to know the full ID, which isn’t very user-friendly, and this is multiplied by each token available in a wallet. Therefore, you have to be careful with the prompt (the detailed instructions on how the agent should behave) so that it knows what and when to execute a specific action or tool.</p><p><a href="https://medium.com/@n.campos.rojas/why-i-built-an-ai-agent-toolkit-to-interact-with-stacks-and-bitcoin-1577a292401c">Why I built an AI agent toolkit to interact with Stacks and Bitcoin</a></p><h3>Creating the assistant</h3><p>First of all, and as I did at the end of <a href="https://medium.com/@n.campos.rojas/registering-tools-to-interact-with-stacks-with-my-agent-f76057f227f7">my previous post</a>, we need to register the assistant with OpenAI along with all the tools so it knows which actions are available to execute on-chain or with <a href="https://medium.com/@n.campos.rojas/using-stacks-js-and-hiro-apis-to-manage-balances-bcb1543a53e3?source=your_stories_page--------------------------------------------">Hiro APIs</a>, for example.<br>Here are the details of the <a href="https://github.com/nescampos/PoXAgents/blob/main/src/openai/createAssistant.ts"><em>createAssistant.ts</em></a> file for creation, using the OpenAI SDK:</p><pre>import OpenAI from &quot;openai&quot;;<br>import type { Assistant } from &quot;openai/resources/beta/assistants&quot;;<br>import { tools } from &quot;../../tools/allTools&quot;;<br>import { assistantPrompt } from &quot;../constants/prompt&quot;;<br><br>/**<br> * Creates a new assistant with the specified model, name, instructions and tools.<br> * @param client The OpenAI client to use to create the assistant.<br> * @returns The newly created assistant.<br> */<br>export async function createAssistant(client: OpenAI): Promise&lt;Assistant&gt; {<br>  // Create the assistant with the specified model, name, instructions and tools.<br><br>  if (!process.env.OPENAI_API_KEY) {<br>      throw new Error(<br>      &quot;OPENAI_API_KEY environment variable is not set. You need to set it to create the assistant.&quot;<br>      );<br>  }<br>  if (!process.env.OPENAI_ASSISTANT_NAME) {<br>      throw new Error(<br>      &quot;OPENAI_ASSISTANT_NAME environment variable is not set. You need to set it to create the assistant.&quot;<br>      );<br>  }<br>  if (!process.env.OPENAI_MODEL) {<br>      throw new Error(<br>      &quot;OPENAI_MODEL environment variable is not set. You need to set it to create the assistant.&quot;<br>      );<br>  }<br><br>  return await client.beta.assistants.create({<br>    // The model to use for the assistant.<br>    model: process.env.OPENAI_MODEL,<br>    // The name of the assistant.<br>    name: process.env.OPENAI_ASSISTANT_NAME,<br>    // The instructions to provide to the assistant.<br>    instructions: assistantPrompt,<br>    // The tools to provide to the assistant.<br>    tools: Object.values(tools).map((tool) =&gt; tool.definition),<br>  });<br>}</pre><p>As you can see, we assigned it a name (to distinguish it in OpenAI), a model (<a href="https://platform.openai.com/docs/models">you can review them all here</a>), the available tools we created, and finally, the prompt, which specifies <strong>everything the agent can do and how it should do it</strong>.</p><h3>Making the prompt</h3><p>In a separate file, I create the agent’s prompt (it could be better parameterized, but for the purposes of this project, it’s working fine so far). These instructions, as a text variable, must detail everything the agent does, including specifying each tool.<br><a href="https://github.com/nescampos/PoXAgents/blob/main/src/constants/prompt.ts"><strong>In this file</strong></a>, you can see the entire prompt, and below, you can see the portion that specifies what each tool does, for clarity and to avoid misinterpretation:</p><pre>export const assistantPrompt = `You are an advanced blockchain AI assistant, operating on the Stacks Network. Your core functionality is built for enabling seamless interaction with blockchain technology. You maintain a professional yet engaging demeanor, focused on executing blockchain operations with precision and clarity.<br><br>Personality Traits:<br>- Precise and Technical: You understand blockchain technology deeply and communicate with technical accuracy<br>- Proactive Execution: You take initiative in executing blockchain operations using sensible defaults<br>- Context-Aware: You maintain awareness of transaction history and contract addresses<br>- Security-Conscious: You handle sensitive operations with appropriate caution<br><br>Core Capabilities:<br><br>READ OPERATIONS:<br>- Retrieve connected wallet address using get_wallet_address<br>- Retrieve the native balance in STX (total, locked, and available) for the wallet using get_balance<br>- Retrieve the balances of tokens for the wallet using get_token_balances<br>- Retrieve the balances of non fungible tokens (NFT) for the wallet using get_nft_balances<br>- Get the last 10 transactions from a wallet using get_last_transactions<br>- Search blocks, transactions, contracts, or accounts by hash/ID and get the information using search_hash<br>- Get the STX supply (total and unlocked) using get_stx_supply<br>- Get information (name, symbol, prices, contract address, and website) about tokens available in Velar Protocol using get_token_information_velar<br>- Get information (tokens and total value locked in USD) about pool available in Velar Protocol using get_pool_information_velar<br>- Get the status of the enrollment in sBTC Incentives for a wallet (if no wallet is specified, use the current address) using get_sbtc_enrollment<br>- Get the current cycle for sBTC rewards using get_sbtc_currentcycle<br>- Get the current/last sBTC reward address for a specific address using get_sbtc_rewardaddress<br>- Get the sBTC rewards for a specific cycle and address using get_sbtc_rewardsbycycleaddress<br>- Get the fee rate in swapping between STX and ALEX in AlexGo protocol using get_feerate_alexgo<br>- Get the available tokens to swap in AlexGo protocol using get_availabletokens_alexgo<br>- Get the price of the tokens (in USD) to swap in AlexGo protocol using get_tokenprices_alexgo<br><br>WRITE OPERATIONS:<br>- Send coins and tokens using send_transaction<br>- Enroll for sBTC incentives and get rewards using enroll_sbtc_incentives<br>- Change the address to receive the sBTC incentives using change_sbtc_rewardaddress<br>- Unenroll/opt-out for sBTC incentives using optout_sbtc_incentives<br></pre><p>As the instructions show, the read and write actions the agent can perform are specified, and the corresponding tool is referenced for each.<br>But up to this point, each action is independent of the other, so if I want to send sBTC, I would have to specify the contract, and that remains the problem. So to solve this, in the same prompt, I begin to specify certain rules for which the agent must be more cautious in its execution, for example,<a href="https://github.com/nescampos/PoXAgents/blob/main/src/constants/prompt.ts#L63"> regarding actions involving any token or currency</a>:</p><pre>...<br>6. ALWAYS be concerned about tokens and coins in every action:<br>   - If no token is specified, use the native coin (STX)<br>   - Check if you have the balance to send (in any token or coin)<br>   - To users, show the token name, and to send/make transactions, use the contract id (token id). <br>   - If you need the token id, check the balance of tokens to get the id.<br>...</pre><p>So, I’m indicating that if the user (you or I) tells the agent “<strong>Send 1 to ST….</strong>”, it will first check if there is a necessary balance (using the <em>get_balance</em> tool indicated in the prompt), and then send <strong>STX</strong> (the network’s native currency) by default.<br>And if sending another token, if the user says “<strong>Send 0.01 sBTC to…</strong>”, it will first check the contract ID for that token (using the <em>get_token_balances</em> tool, which returns the balances and their respective contract IDs and tickers), verify the balance, and then send the token.</p><p>And so, you realize that executing multiple instructions with a single action is a matter of giving the agent clarity about the sequence of steps when appropriate, and the more detail you provide, the more likely it is that the action executed is what the user expected.</p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c018a847bea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Registering tools to interact with Stacks with my agent]]></title>
            <link>https://medium.com/@n.campos.rojas/registering-tools-to-interact-with-stacks-with-my-agent-f76057f227f7?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/f76057f227f7</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 14:29:32 GMT</pubDate>
            <atom:updated>2025-04-30T14:29:32.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In my <a href="https://medium.com/@n.campos.rojas/integrating-the-alex-sdk-in-my-ai-agent-f059a702eb15">previous posts</a>, I explained how I built each method and function to connect the <a href="https://github.com/nescampos/PoXAgents">AI ​​toolkit</a> to the Stacks network. Now, I’ll explain how I connect those methods to the assistant using OpenAI.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*W93wjVKSNG3givKPhFfQVg.png" /><figcaption>Creating a tool for OpenAI</figcaption></figure><h3>Connecting my Stacks functions to OpenAI</h3><p>With the methods created (for checking balances, sending tokens like sBTC, interacting with the Hiro API, and more), we now need to make OpenAI (the platform currently used by my platform) understand the instructions specified by the user and execute the appropriate method. To do this, we’ll use <a href="https://platform.openai.com/docs/assistants/tools/function-calling"><strong>OpenAI’s Assistants tools</strong></a>.</p><p>These tools allow you to do several things, including calling external functions (which is what we’ll be doing), and they have a predefined format for creating them.<br>So first, in the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/allTools.ts"><em>allTools.ts</em></a> file, we create the standard definition for a tool (which will be followed by every tool in the platform):</p><pre>export interface ToolConfig&lt;T = any&gt; {<br>  /**<br>   * The definition of the tool.<br>   */<br>  definition: {<br>    type: &quot;function&quot;;<br>    function: {<br>      name: string;<br>      description: string;<br>      parameters: {<br>        type: &quot;object&quot;;<br>        properties: Record&lt;string, unknown&gt;;<br>        required: string[];<br>      };<br>    };<br>  };<br><br>  /**<br>   * The handler function that will be called when the tool is executed.<br>   */<br>  handler: (args: T) =&gt; Promise&lt;any&gt;;<br>}</pre><p>This definition is standard and contains a name for the tool (which we’ll use later), a description for the agent (and specifies the contexts in which it should be used), and finally, the parameters (required and optional) that should be extracted from the user’s instructions.<br>With all of this, we have a handler specifying the method or function to be called and the extracted parameters.</p><p><a href="https://medium.com/@n.campos.rojas/interacting-with-sip-010-tokens-with-stacks-js-2bf91218fd61">Interacting with SIP-010 tokens with Stacks.js</a></p><p>Next, I’ll register each of the <a href="https://github.com/nescampos/PoXAgents/tree/main/tools">necessary tools</a> that will be used for each method. For this article, we’ll do this by sending STX or any other token, so <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/sendTransaction.ts">we create a new file and register the tool according to the previous definition</a>:</p><pre>import { sendSTX, sendFungibleToken } from &quot;../src/stacks/executeTransactions&quot;;<br>import type { ToolConfig } from &quot;./allTools.js&quot;; // Type definition for tool configurations<br>import type { SendTransactionArgs } from &quot;../interface/index.js&quot;; // Type definition for send transaction arguments<br><br>// Configuration for the send transaction tool<br>export const sendTransactionTool: ToolConfig&lt;SendTransactionArgs&gt; = {<br>  definition: {<br>    type: &quot;function&quot;,<br>    function: {<br>      name: &quot;send_transaction&quot;,<br>      description: &quot;Send a transaction to another address&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          to: {<br>            type: &quot;string&quot;,<br>            description: &quot;The recipient address&quot;,<br>          },<br>          value: {<br>            type: &quot;string&quot;,<br>            description: &quot;The amount of STX to send&quot;,<br>          },<br>          <br>          token: {<br>            type: &quot;string&quot;,<br>            description: &quot;The contract/token Id of the token/coin to send&quot;,<br>            optional: true,<br>          },<br>        },<br>        required: [&quot;to&quot;,&quot;value&quot;],<br>      },<br>    },<br>  },<br>  // Handler function to execute the send transaction tool<br>  handler: async (args) =&gt; {<br>    const result = await sendTransaction(args);<br>    if (!result.success || !result.hash) throw new Error(result.message);<br>    return result.hash;<br>  },<br>};<br><br>// Function to send a transaction<br>async function sendTransaction({<br>  to,<br>  value,<br>  token<br>}: SendTransactionArgs) {<br>  try {<br>    let tx = null;<br>    if(token == undefined || token == &quot;&quot;) {<br>      tx = await sendSTX(value,to);<br>    } else {<br>      tx = await sendFungibleToken(token,value,to);<br>    } <br>    <br>    return {<br>      success: true,<br>      hash: tx.txid,<br>      message: `Transaction sent successfully. Hash: ${tx.txid}`,<br>    };<br>    <br>    <br>  } catch (error) {<br>    // Handling errors and returning an error message<br>    //console.error(error);<br>    return {<br>      success: false,<br>      hash: null,<br>      message: `Failed to send transaction: ${<br>        error instanceof Error ? error.message : &quot;Unknown error&quot;<br>      }`,<br>    };<br>  }<br>}</pre><p>As you can see, the first step is to create the <em>sendTransactionTool</em> property, which follows the tool definition, along with a name and general description. Then, specify all the parameters (recipient, amount, and token) and indicate which ones are required and the options. In this case, the token (which is the token ID) is optional; since it is not specified, the transaction will be in STX.</p><p>While the handler makes a call to a local function in the same file called sendTransaction, which has the logic defining whether to execute the function to send STX or send a specific token, and manages the result to be interpreted by the agent.</p><p>And just like the other tools, this one is ready. Although there’s still one important detail missing: letting the agent know that this tool exists and can be used.</p><h3>Registering the tool</h3><p>Now, as a final step, we need to register the tool so the wizard knows it exists and can interpret the user’s instructions.<br>First, in the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/allTools.ts"><em>allTools.ts</em></a> file, I add to the <strong>tools</strong> the property we just created, specifying the file and the action it executes:</p><pre>import { sendTransactionTool } from &quot;./sendTransaction&quot;;<br>...<br><br>export const tools: Record&lt;string, ToolConfig&gt; = {<br>  ....<br><br>  <br>  /**<br>   * Send a transaction to another address <br>   */<br>   send_transaction: sendTransactionTool,<br>  <br>  ....<br><br>};</pre><p>As you can see, the tool is specified in a key-value format, where the key is the name we specified when creating the tool (name property) and the value is the variable/property from the <em>sendTransaction.ts</em> file.</p><p><strong>You must do this for each new tool you create.</strong></p><p>Finally, the platform will take all the created tools and, when initialized, the assistant will be created, registering all these tools for use. This is done in the createAssistant.ts file:</p><pre>import OpenAI from &quot;openai&quot;;<br>import type { Assistant } from &quot;openai/resources/beta/assistants&quot;;<br>import { tools } from &quot;../../tools/allTools&quot;;<br>import { assistantPrompt } from &quot;../constants/prompt&quot;;<br><br>/**<br> * Creates a new assistant with the specified model, name, instructions and tools.<br> * @param client The OpenAI client to use to create the assistant.<br> * @returns The newly created assistant.<br> */<br>export async function createAssistant(client: OpenAI): Promise&lt;Assistant&gt; {<br>  // Create the assistant with the specified model, name, instructions and tools.<br><br>  ....<br><br>  return await client.beta.assistants.create({<br>    // The model to use for the assistant.<br>    model: process.env.OPENAI_MODEL,<br>    // The name of the assistant.<br>    name: process.env.OPENAI_ASSISTANT_NAME,<br>    // The instructions to provide to the assistant.<br>    instructions: assistantPrompt,<br>    // The tools to provide to the assistant.<br>    tools: Object.values(tools).map((tool) =&gt; tool.definition),<br>  });<br>}</pre><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f76057f227f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Post Conditions in Stacks]]></title>
            <link>https://medium.com/@n.campos.rojas/adding-post-conditions-in-stacks-765bd8450ca1?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/765bd8450ca1</guid>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Tue, 29 Apr 2025 14:08:45 GMT</pubDate>
            <atom:updated>2025-04-29T14:08:45.951Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The Stacks ecosystem is growing every day, supported by both the benefits of the network and the emergence of sBTC, bringing BitcoinFi to a massive scale.<br>But one detail that hasn’t been addressed as much but is key to ensuring the apps we create provide greater security for users is Post Conditions, which I will focus on in this article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*Ke9lbL7Yxjy2io5w.jpg" /><figcaption>Stacks logo</figcaption></figure><h3>The problem of executing on-chain actions with our wallets</h3><p>Each user who interacts on-chain does so through a web application (dApp), which connects to one or more protocols via smart contracts.<br>At first, everything seems fine. You don’t need to understand smart contracts to execute various actions; you have an interface to improve your user experience. However, this also poses a problem: <strong>the smart contract(s) may be malicious or contain errors that cause certain actions to be executed that aren’t what you expected.</strong></p><p>There are many examples of cases, for example, on different networks. For example, you are a user who wants to send a certain amount of a stablecoin to a protocol and obtain yields for saving or lending it. The web application works well, but the smart contract was designed to extract all the money instead of just a user-defined amount, and that could cause problems not only for you (you could lose everything and not know why, because it is not your responsibility to understand the smart contract), but also for the application (because the developer is not the owner of the contract, so although they are the visible face to users, they will be responsible without being the guilty party in the situation).</p><p>While there could be control in the app, it wouldn’t guarantee the security of every on-chain action.</p><p><strong>But </strong><a href="https://www.stacks.co/"><strong>Stacks</strong></a><strong> has already considered that, through Post Conditions.</strong></p><h3>Collaborating with safety through Post Conditions</h3><p>To ensure that user actions executed on-chain are exactly what they want, Stacks implemented the concept of Post Conditions directly on the network.</p><p><a href="https://docs.stacks.co/concepts/transactions/post-conditions"><strong>Post Conditions</strong></a>, as the name suggests, <strong>are conditions that an on-chain transaction must meet for it to execute successfully</strong>. If they don’t, the entire process is aborted. For example, when you send a token (such as <em>sBTC</em>) from your wallet to another wallet, in the transaction with the <em>sBTC</em> contract, the app can set the condition that only the amount you have specified is sent to the <em>sBTC</em> contract address and nothing else. If any other action attempts to occur, such as withdrawing more money from your wallet or something similar, the transaction will not complete correctly.</p><p>Post Conditions are created in the frontend, that is, in the app that will make the network calls and the Smart Contracts, and added to the transaction you want to execute.<br>Now I’ll show a simple example.</p><h4>Example</h4><p>In my <a href="https://github.com/nescampos/PoXAgents"><strong>PoXAgent</strong> project</a>, I added the ability for a user to send any token (SIP010) from their wallet (controlled by the AI ​​agent) to another address in Stacks. But to ensure that only that happens (sending tokens and nothing else), I added a post-condition that specifies that the wallet will send exactly the defined amount of a fungible token (sBTC or any other) and nothing more. Finally, that post-condition is added to the transaction that will be sent to Stacks.</p><p><a href="https://medium.com/@n.campos.rojas/interacting-with-sip-010-tokens-with-stacks-js-2bf91218fd61">Interacting with SIP-010 tokens with Stacks.js</a></p><p>Below is the <a href="https://github.com/nescampos/PoXAgents/blob/main/src/stacks/executeTransactions.ts#L30">complete code</a> for how I use Post Conditions in my project:</p><pre>const tokenData = tokenId.split(&quot;.&quot;);<br>const address = privateKeyToAddress(wallet.accounts[0].stxPrivateKey, &#39;mainnet&#39;);<br>const decimalResult = await fetchCallReadOnlyFunction({<br>    contractName: tokenData[1],<br>    contractAddress: tokenData[0],<br>    functionName: &quot;get-decimals&quot;,<br>    functionArgs:[],<br>    senderAddress:address,<br>    network:&quot;mainnet&quot;<br>  });<br>const formattedAmount =  Number(amount) * 10**Number(decimalResult.value.value);<br>const postConditions = Pc.principal(address)<br>    .willSendEq(formattedAmount)<br>    .ft(tokenId, tokenData[1]);<br><br>const transaction = await makeContractCall({<br>    contractName: tokenData[1],<br>    contractAddress: tokenData[0],<br>    functionName: &quot;transfer&quot;,<br>    functionArgs:[<br>        Cl.uint(formattedAmount), // amount to transfer<br>        Cl.principal(address), // sender address<br>        Cl.principal(to_address), // recipient address<br>        Cl.none()], // optional memo - passing none<br>    senderKey: wallet.accounts[0].stxPrivateKey,<br>    validateWithAbi: true,<br>    network: &quot;mainnet&quot;,<br>    postConditions: [postConditions],<br>    postConditionMode: PostConditionMode.Deny,<br>  });<br><br>const tx_result = await broadcastTransaction({ transaction, network:&quot;mainnet&quot; });<br>return tx_result;</pre><p>Now, breaking down each part, I first define the post condition, specifying that the source wallet (controlled by my agent) will send a certain amount (no more and no less) of a fungible token (specified in the <em>ft</em> method):</p><pre>const postConditions = Pc.principal(address)<br>    .willSendEq(formattedAmount)<br>    .ft(tokenId, tokenData[1]);</pre><p>And then, I add it to the transaction, specifying it in an array (there could be several postconditions depending on what we are doing) and in Deny mode, which indicates that if the condition is not met, the transaction aborts.</p><pre>..<br>postConditions: [postConditions],<br>postConditionMode: PostConditionMode.Deny,<br>});</pre><p>And just like that, I add a little more safety so that my project’s users can send tokens with peace of mind, knowing that only what they specify to the AI ​​agent will be done.</p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765bd8450ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jito in the present and future of the Solana economic value ecosystem]]></title>
            <link>https://medium.com/@n.campos.rojas/jito-in-the-present-and-future-of-the-solana-economic-value-ecosystem-b0251fcfad5a?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0251fcfad5a</guid>
            <category><![CDATA[solana-blockchain]]></category>
            <category><![CDATA[jito]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 16:17:56 GMT</pubDate>
            <atom:updated>2025-04-28T16:17:56.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>Solana’s status now</h3><p>Each year, and especially recently, the growth of the Solana network (both transactions and active wallets) has been considerable and supported by numerous decentralized applications and use cases. That said, we know the network supports thousands of transactions per second to be scalable, but there are times when peak transactions can be too much for a short time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*G7HNnYnyvEdx9e8BjecUGw.png" /><figcaption>Numer of txs in Solana from <a href="https://dune.com/21co/solana-key-metrics">21.co Solana Key Metrics</a></figcaption></figure><p>Imagine you’re on a four-lane highway, going very fast like other vehicles to reach your destination. At some point, you will change to another state/country. Therefore, at the border, there will be a toll booth where you must pay a certain amount, just like everyone else, to access the other side. If many people like you are accessing the highway, you’ll have to wait in line, regardless of whether you have an emergency or not.<br>But there’s a fifth lane, where any vehicle that pays a little more than the standard rate can access this road and have higher priority. And since most won’t want to pay more, this road will be less congested, and you can continue on your way with minimal delay.<br>This example is the same in Solana, where the network is the highway and the fees (<strong>normal and priority</strong>) are the tolls.</p><h3>The “problem” with priority fees</h3><p>In the previous example, the fastest lane requires a higher price to access. This is the same as priority fees in Solana, where transactions with a higher interest in being added to a block at the beginning pay an extra amount, but it’s fixed. That is, if many other transactions are willing to pay that extra, your transaction will be in a “queue” that, while faster than non-priority transactions, won’t necessarily be the fastest in the queue. In other words, the fast lane on the highway will already be moving a little slower because many other vehicles are accessing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*re2cX3PuLYawrSf7Ainhog.png" /><figcaption><a href="https://dune.com/queries/3299816/5526360">Priority fees for one month</a></figcaption></figure><p>So far you might be thinking that it’s okay to go a little slower because you’re still traveling faster than most people, but what if everyone crossing the border (including you) goes to a store that’s selling a new phone model at 90% off and there’s only 100 products in stock, so you want to get there first to make sure you buy at least one, but with the 90% savings more and more people can afford to pay extra to move across the border, so your chances of being in the first 100 people are reduced. In the Solana space, the same thing happens, for example a new <em>memecoin </em>appears, or a new <em>DePIN </em>project, or an <em>arbitrage </em>opportunity between 2 decentralized exchanges (or any opportunity you see where you can get a higher profit) and you want to be one of the first to participate to have better prices, as others are thinking the same as you, all the priority transactions will accumulate and your final benefits will not be as “juicy” as you expected, this is because the fee to be a priority transaction is the same for everyone, regardless of the objective of the transaction.</p><h3>How does Jito tips get in here?</h3><p>Returning to the example, you want to be among the first 100 vehicles to cross the border and arrive at the store to purchase the product, and you want to differentiate yourself from the rest to ensure this. Let’s say there’s now a sixth lane, but it works through an “auction,” where the vehicles willing to pay the most fees will go through first. Since there are several, that fee will increase (the law of supply and demand). Since you have the leeway to pay those fees (you’ll save a lot by having a product at a very high discount), you offer the highest fee of the 300 vehicles by doing the same, so you are selected and will go through first. This final part of the example is what is known in the Solana ecosystem as <strong>Jito tips</strong>.</p><p><strong>Jito tips</strong> to explain it in a simple way, is a technology that provides an incentive mechanism for both users (who want to prioritize their transactions) and nodes in the network (validators and stakers running the <a href="https://www.jito.network/">Jito client</a>), where the former will have the opportunity to have priority for their transactions, and the latter will be able to obtain a greater flow of income by helping these users by placing the transactions at the beginning.</p><p>The difference with priority payments is that the fee value depends on the market and volatility. Therefore, if more users want to be first in line with their transactions, the fee will be higher, and vice versa.<br><strong>Therefore, market volatility doesn’t affect priority fees (but it doesn’t guarantee we’ll be first if there are many like us), but it does affect Jito tips (but we can be first in line if we set a fee that the validators accept).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*gnx8p-myvZqwogdRjCEOqw.png" /><figcaption><a href="https://dune.com/queries/3272756/5525700">Jito Tips between April 2024 and April 2025</a></figcaption></figure><p>And as you can see in the graph above, the impact of the $TRUMP memecoin in January 2025 increased demand for using Jito tips (to be among the first to receive the coin).</p><p>And if that’s not enough, let’s look at the day the $TRUMP coin appeared (January 18th). The daily tip amount increased on that day and the following days (including the change of command on January 20th). Just to put it in perspective, more than 50,000 SOL on the first day (more than US$12 million), which clearly shows that the need that Jito tips addresses allows us to ensure that in large-scale events we can still prioritize our transactions over the rest if we see a valuable opportunity to do so.</p><p>Here you have all access to the chart and info: <a href="https://dune.com/queries/3272756/5525700">https://dune.com/queries/3272756/5525700</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUDw_ptCIZZa2MVt4oDkSA.png" /><figcaption><a href="https://dune.com/queries/3272756/5525700">Jito Tips between April 2024 and April 2025</a></figcaption></figure><h3>Do I need to use Jito tips always?</h3><p>The answer is up to you. It depends on how urgent and important it is to execute your transactions as soon as possible. If it’s a low-priority transaction, a normal fee may be sufficient.<br>In a highly competitive environment, where you’re trading or capturing the best market opportunities and extracting the greatest possible value, Jito tips clearly give you an advantage.<br>Like any user, you should evaluate the benefits you’ll gain from higher fees.</p><h4>So, who should use or is Jito tips recommended?</h4><p>In reality, using Jito tips with slightly higher fees is open to anyone, as I mentioned earlier; it all depends on you. Of course, it’s more popular among professional traders, who focus on finding the best opportunities, such as arbitrage between different decentralized exchanges, buying and selling new coins (memecoins, utility coins, etc.), lending, and much more.</p><p>Another way Jito tips are widely used is through bots, such as snipers, who seek out the best opportunities and want to access them (just like professional traders) before others.</p><p>But whatever the use, my recommendation is that you fully understand how the process works, evaluate the short- and medium-term costs (to know how much you can allocate to fees and tips in total), and be clear about why you want to pay (if it’s to send a little SOL to a family member and it’s not urgent, it’s very likely that a regular fee is more than enough).</p><h3>So, there is a market?</h3><p>Of course, just look at how fees grew on Solana during 2024, where Jito tips were gaining more relevance and contributing to the real economy of the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B9Qsu2lbS6_dOinZ.png" /><figcaption><em>Jito Tips are colored in green. Source: Blockworks.</em></figcaption></figure><p>The main applications that use Jito Tips are:</p><ul><li><strong>Decentralized Exchanges</strong>, like <a href="https://jup.ag/">Jupiter</a>, <a href="https://www.orca.so/">Orca</a>, and <a href="https://raydium.io/swap/">Raydium</a>.</li><li><strong>Telegram bots</strong> (snipers to find and buy new coins).</li><li><strong>Liquidity pools</strong>, such as <a href="https://www.meteora.ag/">Meteora</a>.</li><li><strong>Among others.</strong></li></ul><p><strong>In fact, Meteora currently accounts for (at the time of this article) just over 21% of all Jito tips generated.</strong></p><h3>The opportunity</h3><p>As you can see, both the numbers and the ecosystem itself show that Jito Tips brings and generates more value for both infrastructure providers (validators and stakers) and users (from beginners to professionals) to prioritize their transactions and take advantage of the benefits of Solana in any of their applications.</p><p><strong>What are you waiting for to continue?</strong></p><h3>Links</h3><ul><li><a href="https://www.jito.network/"><strong>Jito main site</strong></a></li><li><a href="https://www.eclipse.xyz/articles/how-jito-works--on-solana-deep-dive"><strong>How Jito Works — A Deep Dive</strong></a>: Understand how Jito is working, including the architecture.</li><li><a href="https://dune.com/jito"><strong>Dune Dashboards for Jito</strong></a>: All information from Jito, including validators, tips, and restaking.</li><li><a href="https://dune.com/queries/4551942"><strong>Total Jito Tips in SOL + USD</strong></a></li><li><a href="https://dune.com/21co/solana-key-metrics"><strong>Solana Key Metrics</strong></a> by 21.co</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0251fcfad5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating the Alex SDK in my AI agent]]></title>
            <link>https://medium.com/@n.campos.rojas/integrating-the-alex-sdk-in-my-ai-agent-f059a702eb15?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/f059a702eb15</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 15:21:01 GMT</pubDate>
            <atom:updated>2025-04-23T15:21:01.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/911/0*cYs5i8xAK_19ktDy" /><figcaption>Integrating the Alex SDK</figcaption></figure><blockquote>In my previous post, I explained how I used <a href="https://medium.com/@n.campos.rojas/using-stacks-js-and-hiro-apis-to-manage-balances-bcb1543a53e3">Stacks.js and the Hiro API to easily manage balances</a>, both native and tokens, through the AI ​​agent.<br>This time, I’ll explain how I used <a href="https://alexlab.co/"><strong>Alex</strong></a> in my toolkit so the agent can retrieve information from its app, such as prices, for example.</blockquote><h3>Installing Alex SDK</h3><p>For my <a href="https://github.com/nescampos/PoXAgents">toolkit</a>, I’m now integrating Alex to take advantage of obtaining information from its DEX platform for exchanging different tokens and reviewing their prices.</p><p>For this, I used npm for it:</p><pre>npm install alex-sdk</pre><h3>Using the SDK</h3><p>Now, I create a file to use the SDK, which I will call <a href="https://github.com/nescampos/PoXAgents/tree/main/src/alexgo"><em>protocolInformation.ts</em></a>, since it will only be responsible for obtaining information from the SDK (no write or swap operations, of course).</p><p>Next, I call the SDK to generate the first function, <a href="https://github.com/nescampos/PoXAgents/blob/main/src/alexgo/protocolInformation.ts#L3"><em>getFeeRateBetweenTokens</em></a>, which will return the fee due for each swap. At the time of this post, the SDK only allows queries for <strong>STX</strong> and <strong>ALEX</strong> (the protocol token).</p><pre>import { AlexSDK, Currency } from &#39;alex-sdk&#39;;<br><br>export async function getFeeRateBetweenTokens() {<br>    const alex = new AlexSDK();<br>    const feeRate = await alex.getFeeRate(Currency.STX, Currency.ALEX);<br>    const feeRate2 = await alex.getFeeRate(Currency.ALEX, Currency.STX);<br><br>    return `The fee rate to swap from STX to ALEX is ${Number(feeRate) / 10**8} STX and from ALEX to STX is ${Number(feeRate2)/10**8} ALEX`;<br>}</pre><p>Other information we can obtain from the SDK is the tokens available for swapping in the protocol, and the USD prices for each token:</p><ul><li><strong>To view the available tokens</strong>:</li></ul><pre>export async function getAvailableTokens() {<br>    const alex = new AlexSDK();<br>    const swappableCurrencies = await alex.fetchSwappableCurrency();<br><br>    const formattedCurrencies = swappableCurrencies.map((token) =&gt; `Name: ${token.name}, Id: ${token.underlyingToken}`);<br><br>    return formattedCurrencies;<br>}</pre><ul><li><strong>To see prices in USD</strong>:</li></ul><pre>export async function getTokenPrices() {<br>    const alex = new AlexSDK();<br>    const prices = await alex.getLatestPrices();<br>    const priceList = Object.entries(prices);<br>    const formattedPrice = priceList.map(([key, price]) =&gt; `The price for ${key} is ${price}`);<br><br>    return formattedPrice;<br>}</pre><p>The answers are always in text, since the agent is ultimately the one who interprets the response and finds the best way to deliver it to the user, based on how the question was asked.</p><h3>Configuring the tools</h3><p>Since this toolkit is designed to work with <strong>OpenAI</strong>, it is necessary to create a tool for each type of query/response that serves as a link between the agent and the action, in this case, to one of the functions created previously.</p><p>In the <a href="https://github.com/nescampos/PoXAgents/tree/main/tools"><strong>tools folder</strong></a>, you can review all the currently created ones (for Alex and all the other Stacks ecosystem apps I’m integrating).<br>Below, I’ll show you the format for using the getAvailableTokens function created above:</p><pre>import { getAvailableTokens } from &quot;../src/alexgo/protocolInformation&quot;;<br>import type { ToolConfig } from &quot;./allTools.js&quot;;<br><br>import type { GetAvailableTokensAlexGoArgs } from &quot;../interface/index.js&quot;;<br><br>/**<br> * Get available tokens from alexgo platform<br> *<br> */<br>export const getAvailableTokensfromAlexgoTool: ToolConfig&lt;GetAvailableTokensAlexGoArgs&gt; = {<br>  definition: {<br>    type: &quot;function&quot;,<br>    function: {<br>      name: &quot;get_availabletokens_alexgo&quot;,<br>      description: &quot;Get the available tokens to swap in AlexGo protocol&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          <br>        },<br>        required: [],<br>      },<br>    },<br>  },<br>  handler: async () =&gt; {<br>    return await getAvailableTokens();<br>  },<br>};</pre><p>As you can see, at the beginning I import the necessary elements: the function to obtain the available tokens, <em>ToolConfig</em>, which is an interface to define the format of each new tool (and thus respect a common structure for all of them), and <em>GetAvailableTokensAlexGoArgs</em>, an interface that defines the parameters this tool should receive (processed through the user’s query and sent to a method).</p><p><em>GetAvailableTokensAlexGoArgs</em> has the following definition:</p><pre>export interface GetAvailableTokensAlexGoArgs {}</pre><p>Indeed, it has nothing inside, because this function has no parameters.</p><p>Next, you must set the tool name and description (to tell OpenAI what this tool does), and then, in the handler, specify what function or action you will execute when the call is successful.<br>The name should be space-free, and name it like any other function you would use. The description should be as clear and straightforward as possible (in case there are other similar tools).</p><h4>Register the tool</h4><p>You already have your tool, just one last detail: registration. For this toolkit, registration means recording that this tool has been created so that when the agent initializes, it will be created along with the others.<br>To do this, record it in the <a href="https://github.com/nescampos/PoXAgents/blob/main/tools/allTools.ts">allTools.ts file</a>, using the tool name you defined earlier. Here’s the example for the created tool:</p><pre>import { getAvailableTokensfromAlexgoTool } from &quot;./getAvailableTokensfromAlexgo&quot;;<br><br>/**<br>  * Get the available tokens to swap in AlexGo protocol<br> */<br>get_availabletokens_alexgo: getAvailableTokensfromAlexgoTool,</pre><h3>Configuring the prompt</h3><p>Finally, you just need to specify in the agent’s prompt that these tools are available, so they know when to use them.<br>Just add a short text describing what it does and the name of the corresponding tool:</p><pre>- Get the fee rate in swapping between STX and ALEX in AlexGo protocol using get_feerate_alexgo<br>- Get the available tokens to swap in AlexGo protocol using get_availabletokens_alexgo<br>- Get the price of the tokens (in USD) to swap in AlexGo protocol using get_tokenprices_alexgo</pre><p>Now just test how it works, first start the agent and then make the query:</p><pre>bun run src\index.ts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0_ylOrq8Aju2dPEP" /><figcaption>Demo of the Alex action in the toolkit</figcaption></figure><p>The image above shows the result of the query. This result may be shortened (given the large number of tokens), and if you want something more precise or detailed, you could simply perform a more specific query (limiting it to tokens with a certain name, for example).</p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f059a702eb15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Stacks.js and Hiro APIs to manage balances]]></title>
            <link>https://medium.com/@n.campos.rojas/using-stacks-js-and-hiro-apis-to-manage-balances-bcb1543a53e3?source=rss-f6dfc08284ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb1543a53e3</guid>
            <category><![CDATA[hiro]]></category>
            <category><![CDATA[stack]]></category>
            <dc:creator><![CDATA[Néstor Nicolás Campos Rojas]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:34:51 GMT</pubDate>
            <atom:updated>2025-04-14T19:34:51.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*916eELQC2pB1tldRfu2iCg.png" /><figcaption>Code to get the balance in STX</figcaption></figure><blockquote>In my <a href="https://medium.com/@n.campos.rojas/using-the-sbtc-rewards-program-smart-contracts-31a359760552">previous post</a>, I explained how to integrate one of the sBTC rewards program smart contracts to register and earn yields.<br>This time, I’ll show how I used the <a href="https://docs.hiro.so/stacks/api">Hiro API</a> and <a href="https://docs.hiro.so/stacks/clarinet-js-sdk">Stacks.js</a> to manage balances.</blockquote><h3>Why did I use both (Hiro API) and Stacks.js instead of just one?</h3><p>The answer is very simple. The <a href="https://docs.hiro.so/stacks/api">Hiro API</a> provides enough information about the balances (fungible and non-fungible) to be able to display them, and then I execute calls to each token’s contract only for the necessary functions so as not to overload the calls.</p><p>So with the <strong>Hiro API </strong>I get all the information about the balances (native in STX, in fungible tokens and non-fungible tokens/NFT), while with Stacks.js for each balance obtained from each fungible token, I make calls to the get-decimals functions (to then calculate the balance to show to the user) and get-symbol (so that the agent can then display it in the best possible way).</p><h3>Getting the balances</h3><h4>Native balance</h4><p>For this case, I separated the native balance from the rest of the tokens since I not only want to know how much <strong>STX</strong> a particular address has but also how much is locked (to get <strong>BTC</strong> in staking) and how much is available to send or pay fees. So, to do this, I use the endpoint “<a href="https://api.hiro.so/extended/v1/address/$%7Baddress%7D/stx">https://api.hiro.so/extended/v1/address/${address}/stx</a>&quot;, where <em>$address</em> is the address to query (which the agent can fill in with the wallet it manages, or the user can enter any other address).</p><p>Here is the code for the method:</p><pre>/**<br> * Get the native balance from an address<br> *<br> *<br> * @returns The STX balance<br> */<br> export async function getNativeBalanceFromAddress(address:string) {<br><br>  let header = undefined;<br>  if (process.env.HIRO_API_KEY) {<br>    header = {<br>        headers: {<br>            &#39;X-API-Key&#39;: process.env.HIRO_API_KEY<br>        }<br>    };<br>  }<br><br>  const targetPath = `https://api.hiro.so/extended/v1/address/${address}/stx`;<br><br>    try {<br>        const {data} = await axios.get(<br>            targetPath,header<br>        );<br>        const totalBalance = Number(data.balance) / 10**6;<br>        const lockedBalance = Number(data.locked) / 10**6;<br>        const availableBalance = totalBalance - lockedBalance;<br>        // Return the balance for the account<br>        return `Total: ${totalBalance}, Locked: ${lockedBalance}, Available: ${availableBalance}`<br><br>    } catch (error) {<br>        throw(error);<br>    };<br>}</pre><p>As you can see, it checked if a key for Hiro’s API is in the environment file (at the time of this post, Hiro announced it will deprecate the option to make API calls without a key) and then queried the corresponding endpoint. This endpoint returns both the wallet total and the amount locked, so to get the available amount, I just need to perform a subtraction.</p><p>And as you can see, since I’m only working with STX, I know the exact number of decimal places, so the calculation to print it in a better format is easier.</p><h4>Token balances</h4><p>To get the balances of other tokens (<strong>SIP010</strong>), the process is similar, but I added two extra steps: getting the decimals and getting the symbol. The Hiro API provides a lot of detail, including the total balance per token and the contract address associated with the token, but not the decimals or the symbol, so with the token’s address ID and Stacks.js, I call the respective functions to get that information, which is important to better display the data to the user (and also to send tokens, since the agent verifies that the balance is sufficient for that).</p><p>Here is the code for the method:</p><pre>/**<br> * Get the token balances from an address<br> *<br> *<br> * @returns The token balances<br> */<br> export async function getTokenBalancesFromAddress(address:string) {<br><br>  let header = undefined;<br>  if (process.env.HIRO_API_KEY) {<br>    header = {<br>        headers: {<br>            &#39;X-API-Key&#39;: process.env.HIRO_API_KEY<br>        }<br>    };<br>  }<br><br>  const targetPath = `https://api.hiro.so/extended/v1/address/${address}/balances`;<br><br>    try {<br>        const {data} = await axios.get(<br>            targetPath, header<br>        );<br>        const fungibleTokens = data.fungible_tokens;<br>        let balances = &quot;&quot;;<br>        // Return the balance for the account<br>        for (const tokenName in fungibleTokens) {<br>          const token = fungibleTokens[tokenName];<br>          const tokenComponents = tokenName.split(&quot;::&quot;);<br>          const contract = tokenComponents[0].split(&quot;.&quot;);<br>          const contractId = contract[0];<br>          const contractName = contract[1];<br>          const decimalResult = await fetchCallReadOnlyFunction({<br>            contractName: contractName,<br>            contractAddress: contractId,<br>            functionName: &quot;get-decimals&quot;,<br>            functionArgs:[],<br>            senderAddress:address,<br>            network:&quot;mainnet&quot;<br>          });<br>          const symbolResult = await fetchCallReadOnlyFunction({<br>            contractName: contractName,<br>            contractAddress: contractId,<br>            functionName: &quot;get-symbol&quot;,<br>            functionArgs:[],<br>            senderAddress:address,<br>            network:&quot;mainnet&quot;<br>          });<br>          const symbol = symbolResult.value.value;<br>          const formattedBalance =  Number(token.balance) / 10**Number(decimalResult.value.value);<br>          //console.log(&quot;Decimals: &quot;+ decimalsToken);<br>          balances = balances.concat(`Token: ${symbol}, Balance: ${formattedBalance}, Token Id: ${tokenComponents[0]}\n`);<br>          <br>        }<br>        return balances;<br><br>    } catch (error) {<br>        throw(error);<br>    };<br>}</pre><p>As you can see in the code above, I use the number of decimal places I extract from the token contract to calculate the balance visible to the user, and I send all the balances as text, so that the agent (and the framework behind it) generates a formatted response after interpreting the question for an exact answer.</p><h4>NFT balance</h4><p>Like the method for fungible tokens, for <strong>NFTs</strong> (non-fungible) I use the same endpoint from the Hiro API, only in the response I select another section (<em>non_fungible_tokens</em>) and print the name and the amount (I omit the address since I don’t see it necessary for the user yet, since at the time of this post nothing else can be done with NFTs).</p><p>Here is the code:</p><pre>/**<br> * Get the NFT balances from an address<br> *<br> *<br> * @returns The balances<br> */<br> export async function getNFTBalancesFromAddress(address:string) {<br><br>  let header = undefined;<br>  if (process.env.HIRO_API_KEY) {<br>    header = {<br>        headers: {<br>            &#39;X-API-Key&#39;: process.env.HIRO_API_KEY<br>        }<br>    };<br>  }<br><br>  const targetPath = `https://api.hiro.so/extended/v1/address/${address}/balances`;<br><br>    try {<br>        const {data} = await axios.get(<br>            targetPath, header<br>        );<br>        const nftTokens = data.non_fungible_tokens;<br>        let balances = &quot;&quot;;<br>        // Return the balance for the account<br>        for (const tokenName in nftTokens) {<br>          if (nftTokens.hasOwnProperty(tokenName)) {<br>            const token = nftTokens[tokenName];<br>            balances = balances.concat(`Token: ${tokenName}, Quantity: ${token.count}\n`);<br>          }<br>        }<br>        return balances;<br><br>    } catch (error) {<br>        throw(error);<br>    };<br>}</pre><p>All methods and functions are available on the <a href="https://github.com/nescampos/PoXAgents">project’s GitHub</a>, specifically in the <a href="https://github.com/nescampos/PoXAgents/blob/main/src/stacks/getWalletInfo.ts">getWalletInfo file</a>.</p><h3>About me</h3><p>I’m Néstor Campos, a <a href="https://github.com/nescampos">builder</a> and <a href="https://www.linkedin.com/in/nescampos/">founder</a> with over 15 years of experience (5 in Blockchain and Web3), working across different products and industries to solve major problems through these technologies.<br>Now, I’m also actively joining the <strong>Stacks</strong> ecosystem and contributing to the future of BitcoinFi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb1543a53e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>