<?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 Javier Zafra on Medium]]></title>
        <description><![CDATA[Stories by Javier Zafra on Medium]]></description>
        <link>https://medium.com/@jzafradelpozo?source=rss-384a00d8b3b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fsbap9wFm2fj7EZrM-eTqQ.jpeg</url>
            <title>Stories by Javier Zafra on Medium</title>
            <link>https://medium.com/@jzafradelpozo?source=rss-384a00d8b3b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:31:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jzafradelpozo/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[Manual de cripto para cansinos: todo lo que necesitas saber antes de perder tu dinero (o no)]]></title>
            <link>https://medium.com/@jzafradelpozo/manual-de-cripto-para-cansinos-todo-lo-que-necesitas-saber-antes-de-perder-tu-dinero-o-no-e8fb7ef79e00?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8fb7ef79e00</guid>
            <category><![CDATA[criptomonedas]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Sat, 25 Apr 2026 13:04:24 GMT</pubDate>
            <atom:updated>2026-04-25T13:04:24.101Z</atom:updated>
            <content:encoded><![CDATA[<p>Así que quieres meterte en esto del cripto. Perfecto. Bienvenido al club de los que no entienden del todo qué es, pero tienen claro que no quieren quedarse fuera. No te preocupes, todos empezamos igual.</p><p>Este artículo <strong>no es consejo financiero</strong>. Es un mapa para que no te pierdas tanto. Empecemos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExFrxh8Hw6dPapblTRl58g.png" /></figure><h3>1. Lo primero: no vayas a ningún sitio sin saber esto</h3><p>Antes de comprar nada, de registrarte en ningún exchange ni de mandar ni un céntimo, necesitas entender tres bloques básicos.</p><h4>Criptografía básica (sin ponerse técnico)</h4><p>La criptografía es la magia matemática que hace que todo esto funcione. En esencia: las transacciones en blockchain están protegidas por firmas digitales que solo tú puedes generar con tu clave privada. Si alguien tiene tu clave privada, tiene tu cripto. Sin matices. Sin atención al cliente. Sin recuperación de contraseña. <strong>Adiós dinero.</strong></p><h4>Bitcoin, Ethereum, tokens y todo ese zoo</h4><ul><li><strong>Bitcoin (BTC):</strong> El original. El oro digital, dicen. Funciona como dinero descentralizado sin un banco detrás.</li><li><strong>Ethereum (ETH)</strong>: Una blockchain programable. No solo envía dinero, ejecuta código (los llamados <em>smart contracts</em>).</li><li><strong>Tokens ERC:</strong> Son activos creados encima de Ethereum. Algunos valen algo. Muchos no valen nada. Distinguirlos es parte del juego.</li><li><strong>GAS:</strong> No es gasolina, aunque se parece. Es la comisión que pagas por hacer cualquier operación en Ethereum. Sí, incluso por mover tus propios fondos.</li><li><strong>Txns (transacciones):</strong> Cada movimiento que haces queda grabado para siempre en la blockchain. Todo el mundo puede verlo. Para siempre. Sin borrador.</li><li><strong>Addresses (direcciones):</strong> Algo así como tu número de cuenta, pero público y sin banco. Una cadena de letras y números que es la dirección donde recibes cripto.</li></ul><h4>DeFi, seguridad y fiscalidad: el triángulo que mucha gente ignora</h4><ul><li><strong>DeFi</strong> (Finanzas Descentralizadas) es el ecosistema de servicios financieros — préstamos, intercambios, inversión — sin intermediarios. Suena genial. Y puede serlo. Pero también es el lugar donde más gente pierde dinero por no saber lo que hace.</li><li><strong>Seguridad</strong>: En cripto no hay seguro de depósito. No hay Banco de España que te proteja. Si haces clic donde no debes, si conectas tu wallet a una web maliciosa, o si guardas tu frase semilla en un fichero de texto en el escritorio… lo pierdes todo. Sin apelación.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*RLcVTtT1LoV-S_qJk6ifJg.png" /></figure><ul><li><strong>Fiscalidad</strong>: En España, Hacienda quiere su parte. Las ganancias con criptomonedas tributan como ganancia patrimonial en el IRPF. Ignorar esto no lo hace desaparecer. Muchos se han llevado sorpresas muy desagradables en la declaración de la renta. Infórmate bien o consulta a un asesor fiscal.</li></ul><blockquote>⚠️ <strong>Advertencia real:</strong> El mercado cripto es extremadamente volátil. Es perfectamente posible ver cómo tu inversión pierde el 50% de su valor en cuestión de días. Invierte solo lo que estés dispuesto a perder por completo.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*WOh9-bn6zwtETWk56uj85Q.png" /></figure><h3>2. ¿Eres de CEX o de DEX? (O: ¿quieres que alguien te cuide o prefieres volar solo?)</h3><p>Esta es una de las primeras decisiones que vas a tomar y define bastante tu perfil.</p><p>- <strong>CEX (Exchange Centralizado):</strong> Plataformas como Coinbase, Kraken o Binance. Funcionan como un banco cripto. Te registras, haces KYC (verificación de identidad), y ellos custodian tus fondos. Fácil de usar, pero <strong>tus claves no son tuyas</strong>. Si la plataforma quiebra, es hackeada, o te congela la cuenta… problema.</p><p>- <strong>DEX (Exchange Descentralizado):</strong> Plataformas como Uniswap. Intercambias directamente desde tu wallet, sin intermediarios, sin registro, sin KYC. Más libertad, más responsabilidad.</p><h4>El KYC y la libertad financiera: el debate eterno</h4><p><strong>KYC</strong> significa <strong><em>Know Your Customer</em></strong> (Conoce a tu cliente). Es el proceso por el que te piden el DNI, una selfie y a veces tu historial de vida completo antes de dejarte operar.</p><p>En un CEX es obligatorio. En un DEX, no existe.</p><p>Aquí hay un debate filosófico genuino: la promesa original del cripto era la libertad financiera, transacciones sin que nadie te pida permiso. El KYC va exactamente en sentido contrario. Pero también es la forma en que los exchanges cumplen con la regulación y evitan que la plataforma sea un mercadillo de actividades ilegales.</p><p>Tú decides con qué nivel de comodidad y qué nivel de control operas. No hay respuesta correcta, pero sé consciente de los pros y contras de cada opción.</p><h3>3. DeFi y smart contracts: el corazón del asunto</h3><p>Un <strong>smart contract</strong> es un programa que vive en la blockchain y se ejecuta automáticamente cuando se cumplen ciertas condiciones. Sin abogados, sin intermediarios, sin confianza en terceros… en teoría.</p><p>El problema: si el smart contract tiene un bug, o fue diseñado con malas intenciones, el código se ejecuta igual. No hay nadie a quien reclamarle. Han desaparecido cientos de millones de dólares en exploits de smart contracts. No es ficción.</p><p><strong>DeFi</strong> construye servicios financieros enteros sobre estos contratos: puedes prestar tus cripto y ganar intereses, pedir prestado usando cripto como garantía, o participar en pools de liquidez. Las rentabilidades pueden parecer fantásticas. Y a veces lo son. Y a veces el proyecto era una estafa desde el principio (<em>rug pull</em>: los creadores se llevan todo y desaparecen).</p><blockquote>⚠️ <strong>Regla de oro:</strong> Si algo promete un 300% de APY, pregúntate de dónde viene ese rendimiento. Si no encuentras respuesta clara, no metas dinero.</blockquote><h3>4. Wallets: mis claves, mi cripto</h3><p>Una <strong>wallet</strong> (cartera) no guarda tus cripto. Guarda tus claves privadas, que te dan acceso a tus activos en la blockchain. Hay dos grandes categorías:</p><h4>Software wallets</h4><p>Aplicaciones en tu móvil o navegador (Rabby, MetaMask…). Cómodas y gratuitas. El problema: están conectadas a internet, lo que las hace vulnerables a malware, phishing y a que te equivoques de clic en el momento menos oportuno.</p><h4>Hardware wallets</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*efm-nizqEudFVn_QaK54pA.png" /></figure><p>Dispositivos físicos (Ledger, Trezor…) que guardan tus claves fuera de internet. Para firmar una transacción, necesitas el dispositivo físico. Mucho más seguras para guardar cantidades relevantes. Cuestan entre 50 y 150€ y son la mejor inversión en seguridad que puedes hacer si vas en serio.</p><h4>Portfolio trackers</h4><p>Herramientas (como CoinStats o DeBank) que agregan todas tus posiciones en un solo sitio. Muy útiles para no perderte cuando tienes activos en varias chains y wallets. Ojo con las que piden demasiados permisos.</p><h3>5. Plan para empezar… sin pegar un petardazo en el intento</h3><p>Aquí va una hoja de ruta sensata para alguien que empieza desde cero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*lbhY53dk8W1gTJRxzNeUQg.png" /></figure><h4>Paso 1: Compra una Hardware Wallet</h4><p>Sí, antes de comprar tu primer bitcoin. La recomendación más extendida es <strong>Ledger</strong> (aunque Trezor también es una opción sólida). Cómprala siempre en la web oficial del fabricante, nunca de segunda mano ni en Amazon a un vendedor desconocido. Los dispositivos manipulados existen.</p><h4>Paso 2: Inicialízala y crea cuentas de BTC y ETH</h4><p>Cuando la configuras por primera vez, te genera una <strong>frase semilla</strong> (12 o 24 palabras). Esta frase ES tu cripto. Quien la tenga, tiene acceso a todo. Escríbela en papel (sí, en papel), guárdala en un lugar seguro, y no la fotografíes, no la escribas en el móvil, no la mandes por WhatsApp. Nunca.</p><h4>Paso 3: Aprende a identificar tus wallets</h4><p>Cada cuenta tiene una dirección pública. Es lo que le das a alguien para que te envíe cripto. Puedes ver el historial de cualquier dirección pública en exploradores como Etherscan (para Ethereum) o Blockchain.com (para Bitcoin).</p><p>Un detalle curioso del ecosistema Ethereum: puedes registrar un nombre legible para tu dirección mediante <strong>ENS</strong> (Ethereum Name Service). En vez de `0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE`, puedes tener algo como `criptocansino.eth`. Mucho más manejable.</p><h4>Paso 4: Fondea tu wallet (con cabeza)</h4><p>Aquí llega la pregunta del millón: ¿cómo conviertes euros en cripto?</p><p><strong>Si quieres pasar por el aro (KYC):</strong></p><ul><li>Regístrate en un CEX (<a href="https://www.kraken.com/es-es/">Kraken</a>, <a href="https://www.coinbase.com/es-es">Coinbase</a> o <a href="https://www.binance.com/es">Binance</a> son los más usados en España).</li><li>Completa el KYC con tu documentación.</li><li>Compra BTC o ETH (con tarjeta de crédito, PayPal… u otras opciones disponibles) y retíralos a tu hardware wallet.</li></ul><p><strong>Si prefieres más anonimato:</strong></p><ul><li>Tarjetas prepago de prepago de criptomonedas.</li><li>Pago con tarjeta en plataformas que no exigen KYC para pequeñas cantidades.</li><li>Saldos de Google Play u otras plataformas que se pueden convertir.</li></ul><blockquote>⚠️ <strong>Importante:</strong> Aunque en algunos métodos no haya KYC, en España sigues obligado a declarar tus ganancias en cripto a Hacienda. El anonimato en la compra no te exime de tus obligaciones fiscales.</blockquote><p><strong>Una cosa crítica que mucha gente olvida:</strong> Necesitas ETH para pagar el GAS de cualquier operación en la red Ethereum. Si tienes tokens ERC pero no tienes ETH, no puedes moverlos. Guarda siempre algo de ETH en tu wallet para las comisiones.</p><h4>Paso 5: Tu primer swap (bienvenido a DeFi)</h4><p>Un <strong>swap</strong> es intercambiar una criptomoneda por otra directamente desde tu wallet, sin pasar por un exchange centralizado. La plataforma más usada es <strong>Uniswap</strong>.</p><p>El ejemplo clásico para empezar: <strong>swap de ETH por WBTC</strong> (Wrapped Bitcoin, que es Bitcoin representado como token ERC en la red Ethereum). Así tienes exposición a Bitcoin usando la infraestructura de Ethereum.</p><p>El proceso básico:<br>1. Conecta tu Ledger a MetaMask.<br>2. Entra en Uniswap.<br>3. Selecciona ETH → WBTC, introduce la cantidad.<br>4. Revisa el slippage y las comisiones.<br>5. Confirma en tu Ledger.</p><p>Hecho. Has hecho tu primer swap. Ya eres oficialmente un criptocansino.</p><h4>Paso 6: ¿Y ahora qué? Estrategias según tu perfil</h4><ul><li>A corto plazo: <em>trading</em><br>El trading a corto plazo es para personas con mucha experiencia, mucho tiempo, y estómago de acero. Las estadísticas son brutales: la inmensa mayoría de los traders minoristas pierde dinero frente a los algoritmos profesionales. No empieces por aquí.</li><li>A medio plazo: <em>altcoins</em><br>Comprar altcoins (criptomonedas alternativas a BTC y ETH) baratas cuando el mercado está bajo, y venderlas cuando suben. Suena sencillo. No lo es. Muchas altcoins que suben mucho también bajan mucho. Y algunas simplemente desaparecen. Requiere investigación seria y tolerancia al riesgo elevada.</li><li>A largo plazo: <em>hold, staking y préstamos</em><br>- <strong>Hold BTC:</strong> La estrategia más simple y la que históricamente ha funcionado mejor para la mayoría. Compras, guardas en tu hardware wallet, y no miras el precio todos los días (tu salud mental lo agradecerá).<br>- <strong>Stake ETH:</strong> Participar en la validación de la red Ethereum a cambio de recompensas. Puedes hacerlo con plataformas de liquid staking como Lido o Rocket Pool sin necesitar los 32 ETH del staking nativo.<br>- <strong>Prestar tus criptoactivos:</strong> Plataformas como Aave te permiten prestar tus cripto y ganar intereses. Los rendimientos varían. Los riesgos de smart contract existen. Estudia bien antes de entrar.</li><li>Cómo estar al día: suscribirse a newletters de cripto, o seguir a generadores de contenido cripto en redes sociales, son formas de estar al día. Tienes sitios interesantes en internet como: <a href="https://www.coingecko.com/es">coingecko</a>, <a href="https://coinmarketcap.com/">coinMarketCap</a>, o <a href="https://cryptobubbles.net/">criptoBubbles</a>.</li></ul><h3>6. Glosario para el criptocansino</h3><p>Porque si no entiendes la jerga, te pierdes la mitad de las conversaciones (y el 100% de las estafas).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*JoGjf_zjNG6t1kP8h6hVNA.png" /></figure><p><strong>HODL: </strong>“Hold” mal escrito en un foro. Estrategia de aguantar sin vender pase lo que pase. <br><strong>FOMO:</strong> <em>Fear Of Missing Out</em>. El miedo a perderse una subida. La causa número uno de malas decisiones. <br><strong>FUD:</strong> <em>Fear, Uncertainty, Doubt</em>. Noticias negativas (a veces falsas) que hacen bajar el precio.<br><strong>Rug pull: E</strong>stafa en la que los creadores de un proyecto se llevan los fondos y desaparecen.<br><strong>Whale:</strong> Alguien con tantísimo cripto que sus movimientos mueven el mercado.<br><strong>Gas:</strong> Comisión que se paga en ETH por ejecutar transacciones en la red Ethereum.<br><strong>Seed phrase:</strong> Las 12–24 palabras que son la llave maestra de tu wallet. Jamás las compartas.<br><strong>Slippage:</strong> La diferencia entre el precio que esperas y el que obtienes al hacer un swap.<br><strong>APY:</strong> <em>Annual Percentage Yield</em>. Rendimiento anual. Si parece demasiado bueno, desconfía.<br><strong>KYC:</strong> <em>Know Your Customer</em>. Proceso de verificación de identidad.<br><strong>ENS: </strong><em>Ethereum Name Service</em>. Sistema de nombres legibles para direcciones Ethereum. Si lo usas, ponte un alias y no un identificador personal como DNI, nombre o apellidos.<br><strong>Layer 2 (L2): R</strong>edes construidas sobre Ethereum para reducir comisiones y aumentar velocidad (Arbitrum, Optimism…).<br><strong>DApp:</strong> Aplicación descentralizada que corre sobre una blockchain.<br><strong>Stablecoin:</strong> Token con valor estable, normalmente 1:1 con el dólar (USDT, USDC, DAI).<br><strong>Altcoin:</strong> Cualquier criptomoneda que no sea Bitcoin.</p><p>— -</p><h3>Resumen: lo que debes llevarte de este artículo</h3><p>1. <strong>Aprende antes de invertir.</strong> El conocimiento es la mejor protección contra las estafas.<br>2. <strong>Invierte solo lo que puedas permitirte perder.</strong> Sin exageración: es posible perderlo todo.<br>3. <strong>Custodia propia = Hardware Wallet.</strong> Si tus claves no son tuyas, tus cripto no son tuyas.<br>4. <strong>La fiscalidad existe.</strong> Hacienda no está en DeFi, pero te encontrará igualmente.<br>5. <strong>El largo plazo bate al trading especulativo</strong> para la inmensa mayoría de los mortales.<br>6. <strong>Si algo promete rendimientos imposibles, es una trampa.</strong></p><p>El mundo cripto puede ser genuinamente interesante y ofrecer oportunidades reales. También es un ecosistema lleno de riesgos, estafas y volatilidad extrema. Infórmate, empieza pequeño, y nunca dejes de ser escéptico.</p><p>Bienvenido al ecosistema, criptocansino. 🎉</p><p><em>✦ Artículo generado con IA a partir de un guión original en español. La información contenida tiene carácter educativo y no constituye asesoramiento financiero ni fiscal. DYOR.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8fb7ef79e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Realizar un airdrop de token ERC20 con Vottun APIS y VottumERC20API.NET]]></title>
            <link>https://medium.com/@jzafradelpozo/realizar-un-airdrop-de-token-erc20-con-vottun-apis-y-vottumerc20api-net-457fb7b30a3d?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/457fb7b30a3d</guid>
            <category><![CDATA[airdrop]]></category>
            <category><![CDATA[vottun]]></category>
            <category><![CDATA[erc20]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 12:28:12 GMT</pubDate>
            <atom:updated>2024-05-01T18:56:57.081Z</atom:updated>
            <content:encoded><![CDATA[<p>Las APIs de Vottun permiten a desarrolladores con conocimientos de programación web2 realizar una transición sin problemas a web3.0, sin necesidad de conocer en profundidad la blockchain y sus conceptos asociados (carteras, transacciones), ni tener que aprender nuevos lenguajes de programación de contratos inteligentes como Solidity.</p><p>Si eres un programador con conocimientos de .NET, puedes integrarte fácilmente con las APIS ERC20 de Vottun con un par de líneas de código. Es tan facil como añadir el paquete VottunERC20API.NET a tu proyecto y empezar a utilizar el cliente API.</p><p>En este artículo implementaremos un aidrop de un token ERC20 a un listado de direcciones, contenidas en un archivo de hoja de cálculo Excel.</p><h3>Requisitos previos</h3><ul><li>conocimientos básicos de programación en C#</li><li>Disponer de una cuenta gratuita de Vottun APIs, que puedes obtener registrándote en <a href="https://app.vottun.io/">https://app.vottun.io/</a>.</li><li>Necesitarás conocer tu APIKey y tu ApplicationID (AuthorizationKey). Puedes obtenerlos consultando aquí: <a href="https://docs.vottun.io/start/get-your-api-key">https://docs.vottun.io/start/get-your-api-key</a></li><li>Disponer de algo de MATIC testnet en la red de pruebas Amoy de Polygon. Tambien puede realizarse el proceso en cualquier otra red, aunque en este tutorial se ha usado la testnet Amoy de Polygon (network 80002).</li><li>Visual Studio Community Edition o tu editor .NET favorito</li></ul><h3>Creando el proyecto .NET y agregando las dependencias:</h3><ul><li>comienza creando un nuevo projecto de consola para NET 8, y añade las siguientes dependencias: ExcelLibrary, and VottunERC20API.NET:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*8HaGw2XvMZ1uzvH4Cc4WZQ.png" /></figure><ul><li><strong>ExcelLibrary </strong>nos permitirá abrir y recorrer el fichero excel que contiene el listado de direcciones para realizar el airdrop.</li><li><strong>VottunERC20API.NET </strong>es un paquete nuget implementado por la Comunidad de Vottun, que proporciona un sencillo cliente para usar las APIS ERC20 de Vottun desde programas .NET.</li></ul><h3>Instanciando el cliente para invocar las APIS de Vottun</h3><p>El siguiente código instancia el cliente para poder realizar llamadas a las APIs de Vottun. Debes cambiar los valores de <em>apiKey </em>y <em>applicationID</em> por los correspondientes a tu suscripción de Vottun API.</p><pre>using ExcelLibrary.SpreadSheet;<br>using VottumERC20API.NET;<br><br>//set your api and authorization key<br>var apiKey = &quot;your API key&quot;;<br>var applicationID= &quot;your application ID&quot;;<br><br>//instance a client by calling the provided factory<br>var vottunAPIForNETClient = VottunApiClientFactory.<br>                                Create(apiKey, applicationID);</pre><h3>Creando un nuevo token ERC20 que usaremos para el airdrop</h3><p>A continuación, el siguiente código realiza una llamada al metodo <strong><em>Deploy() </em></strong>del API para crear un nuevo token ERC20, con los siguientes atributos (puedes cambiarlos a voluntad)</p><ul><li>nombre: Vottun airdropped token</li><li>símbolo: VTNFREE1</li><li>alias: Vottun airdropped token ERC20 test1</li><li>cantidad de tokens disponibles: 21000000</li><li>red de despliegue: 80002 (Amoy Polygon testnet )</li></ul><pre><br>//1. Deploy new ERC20 token<br>var deployRequest = new DeployRequest<br>{<br>    name = &quot;Vottun airdropped Token&quot;,<br>    symbol = &quot;VTNFREE1&quot;,<br>    alias = &quot;Vottun airdropped token ERC20 test1&quot;,<br>    initialSupply = 21000000,<br>    network = 80002<br>};<br><br>var deployResponse = await vottunAPIForNETClient.DeployAsync(deployRequest, CancellationToken.None);<br>Console.WriteLine($&quot;Deployed ContractAddress: {deployResponse.contractAddress}&quot;);<br>var ERC20 = deployResponse.contractAddress;<br></pre><h3>Transferencia de tokens a cada direccion contenida en el excel</h3><p>Por último, abrimos y recorremos las direcciones contenidas en la excel, utilizando las funciones de utilidad que nos proporcionar el paquete nuget <em>ExcelLibrary</em>.</p><p>Sustituye en valor de la variable ruta por la ruta donde tengas el fichero excel con la lista de direcciones. Deben estar en la primera columna, como en este ejemplo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ps-ShrpfJWaoUyBFQj-x4A.png" /></figure><p>Para cada dirección, realizamos una llamada al método <strong><em>Transfer()</em></strong> a través del cliente. El airdrop está parametrizado como transferencias de 100 unidades para cada dirección; es importante puntualizar que 1 token = 1*10¹⁸, debido al uso de 18 decimales por defecto de los tokens ERC20. Por lo tanto, la cantidad que estamos transferiendo es de 0.0000000000000001 tokens, que nos vale para este tutorial.</p><ul><li>cantidad: 100 = 0.0000000000000001 tokens</li></ul><pre>//2. Open excel file and iterate every row<br>string ruta = @&quot;C:\Temp\addresslist.xls&quot;;<br>Workbook book = Workbook.Load(ruta);<br>var sheet = book.Worksheets[0];<br><br>for (int rowIndex = sheet.Cells.FirstRowIndex;<br>       rowIndex &lt;= sheet.Cells.LastRowIndex;<br>       rowIndex++)<br>{<br>    var row = sheet.Cells.GetRow(rowIndex);<br>    var address = row.GetCell(0).StringValue;<br><br>    //Prepare Transfer request via Vottum API for .NET client<br>    var transferRequest = new TransferRequest<br>    {<br>        contractAddress = ERC20,<br>        recipient = address,<br>        amount = 100,<br>        network = 80002,<br>    };<br><br>    try<br>    {<br>        var transferResponse = await vottunAPIForNETClient.TransferAsync(transferRequest, CancellationToken.None);<br>        Console.WriteLine($&quot;Transfer tokens to {transferRequest.recipient} ,TxnHash: {transferResponse.txHash}&quot;);<br>    }<br>    catch (Exception ex)<br>    {<br>        Console.WriteLine($&quot;Txn error:{ex.Message}&quot;);<br>    }<br><br>}</pre><h3>Ejecución del código</h3><p>Por último, compila y ejecuta el código. Como resultado de la ejecución del código, se mostrará por la consola las siguientes trazas, que evidencian las transacciones realizadas:</p><pre>Deployed ContractAddress: 0xcb07997B4c8BE75aA03C6C30874d49144ddeD73e<br><br>Transfer tokens to 0x4Ef7f46b3aaD6DEfd77e6C2662B987f21F72D283 ,TxnHash: 0x577b08560d31fac606a132ca403aeb071b39cd5aecca5dc4aa2271e4ebeffcd3<br>Transfer tokens to 0x9a631B2fC37872Ad178b322240dDc316EB2f48E8 ,TxnHash: 0x11091d0d5c1634c1dd6c30dd950b9dc7f0eba18d0b02672252625fdf5f646b60<br>Transfer tokens to 0x43f73ab141Fd9A1A83ab49F2550D940010aC9B82 ,TxnHash: 0x2b1e3338cb49a9132a443d9ddd26fdd50a2e23b85c413d39f8da6e66f1b15d3b</pre><h3>Resumen</h3><p>Hemos visto lo sencillo que es crear un nuevo token ERC20 con nuestras APIS de Vottun y realizar un aidrop a las direcciones que queramos. Este proceso lo podemos incluir fácilmente en nuestros programas .NET, de forma sencilla, utilizando el paquete nuget VottumERC20API.NET (<a href="https://github.com/jzafrap/VottunERC20API.NET">https://github.com/jzafrap/VottunERC20API.NET</a>).</p><p>Tienes disponible el proyecto y todo el código comentado en este tutorial en GitHub en este repositorio: <a href="https://github.com/jzafrap/ERC20Airdrop.VottunERC20API.NET">https://github.com/jzafrap/ERC20Airdrop.VottunERC20API.NET</a></p><h3>Disclaimer</h3><p>Ten en cuenta que: el código mostrado en este artículo tiene fines educativos y no está pensado para su ejecución en entornos productivos, DYOR.</p><p>Keep coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457fb7b30a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart contracts for every developer]]></title>
            <link>https://medium.com/@jzafradelpozo/smart-contracts-for-every-developer-f18090016789?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18090016789</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Tue, 08 Jan 2019 21:56:03 GMT</pubDate>
            <atom:updated>2019-01-08T21:58:53.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XM1VoTeyiy0u3PQ-" /><figcaption>Photo by <a href="https://unsplash.com/@ilyapavlov?utm_source=medium&amp;utm_medium=referral">Ilya Pavlov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is more than Solidity to develop smart contracts.</p><p>Are you a developer? Do you think learn Solidity is mandatory for programming smart contracts for Blockchain? You are wrong!</p><p>Here I bring a list of different crypto projects (not all but the most important at the moment) that support deploying of smart contracts over their blockchains, where you will see what programming language can be used to implement smart contracts; there is more than Solidity out there!</p><p>For each of them, I’ll include the source url as an evidence. Also I’ll include programming languages of supported APIs/SDKs avalaible, and availability of blockchain networks for every crypto (Testnets, Mainnets, etc), as a reference for programmers interested in using their current skills to introducing in this crypto word.</p><p>What about EOS, Stellar, Cardano, Neo, Waves, Tezos, Qtum, Tron, Nebulas or Ontology? I hope you heard about all of these … Here is the promised info, let’s go!</p><h3><a href="https://eos.io/">EOS</a></h3><p><a href="https://eos.io/">EOSIO - Blockchain software architecture</a></p><ul><li>EOS white paper is <a href="https://github.com/EOSIO/Documentation/blob/master/TechnicalWhitePaper.md">here</a>.</li><li><a href="https://developers.eos.io/eosio-cpp/v1.3.1/docs/c-cpp-api">C and C++ as smart contract language</a>; you can get all the info in the <a href="https://developers.eos.io/">EOS Developer Portal</a></li><li>Developers can build their own public or private blockchains; at the moment there aren’t any EOS network blockchains avalaible, developers must run a local EOS node to develop and deploy smarts contracts over it.</li></ul><h3><a href="https://www.stellar.org/">STELLAR</a></h3><p><a href="https://www.stellar.org/">Stellar | A Blockchain Network for Payments and Tokenization</a></p><ul><li>Stellar white paper is <a href="https://www.stellar.org/papers/stellar-consensus-protocol.pdf">here</a></li><li>Stellar Smart Contracs (SSC) are explained <a href="https://www.stellar.org/developers/guides/walkthroughs/stellar-smart-contracts.html">here</a>. Avalaible <a href="https://www.stellar.org/developers/reference/">REST API, and Javascript, Go, Java, Ruby, Python and C# SDKs</a>.</li><li>Stellar livenet (stellar core) is available.</li><li>Stellar cryptocurrency is Stellar LUMEN; token creation is supported.</li><li>Stellar livenet and <a href="https://www.stellar.org/developers/guides/concepts/test-net.html">testnet</a> available for developers (<a href="https://www.stellar.org/developers/guides/concepts/test-net.html">url here</a>)</li><li>Txn explorer for livenet (and testnet) <a href="https://stellarchain.io/">here</a></li></ul><h3>CARDANO</h3><p><a href="https://www.cardano.org/en/home/">Home - Cardano</a></p><ul><li>Cardano whitepaper is <a href="https://whycardano.com/assets/WhyCardanoEN.pdf">here</a></li><li>Supports smart contracts implemented in <strong>Plutus </strong>language, a functional language similar to Haskell</li><li>MainNet, Txn explorer <a href="https://cardanoexplorer.com/">here</a>.</li><li>Cardano cryptocurrency is ADA, also support token creation, but there aren’t implemented tokens on Cardano network at the moment.</li></ul><h3>NEO</h3><p><a href="https://neo.org/">Neo Smart Economy</a></p><ul><li>Neo whitepaper is <a href="https://docs.neo.org/en-us/whitepaper.html">here</a></li><li>Neo supports C#, VB.Net, F#, Java, and Kotlin for developing smart contracs.</li><li>Neo has Mainnet and testNet avalaible (Txn explorer <a href="https://neotracker.io/">here</a>)</li><li>Neo cryptocurrency is NEO ( GoverningToken), GAS (Utility token) and supports NEP5 token creation.</li></ul><h3>WAVES</h3><p><a href="https://wavesplatform.com/">Official site of Waves. The WEB 3.0 company</a></p><ul><li>Waves whitepaper is <a href="https://blog.wavesplatform.com/waves-whitepaper-164dd6ca6a23">here</a></li><li>Smart contracts use <a href="https://docs.wavesplatform.com/en/technical-details/ride-language.html"><strong>RIDE </strong>language</a></li><li>Client library in python, java, c#, typescript/javascript, C; Node REST API avalaible (reference <a href="https://docs.wavesplatform.com/en/getting-started/as-a-developer.html">here</a>).</li><li>Waves cryptocurrency is WAVES, and creation of smart assets is supported.</li><li>TestNet and MainNet avalaible.</li></ul><h3>TEZOS</h3><p><a href="https://tezos.com/">Home | Tezos</a></p><ul><li>White paper is <a href="https://tezos.com/static/papers/white_paper.pdf">here</a></li><li>Smart contracts implemented in <strong>L</strong><a href="http://www.liquidity-lang.org/"><strong>iquitity</strong> </a>or <a href="http://tezos.gitlab.io/mainnet/whitedoc/michelson.html"><strong>Michelson</strong> language</a>, both of them are OCaml style functional languages</li><li>Tezos cryptocurrency is TEZ; no evidence of tezos asset creation supported.</li><li>Tezos have three networks, from test to production: Alphanet, zeronet and MainNet. Txn explorer <a href="https://tzscan.io/">here</a>.</li></ul><h3>QTUM</h3><p><a href="https://qtum.org/en">Home - Qtum</a></p><ul><li>Whitepaper <a href="https://qtum.org/user/pages/01.home/Qtum%20whitepaper_en%20v0.7.pdf">here</a></li><li>Smart Contracts are implemented in <strong>Solidity</strong>. Developer docs <a href="http://book.qtum.site/en/">here</a>.</li><li>QTUM cryptocurrency is QTUM, and supports ERC20 tokens.</li><li>TestNet and MainNet avalaible, Txn explorer <a href="https://explorer.qtum.org/">here</a>.</li></ul><h3>TRON</h3><p><a href="https://tron.network/index?lng=en">TRON Foundation：Capture the future slipping away</a></p><ul><li>white paper is <a href="https://tron.network/static/doc/white_paper_v_2_0.pdf">here</a></li><li>smart contracts in <strong>solidity </strong>language</li><li>It has a browser plugin (tronix) similar to metamask.</li><li>Can use tools like remix ide to compile contracts</li><li>support TRC10,TRC20 token creation</li><li>TRON has a testNet (Shasta) and MainNet. Txn explorer <a href="https://tronscan.org/#/">here</a></li></ul><h3>NEBULAS</h3><p><a href="https://nebulas.io/">Nebulas</a></p><ul><li>White paper is <a href="https://nebulas.io/docs/NebulasWhitepaper.pdf">here</a></li><li>uses <strong>javascript and typescript </strong>as contract language (<a href="https://wiki.nebulas.io/en/latest/dapp-development/tools.html">source</a>); uses V8 engine to run smart contracts on nebula blockchain.</li><li>Nebulas API avalaible in <a href="https://wiki.nebulas.io/en/latest/dapp-development/tools.html#"><strong>Go, Python, PHP, ruby, NET, unity3d, swift</strong></a></li><li>Nebulas cryptocurrency is NAS. Supports <a href="https://wiki.nebulas.io/en/latest/dapp-development/nrc20.html">NRC20 token creation</a>.</li><li>TestNet and MainNet available. Txn Explorer <a href="https://explorer.nebulas.io/">here</a>.</li></ul><h3>At Last…</h3><p>With no more time at the moment to include other examples, you can see, as adeveloper, <strong>how big is the actual blockchain ecosystem</strong>, and how many posibilities for smart contract implementation exist, using programming languajes like Solidity, C#, Java, Javascript, C++, and others more peculiar like pluto, Michelson or RIDE.</p><p>Do you know that your implemented solidity contract for Ethereum blockchain can be (almost)easily adapted to deploy on TRON or QTUM (and many others) blockains? Take a chance! Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18090016789" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PetFriendResolver, a PoC of Snowflake Resolver, Part II — Adapting to ERC 1484]]></title>
            <link>https://medium.com/@jzafradelpozo/petfriendresolver-a-poc-of-snowflake-resolver-part-ii-adapting-to-erc-1484-78c0aa8e4905?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c0aa8e4905</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[hydro]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 14:13:53 GMT</pubDate>
            <atom:updated>2018-12-13T14:09:32.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>PetFriendResolver, a PoC of Snowflake Resolver, Part II — Adapting to ERC 1484</h3><p>In <a href="https://medium.com/@jzafradelpozo/petfriendresolver-making-a-poc-of-snowflake-resolver-part-i-d98cb096bae3">my first post</a>, I introduced what Snowflake dashboard is, and what is the expected functionality to implement in PetFriend DApp. Lot of progress done in DApp since last post, as you can see in this screenshots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_F8u-FN5VhoR-hniLSy3Lg.png" /><figcaption>1. Account details view</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*os-TO8C55oVr5pt0lFRqmQ.png" /><figcaption>2. Pet details main view, and next, the lost pet list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X46Nlcb9KSDM7kiRspZR5Q.png" /><figcaption>3. Lost Pets list view</figcaption></figure><h4>Changes in snowflake contract</h4><p>Recently, an update of Snowflake contract has been submitted, making it compliant with <a href="https://eips.ethereum.org/EIPS/eip-1484">ERC 1484</a>. Changes include using <strong>EIN </strong>instead HydroId as standard identity number for snowflake owners. As said in ERC 1484,<em> “EINs are incrementing uint identifiers starting at 1”</em>. From s<em>olidity contract point of view</em>, the EIN is uint type, while HydroId is string type, making much more efficient to work with uint than strings in the contract code. Mayor changes include updating to 0.50.0 solidity compiler, and for DApp frontend, the proposal of using <a href="https://reactjs.org/docs/hooks-intro.html"><strong>React Hooks</strong></a> with “functional components” instead using react State and class Components. This required a little adaptation of my main App js (index.js), that now has been renamed to <a href="https://github.com/jzafrap/PetFriendResolver/blob/master/PetFriendResolver.js">PetFriendResolver.js</a>, and has become a function instead a class.</p><h4>Using ExtraData parameters on sign-up</h4><p>This new snowflake dashboard also supports extraData params passing to resolver when new snowflake is registered. <strong>ExtraData params allow passing inital state to registration of a snowflake to resolver</strong>, like account or contact information. New code in contract is like this:</p><pre>// implement signup function<br>function onAddition(uint ein, uint, <strong>bytes memory extraData</strong>) <br>public <br>senderIsSnowflake() <br>returns (bool) {<br> SnowflakeInterface snowflake = SnowflakeInterface(snowflakeAddress);<br> snowflake.withdrawSnowflakeBalanceFrom(ein, owner(), signUpFee);<br> //update the mapping owners<br> <strong>(string memory contactName, string memory contactData) = abi.decode(extraData, (string, string));</strong><br> owners[ein].contactName = contactName;<br> owners[ein].contactData = contactData;<br> // emit StatusSignUp(ein);<br> return true;<br>}</pre><p>Extradata must be encoded using abi functions before sending to contract, and must be “sended” to register form by calling sendExtraData() function:</p><pre>function handleClick(){ <br>  var extradata =   context.web3js.eth.abi.<strong>encodeParameters</strong>([‘string’,’string’], [contactName, contactData]); <br>  <strong>sendExtraData</strong>(extradata); <br>}</pre><h4>Deposit and withdraw flow between Resolver and registered Snowflake</h4><p>This DApp implements reward mechanism with this algorithm:</p><ol><li>When pet owner put a reward, funds from snowflake are sended to resolver and are escrowed in the resolver, until someone claim it.</li><li>When pet owner change reward (by modifing report form), funds are updated, making new deposit (or withdraw if needed) until match new reward from previus value.</li><li>When pet owner cancel report, funds are withdraw again from resolver to snowflake.</li><li>When any claims the reward after found a pet, and pet owner confirm the reward, funds are transferred from resolver to claimer snowflake funds.</li></ol><p>These use cases are basic examples of fund transaction between resolver and registered snowflake. Next you can see the contract method used to put a new report, including code to deposit funds from snowflake(owner) to resolver:</p><pre>//new LostReport<br>function putLostReport(uint ownerId, string memory petId, string memory sceneDesc, uint reward ) <br>public <br>_onlyPetOwner(petId)<br>//_petExists(petId)<br>_canReward(ownerId,reward)<br>_reportNotActive(petId)<br>returns (bool){</pre><pre> //1. report dont exists<br> require(bytes(lostReports[petId].sceneDesc).length==0,”Lost Report already exists.”);<br> //2. create new struct, assign to storate mapping<br> //persist on storage<br> lostReports[petId].sceneDesc = sceneDesc;<br> lostReports[petId].reward = reward;<br> lostReports[petId].status = Status.Pending;<br> lostReportKeys.insert(petId); <br> <br> //escrow reward from snowflake to resolver<br><strong> SnowflakeInterface snowflake =  SnowflakeInterface(snowflakeAddress);<br> snowflake.withdrawSnowflakeBalanceFrom(ownerId, address(this), reward.mul(10**18));</strong><br> //emitFundsChanged(ownerId, petId, Status.Pending, FundMovement.Withdraw);<br> emitEventV2(petId, lostReports[petId]);<br> return true;<br>}</pre><p>The code used to send the reward to claimer is:</p><pre>function confirmReward(uint ownerId, string memory petId) <br>public <br>_onlyPetOwner(petId)<br>_reportStatusMustBe(petId,Status.Found)<br>returns (bool){</pre><pre> //change state to Closed<br> lostReports[petId].status = Status.Rewarded;</pre><pre>//transfer previously deposited funds from resolver to claimer <strong>transferHydroBalanceTo(lostReports[petId].claimerEin,lostReports[petId].reward.mul(10**18));</strong></pre><pre> //LostReportChanged event<br> emitEventV2(petId, lostReports[petId]);<br> <br> //delete all struct elements for hydroOwnerId<br> delete lostReports[petId];<br> //delete key<br> lostReportKeys.remove(petId);<br> <br> return true;<br> }</pre><p>This very basic example uses two methods:</p><pre>withdrawSnowflakeBalanceFrom(uint UIN, address To, uint quantity) </pre><p>is a method included in Snowflake interface, and is used to escrow reward funds from pet owner’s snowflake funds to petOwnerResolver funds. In addition:</p><pre><strong> </strong>transferHydroBalanceTo(uint EIN, uint quantity)</pre><p>is a method of SnowflakeResolver (thus, inherited in PetFriendResolver), used to withdraw previous escrow from resolver funds to snowflake funds.</p><h4>Easter Egg: Deploying to Azure</h4><p>Actually I’m working with Microsoft Azure ecosystem, and I decided to give Azure a try to deploying my local dashboard online, where other people can see the results and give me feedback. I started googling and got some good links to do the process of deploying a node.js app over Azure. Here is an abstract of followed steps:</p><ol><li>Prerrequisites: You must have an Azure account; there are free accounts for developers, just get one! Also you must have a zip file with your node.js app compressed files.</li><li>After registration, go to Azure Portal, and open a Cloud Shell console; you have to click cloud shell icon as shown in this screenshot:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeKO0V8HpycTwRx3O_MDLw.png" /><figcaption>“Cloud Shell” icon in Azure Portal</figcaption></figure><p>Then, execute this commands in order, waiting for console response:</p><pre>az group create — name myResourceGroup — location “France Central”</pre><pre>az appservice plan create — name myAppServicePlan — resource-group myResourceGroup — sku FREE</pre><pre>az webapp create — resource-group myResourceGroup — plan myAppServicePlan — name PetFriendResolver</pre><pre>app config appsettings set — resource-group myResourceGroup — name PetFriendResolver — setting WEBSITE_NODE_DEFAULT_VERSION=8.11.1</pre><p>Then, yo can access admin portal for your deployed application:</p><p>http://&lt;your_app_name&gt;.scm.azurewebsites.net</p><p>Next step is upload App zip; open this url:</p><p>http://&lt;your_app_name&gt;.scm.azurewebsites.net/ZipDeployUI</p><p>You can drag and drop the zip with your application to this window, to deploy inmediately over the last deployed app (last app is deleted before deployment).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxCZLddid--X4zJRaVzu4A.png" /></figure><p>And, at last, you can explore your application in : &lt;appname&gt;.azurewebsites.net:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBL0MpVRUtI3AAJ5pC5dVQ.png" /><figcaption>Running our DApp over Azure!</figcaption></figure><h4>At last…</h4><p>PetFriend DApp has evolved from a paper idea to implementation, and now It is fully functional in Rinkeby network. Thought this is a PoC, and not optimized for mainnet network (because of transaction costs), it can be a good starting point to introduce yourself developing DApps for snowflake dashboard. Making this Dapp was a very good experience for me to develop over Ethereum blockchain, learn Solidity, put it a Front-End (answering “What is react.js?”), push it to snowflake dashboard, and learn a lot in the process.</p><p>You can see source code of contract <a href="https://github.com/jzafrap/PetOwner-Snowflake-Resolver-PoC/blob/master/contracts/PetFriendResolver.sol">here</a>, and DApp frontent source code <a href="https://github.com/jzafrap/PetFriendResolver">here</a>.</p><p>Lot of thanks to Hydro Project and specially to <a href="https://medium.com/u/73b655c3546">Noah Zinsmeister</a> and <a href="https://medium.com/u/dc1ba7b022aa">Anurag Angara</a>, from Hydrogen Team, for their helping to make this possible. Bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c0aa8e4905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using contract Events as data source for your DApp]]></title>
            <link>https://medium.com/@jzafradelpozo/using-contract-events-as-data-source-for-your-dapp-9fdb559b9f0b?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fdb559b9f0b</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 07:41:51 GMT</pubDate>
            <atom:updated>2018-11-27T07:41:51.075Z</atom:updated>
            <content:encoded><![CDATA[<p>Since the initial design of my PetFriend DApp, I want to implement a use case for showing a list of incidences registered on every pet. I read about ethereum blockchain having a <strong>public registry of all events emitted by transactions</strong>, and I think this information can be very useful to pet owners, and these events are, at last, a <em>blockchain contained breadcrumbs</em> of every incidence with my pets. Isn’t it the main objetive of making a PetFriends Resolver based on blockchain? I think so, go for it! The idea is not registering historic of report changes as contract data, but as events generated by transactions.</p><p>After read lot of documentation (the best found <a href="https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#getpastevents">here </a>and <a href="https://solidity.readthedocs.io/en/v0.4.24/contracts.html#events">here</a>), started with this:</p><p>This is the event declared in my ethereum contract:</p><pre>//when lost report changes: reports, modifies, claimed, closed…<br> //to be used to list an historic of pet incidences<br> event <strong>LostReportChanged</strong>(<br>    string <strong>indexed </strong>petIdentification, <br>    uint date,<br>    LostReport lostReport<br> );</pre><p>This event is thrown when any changes to a LostReport are made, making a “history of changes”.</p><blockquote>Note: you can see indexed<strong> </strong>keyword in the code; indexing event fields is necesary to allow indexed searching of the event log. But solidity indexing capabilities are limited; if you try to index a string field, as an unknown-length array of chars, solidity generates a hash for that field and put it as a additional <em>topic </em>in the event log. What are <em>event topics</em>? They are searchable fields, in the form of hash (32bytes) strings, that allow searching in Event Log for any of the topics, using web3j interface.</blockquote><p>As an example, when we call contract.updateReport(), and the transaction is made in the blockchain, we can see the result events using <a href="https://rinkeby.etherscan.io/tx/0x3e264ecb3312540f6e2d34d318d84fc54b5d7abc3c977347f39e0b09ff63df4e#eventlog">Rinkeby Etherscan</a>, showing this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*i8LgVNDi2hJr5N30UshacQ.png" /></figure><p>We can see two topics, the first is added by default, and corresponds to event signature (a very complicated hash of a string containing event name and canonical type of every args the event have); the next ones, if any, correspond to indexed fields of the event. Be careful, because the order is important when calling event searching API.</p><p>This is the js file except, showing how to search events, filtered by event name (LostReportChanged) and topics (array of topic ids), petId, that will be rendered as a table:</p><pre>//ReportHistoryTable.js</pre><pre>componentDidMount() {<br> <br> var _this = this;<br> var shaPetId = this.props.w3w.web3js.utils.sha3(this.state.petIdentification);<br> this.props.resolverContract.getPastEvents(‘LostReportChanged’, <br>  {<br>    filter: {},<br>    fromBlock: 0, <br>    toBlock: ‘latest’,<br>    <strong>topics: [null,shaPetId]</strong><br>  }, <br>  function(e,l){<br>    _this.setState({ events: l,})<br>  }<br> )<br>}</pre><p>This code use the getPastEvents method to get all the LostReportChanged events; the search is made in the blockchain, from block 0 to the last, and topics parameter is an array of topic values used for searching; as LostReportChanged has two topics, and we don’t wan’t to filter by the first topic, we pass null as topics[0] array.</p><p>The second topic is a generated hash (using sha function) of petIdentification field, because indexed fields with no fixed length (like ‘bytes’ or ‘string’) are hashed, to reduce to 32bytes length, before including in event topic array; you can read about it in solidity docs <a href="https://solidity.readthedocs.io/en/v0.4.24/contracts.html#low-level-interface-to-logs">here</a>.</p><p>Rendering events into a table is easy with react, here is the code. The trick is using map ES6 javascript function to map events to table rows:</p><pre>render() {<br>    return(<br>  <br>  &lt;div&gt;<br>       <br>        &lt;Dialog<br>          open={this.props.open}<br>    fullScreen={true}<br>          TransitionComponent={Transition}<br>          onClose={this.handleClose}<br>          aria-labelledby=&quot;alert-dialog-slide-title&quot;<br>          aria-describedby=&quot;alert-dialog-slide-description&quot;<br>        &gt;<br>          &lt;DialogTitle id=&quot;alert-dialog-slide-title&quot;&gt;<br>            {&quot;Report history...&quot;}<br>          &lt;/DialogTitle&gt;<br>          &lt;DialogContent&gt;<br>    <br>   &lt;Table&gt;<br>    &lt;TableHead&gt;<br>     &lt;TableRow &gt;<br>      &lt;TableCell&gt;Date&lt;/TableCell&gt;<br>      &lt;TableCell &gt;Status&lt;/TableCell&gt;<br>      &lt;TableCell &gt;Pet Id&lt;/TableCell&gt;<br>      &lt;TableCell &gt;Scene Desc&lt;/TableCell&gt;<br>      &lt;TableCell &gt;&lt;MoneyIcon/&gt;&lt;/TableCell&gt;<br>     &lt;/TableRow&gt;<br>    &lt;/TableHead&gt;<br>    &lt;TableBody&gt;<br>    <br>     <br>      <strong>{this.state.events.map( ev =&gt;</strong> <br>       &lt;TableRow&gt;<br>        &lt;TableCell&gt;<strong>{this.formatTimestamp(ev.returnValues.date)}</strong>&lt;/TableCell&gt;<br>        &lt;TableCell&gt;{this.props.getStatusTxt(<strong>ev.returnValues.lostReport.status</strong>)}&lt;/TableCell&gt;<br>        &lt;TableCell&gt;<strong>{ev.returnValues.petIdentification}</strong>&lt;/TableCell&gt;<br>        &lt;TableCell&gt;<strong>{ev.returnValues.lostReport.sceneDesc}</strong>&lt;/TableCell&gt;<br>        &lt;TableCell&gt;<strong>{ev.returnValues.lostReport.reward}</strong>&lt;/TableCell&gt;<br>       &lt;/TableRow&gt;<br>     <strong> )}</strong><br>    &lt;/TableBody&gt;<br>   &lt;/Table&gt;<br>  &lt;/DialogContent&gt;<br>   &lt;DialogActions&gt;<br>    <br>   &lt;Button onClick={this.props.handleClose} color=&quot;primary&quot;&gt;<br>              Close<br>            &lt;/Button&gt;<br>          <br>          &lt;/DialogActions&gt;<br>  &lt;/Dialog&gt;<br>  &lt;/div&gt;<br>    )<br>  }</pre><p>And this is the result data shown in browser. As a Dialog, it shows in a modal panel, with “close” button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOWun6z6aV--xGdgaazt5Q.png" /></figure><p>As expected, we have a history of report changes for the pet, with all the needed data, fetched from the ethereum event logs. The table contains:</p><ol><li>First report was created nov 18 2018.</li><li>Then, desc, location and reward were changed</li><li>At last, the owner removed the report.</li></ol><p>This search was difficult to implement, because the lack of documentation and examples on the web: first I had to modify the contract, to include indexed keywork to indexing the desired field of the event; after redeploy the contract to Rinkeby net, I had to deal with js code and Web3j API, until I got the desired behavior.</p><p>I hope this notes can help you, bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fdb559b9f0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PetFriendResolver, making a PoC of Snowflake Resolver - Part I]]></title>
            <link>https://medium.com/@jzafradelpozo/petfriendresolver-making-a-poc-of-snowflake-resolver-part-i-d98cb096bae3?source=rss-384a00d8b3b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d98cb096bae3</guid>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[hydro]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Javier Zafra]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 17:51:48 GMT</pubDate>
            <atom:updated>2018-12-13T12:03:39.125Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a follower of Hydrogen Platform from the beginning, and I was there in the one&amp;only airdrop made to developers. Since then, I want to contribute with the Hydro community. This Poc is about making a Snowflake Resolver, the different steps you must do in the process, and all the problems and odds you can experiment on the way.</p><p>First, you must know what Snowflake is: one of the projects made around Hydrogen platform, based on Hydro token. Please, read the next document to have more information about it.</p><p><a href="https://medium.com/hydrogen-api/snowflake-identity-protocol-and-the-hydro-dapp-store-61d8fadcce0f">Snowflake Identity Protocol and the Hydro dApp Store</a></p><p>Snowflake is focused on user identification, privacy, and verification. Actually the project is developing a dashboard where everybody can deploy their own resolvers, as Dapps, that make use of the snowflake contract.</p><p>What are the benefits of using this DApps? I recommend you to google and read the docs about snowflake, and I’ll try explain in a few lines:</p><ul><li>Any crypto user can have a lot of crypto wallets, making the use of them very confusing, dealing with diferent adresses, etc.</li><li>Driving with the different private keys of every wallet, the thing is going worse. It becomes a security problem dealing with all your accounts an private keys.</li><li>What about to have an unique account that can include all of your crypto wallets, with an easy to remember ID? No need to remember addresses (do not try!), only your ID. That’s we call <strong>Snowflake ID</strong>.</li><li>With Snowflake, you can create an unique ID, with the identification you want (not previously created by other). Then you can attach one or more ethereum addresses to this ID. After that, you can use your unique ID in lot of use cases, including: transferring funds to other snowflakes, pay for services, subscribe to content providers, etc.</li></ul><p>In these articles, I’m going to explain the process followed to make a Snowflake Resolver: a Dapp built to be used with snowflake IDs, and aims to give an example (that we can call PoC or <em>Proof of Concept</em>) of What You can do, and What use cases can make use of this functionality.</p><h3>Introducing PetFriendResolver</h3><p>As a pet owner, I have my two cats correctly identified with a microchip. Pet owners must have their pets identified, because it simplifies the process of finding the pet owner in case of loss of the pet, or any incidence related to the pet.</p><p>There are many of internet web pages where you can register and report when your pet is lost, and let the community to help you finding it.</p><p>This PoC try to make a pet owner’s community, when you can register all your pets, including information to identify them, like the microchip ID, a photo, and description data.</p><p>Let’s talk about the requisites! Starting with an ER diagram (as a good programmer):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*tdpQdUkIjjMGvfr8_zFN1g.png" /></figure><p>REQ 1: Other users can contact an owner, but be careful what contact info you publish, this is public data! Give a public email, Telegram or Facebook id can be correct.</p><p>REQ 2: an owner can have one or more pets. Pet owners can see and edit the information of their pets.</p><p>REQ 3: an owner can report the loss of an owned pet. In the report, is important to give information about the scene and location where you last see your pet. You can put a reward for helping you to find your pet. This reward is only symbolic and try to help the community collaboration. In addition, the reward acts as a good use case to see pay transaction between diferent Snowflake accounts.</p><p>REQ4: anyone registered can see a list of lost pets at the moment. The app shows the photo of the lost pet, description, lost scene and location, and offered reward. Also you can see the microchip ID, proof of identity of the pet. If you found a pet and it matches any of lost pets, you can <em>Claim the found of the pet</em>. Then you can contact pet owner.</p><p>REQ5: pet owner must confirm the found of the pet, closing the report and making the payment of the reward to the claimer. This is a transaction between owner’s snowflake and claimer’s snowflake.</p><p>REQ6: pet owner can cancel a previous lost report before it is claimed (for example, the owner found its pet by himself); this remove the report from list of lost pets.</p><p>And that’s all!</p><p>This DApp acts as a registry of pets (for a closed community, like a small town or a neighborhood). When a pet owner get registered in the App, he belongs to a pet friend community, when he can help others to find lost pets (getting a little reward in the process), and can be helped to find his own pets in case of lost. Isn’t it marvelous? Don’t worry boy, this is only a PoC!</p><h3>Introducing developing ecosystem</h3><p>Let’s talk about the developing ecosystem; I’m using these tools:</p><ul><li><strong>Remix — Solidity IDE,</strong> for writing and deploy contract to ethereum network. Go to <a href="https://remix.ethereum.org/">page</a>.</li><li><strong>Node.js</strong> + snowflake dashboard fork to start development.</li><li>Front end: <strong>React.js, web3j, javascript</strong> skills.</li><li>Ethereum contract: <strong>solidity</strong> skills, and knowledge of snowflake contract and dapps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*EVgrLmvusglH1QTYR0Ge0g.png" /><figcaption>My metamask plugin showing connected network (Rinkeby) and current active account (Account 1 starting with 0x422ee…)</figcaption></figure><ul><li><strong>Metamask </strong>plugin for chrome: this is an interface from browser to ethereum blockchain, allowing the creation and administration of several ethereum accounts.</li></ul><p>First, you must fork and deploy a local snowflake dashboard (can be found here). <strong>This process was very hard at the beginning</strong>, because building and running a local environment with node.js and the compiled dashboard was not easy at all. Following deploy instructions, I found problems compiling project dependencies, and at last, I had to install python binaries, and Visual Studio Community Edition 2015 only to compile dependencies (C classes!) needed to deploy. Finally I made “npm install” run correctly to compile and deploy the dashboard; I hope you don’t have same problems deploying your local dashboard.</p><p>Here you can see my running dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nj8Rk6Je9YINxvS_cJWDyg.png" /></figure><p>It runs in the url localhost:3000/dapp-store after the execution of “npm start” in the folder where the dashboard app is deployed (and compiled).</p><p>In the screen capture you can see my snowflake Id (jzafra2), my hydro balance (19990) and the available Dapps, as a list of resolvers. Every resolver has an image, the big “S” is the Status resolver, example of Dapp in the dashboard, made by Hydro team as an example. You can see the source code on Github.</p><p>Next resolvers have an animal image, they are my petFriend resolvers that I’m developing.</p><p>Here you see my first prototype results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7c6v-Zunxsq4cGAHqr8eg.png" /><figcaption>This is the registered pet (at the moment only one, but developing for N pets)</figcaption></figure><p>And this is the list of lost pets (of any pet owner). I’m working with two snowflake Ids (jzafra2, jzafra3), to see the results. As you can see, the lost pet is from another snowflake Id, jzafra3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrOcQxvxR1My122MuRnZww.png" /></figure><p>Interactions are made with Dialogs (a basic React,js component); for example, this dialog is for editing pet details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzHu702sSkrXY-bwqmrn4A.png" /></figure><p>In next articles, i will explain the process of developing the resolver, dot a dot:</p><ul><li>Making the resolver contract and deploying to Rinkeby network</li><li>Make dapp interface with React.js</li><li>Development cycle of improving interface, improving contract, testing functionality, once and another…Until app is done!</li></ul><p>I had to deal with React.js and javascript to make frontend; and with solidity at backend. I didnt’ work with react.js nor solidity before (but I’m an experienced programmer in Java and C#), and I had to learn basic skills to made all this stuff. If this is your case, I hope you can learn of my experience.</p><p>Thanks to @NoahHydro and all the team of hydro at discord in <a href="https://discordapp.com/channels/416248342381854721/416269213557194764">https://discordapp.com/channels/416248342381854721/416269213557194764</a>, who are helping me to do this, at last It will be done, I hope!</p><p>Thanks for read! Please, go to part 2 of this article here:</p><p><a href="https://medium.com/@jzafradelpozo/petfriendresolver-a-poc-of-snowflake-resolver-part-ii-adapting-to-erc-1484-78c0aa8e4905">PetFriendResolver, a PoC of Snowflake Resolver, Part II — Adapting to ERC 1484</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d98cb096bae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>