<?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[NicaSource - Medium]]></title>
        <description><![CDATA[Nicasource is a specialized staffing firm offering clients high-quality dedicated teams &amp; staff augmentations solutions. You will find us here sharing our best practices, tips &amp; tricks on the technologies we love and some other trends. - Medium]]></description>
        <link>https://medium.com/nicasource?source=rss----76ea101e9a71---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>NicaSource - Medium</title>
            <link>https://medium.com/nicasource?source=rss----76ea101e9a71---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:52:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/nicasource" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Celebrating 10 Years of Breakthroughs at NicaSource]]></title>
            <link>https://medium.com/nicasource/celebrating-10-years-of-breakthroughs-at-nicasource-ec1c7b2e014e?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/ec1c7b2e014e</guid>
            <category><![CDATA[memories]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[anniversary]]></category>
            <category><![CDATA[success]]></category>
            <dc:creator><![CDATA[Christian Torres]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 15:01:52 GMT</pubDate>
            <atom:updated>2023-07-19T15:01:51.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMpTmod3zYoOR5vtYs_DDg.png" /></figure><p>As we commemorate the momentous occasion of our 10-year anniversary at NicaSource, I find myself filled with a mix of emotions — pride, nostalgia, and a sense of gratitude and accomplishment. Over the past decade, our company has grown from a US-market focus Agency to a Staff Augmentation Organization with a market presence in US, Australia, and Nicaragua, evolving from a fully co-located company with offices in 2 countries to a remote-first company with employees distribute around the globe, people working from US, Nicaragua, Mexico, Argentina among other countries. Join me as we reflect on the past and look forward to an even brighter future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*zUW1WJmkSJw6MCP0HrSylw.jpeg" /><figcaption>First Company End Of Year Celebration in Nicaragua, December 13th, 2013. The first year ends with a small team of 11 people formed by 8 developers, an office manager, a branch CEO -who at that moment was also the Global VP of Technology and Development- and a chef</figcaption></figure><p><strong>The Early Days: Planting Seeds of Innovation</strong></p><p>A decade ago, our founders had a bold vision to create a company in Nicaragua, it was during <strong>Valentine’s Day ❤️ </strong>when the vision was confirmed, and then a couple of months later, ten years ago, a group of passionate individuals came together. We started with a handful of developers working tirelessly in a small office space, fueled by a shared belief that we could make a difference, learn new things, and expand our landscape. It was an exciting time of change with the new culture, brainstorming, experimenting, paying attention to quality, and coding late into the night. Our early projects laid the foundation for what was to come, and by then, technology was already reshaping the world as we knew it. As a developer, I have had the privilege of witnessing firsthand the rapid evolution of programming languages, frameworks, and tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hp_2YLHlDcmcocBsH2KJ8A.jpeg" /><figcaption>First Office at Viejo Santo Domingo, December 7th, 2013.</figcaption></figure><p><strong>Building a Healthy Organizational Culture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_iatr39wBPkFyJcVkoCaA.jpeg" /><figcaption><strong>Sharing knowledge</strong> has been part of NicaSource <strong>culture</strong> since the beginning. At the left a meetup with the Drupal community, one of our first, in October 2013. At the right, our internal twice-a-week company paid lunch gathering to share about technology, November 12th, 2013.</figcaption></figure><p>One of the key factors that contributed to our growth was the culture we fostered. Things like sharing knowledge, collaboration, innovation, creativity, adaptability, work-life balance, and autonomy, among other things.</p><p>We understood that great ideas rarely come from individual brilliance alone; they emerge from collaboration and diverse perspectives. We encouraged open communication, embraced failure as a learning opportunity, and celebrated our successes together. This spirit has been the driving force behind our achievements.</p><p>Cultivating this environment allows every team member to feel empowered to contribute their best work.</p><p><strong>Embracing Change and Evolving Technologies</strong></p><p>The tech landscape is constantly evolving, and as a company, we knew that adaptability was crucial for our survival. Over the past decade, we have witnessed significant technological advancements, from the rise of mobile applications to the advent of artificial intelligence and machine learning. Embracing these changes, we expanded our skill sets, adopted new technologies, and stayed ahead of the curve. Our ability to adapt and embrace emerging trends has been instrumental in keeping us at the forefront of the industry.</p><p>From the early days of web development to the current era of artificial intelligence and cloud computing, our adaptability and hunger for knowledge have been key to our success.</p><p><strong>Achieving Strategic Partnerships with our clients</strong></p><p>As we transformed to be a staff augmentation company focused on our client’s needs, strategic partnerships played a crucial role in our business landscape.</p><p>Our alliance and collaboration become increasingly important in today’s dynamic world. By achieving mutually beneficial goals that we couldn’t accomplish alone, it provides us with opportunities for growth and market expansion. It also enables us to achieve goals more effectively and efficiently and have an impact on both our and our client’s business.</p><p>We always look for ways to offer access to specialized expertise and the right fit for the needs of our partners.</p><p><strong>Looking Forward to the Next Decade</strong></p><p>As we celebrate our 10-year anniversary, we stand at the cusp of an even more exhilarating future. The next decade holds immense promise and opportunities for exponential growth; we must not rest on our laurels. Things such as Artificial Intelligence, Machine Learning, ChatGPT, Augmented Reality, Apple Vision Pro are here to stay, and it’s proof that the tech industry continues to evolve and at an unprecedented pace; and we must continue pushing boundaries, thinking outside the box, and anticipating the needs of tomorrow.</p><p>We will continue to invest in forging strategic partnerships, nurture emerging talent, and foster a culture of constant experimentation and learning.</p><p>In the years to come, we aspire to continue creating groundbreaking products, making a positive impact on our clients and on society, and fostering an inclusive and diverse tech community. With our team’s unwavering dedication and the support of our valued customers, I have no doubt that the next 10 years will be even more extraordinary than the last.</p><p>Happy 10-year anniversary, NicaSource!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BKB1B34ZViR5NdvbM8GPQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec1c7b2e014e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/celebrating-10-years-of-breakthroughs-at-nicasource-ec1c7b2e014e">Celebrating 10 Years of Breakthroughs at NicaSource</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django REST Framework to Quickly Get a Working API: part III]]></title>
            <link>https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-iii-8828a547dae6?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/8828a547dae6</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 16:12:19 GMT</pubDate>
            <atom:updated>2023-07-13T16:12:19.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbY5lfwK-4KLUOcuCIgxDA.png" /></figure><p>As a conclusion for this three-part series of articles on “how to use the DRF (Django Rest Framework)” to get a working API, we will focus on two crucial yet overlooked (mostly by beginners) concepts for your API, authentication and permissions, also referenced as authorization. As stated in the conclusion of part II, up until this point, our API accepts requests from any origin, and it allows unrestricted modification of the information stored in the database, which won’t be the case for most projects, so we will check some of the tools the DRF has to improve the resource administration.</p><h3>Authentication and authorization as concepts</h3><p>Before we do any Django REST Framework documentation reference, let’s establish what it means to have an authorized request in the context of a microservices architecture since that will help us better understand the implementation in our simple mechanic shop API project.</p><p>According to<a href="https://auth0.com/docs/get-started/identity-fundamentals/authentication-and-authorization"> auth0 by Okta</a>,</p><blockquote>authentication is the process of verifying who a user is, while authorization is the process of verifying what they have access to.</blockquote><p>It’s just like when you visit a hotel — you let them know you’ve arrived, and depending on your reservation and payment information, you may or may not be able to access the mini-bar.</p><p>How does this get translated into our project? First, we’d like to know who is trying to access our API, so we’ll see how we incorporate authentication using what the DRF provides us.</p><h3>Authentication with DRF</h3><p>According to the <a href="https://www.django-rest-framework.org/api-guide/authentication/#authentication">very efficient documentation of the DRF</a>,</p><blockquote>authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with.</blockquote><p>Without having to install any third-party package, the DRF has support for five types of authentication schemes:</p><ol><li>BasicAuthentication is generally only appropriate for testing.</li><li>TokenAuthentication suits client-server setups and fits like a glove with what we are developing.</li><li>SessionAuthentication is meant for AJAX clients running in the same session context as your website.</li><li>RemoteUserAuthentication, which allows you to delegate authentication to your web server (APACHE or NGINX).</li><li>Custom authentication (implemented by subclassing the BaseAuthentication class and overriding the authenticate method).</li></ol><p>How do we specify the authentication scheme we want to use? We will always define them using a list of classes. Then the DRF will attempt to authenticate with each class in the list, and it will set request.user and request.auth using the return value of the first class that successfully authenticates.</p><p>Based on the nature of your project you can:</p><ol><li>Declare the list of authentication classes globally.</li><li>Set that list of authentication classes.</li></ol><p>Since the endpoints we have set are somewhat sensitive, we will set the authentication globally in the settings.py module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*M7IKisjoqJo-cXsR" /><figcaption>A reminder for where settings.py is located.</figcaption></figure><p>In that module, we will add a piece of configuration. In this case, as we previously stated, the TokenAuthentication class is what we want, so your configuration will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80849f150ccf9dbb59ea286bc2dbca7c/href">https://medium.com/media/80849f150ccf9dbb59ea286bc2dbca7c/href</a></iframe><p>Plus, this authentication scheme requires us to add the authtoken app to the INSTALLED_APPS configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8869172c0043cbf2152e8c86d3be3de9/href">https://medium.com/media/8869172c0043cbf2152e8c86d3be3de9/href</a></iframe><p>Having the rest_framework.authtoken app registered in the installed apps will provide some migration files to create a table to store the generated tokens, so you, as a very aware person, will know that we need to apply those migrations by running python manage.py migrate :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OY2WgjgQK9QyB8mU" /><figcaption>Migrations that were applied after adding the Token authentication config.</figcaption></figure><p>Before moving on, let’s attempt one of the requests we’ve made in part II to see what functional changes have been introduced by the additional configuration we’ve set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8jQKIbIlvxrLMCY" /><figcaption>Getting the vehicles list after adding TokenAuthentication.</figcaption></figure><p>We still are allowed to get the list of vehicles despite not providing any credentials that validate who we are. That’s because<strong> authentication by itself won’t allow or disallow an incoming request; it simply identifies the credentials with which the request was made</strong>. In this case, since we’re not providing information about who we are, the request.user variable will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None. With that cleared out, we will consider the options we have to generate the tokens that inform the API of our identity.</p><h3>Generating a token</h3><p>a. in Django, you can have ‘listeners’ that act before or after a certain action or process with instructions that fit your needs, called signals. For example, we can make sure that after saving a User instance, a Token instance is generated and saved for the newly created user. IMHO, using signals can become rather tangled pretty quickly for moderately complex projects, and if you’re a beginner with Django, you probably are better off without using them.</p><p>b. Exposing an endpoint: when using TokenAuthentication , generating a token using a username-password pair seems rather convenient, so the DRF provides a built-in view to provide it by using the obtain_auth_token function. obtain_auth_token will return a JSON response when valid username and password fields are POSTed to the view using form data or JSON.</p><p>c. Using Django admin: we didn’t mention this given the nature of our project, but Django has this useful interface that allows creating objects from models we defined using a built-in admin panel. Considering we’re building this API from a microservices standpoint, there’s not much use to it.</p><p>d. Using Django manage.py command: the CLI utility that gave us the ability to start the project and add apps to it, generating migration files and applying them, also makes it possible (for version ≥ 3.6.4) to generate a user token by running:</p><p>python manage.py drf_create_token &lt;username&gt;</p><p>which will return the API token for the requested user, generating one if it doesn’t exist yet.</p><p>The option that better fits our requirements, both didactically and functionality-wise, is generating the token with the built-in view obtain_auth_token. To reach that functionality, we need to specify a path for it in the URL patterns we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31b2fd8286b2073536af30ef757c42d0/href">https://medium.com/media/31b2fd8286b2073536af30ef757c42d0/href</a></iframe><p>Then we will generate an ad-hoc user to get a token and present a general Django tool that I use quite frequently in my projects and find helpful, which is the<a href="https://docs.djangoproject.com/en/4.1/ref/django-admin/#shell"> “Django shell</a>.” The Django shell allows us to open an interactive Python interpreter with the context of the Django project we’re in, so doing the following is totally valid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*q73GvAhLnvdazktU" /><figcaption>Using the Django shell to create a user.</figcaption></figure><p>Notice that we’re leveraging the create_user method of the User model (<a href="https://docs.djangoproject.com/en/4.1/ref/contrib/auth/">another feat of Django)</a>, instead of directly using the create method. Otherwise, we wouldn’t get a hash of the password we specified, and our information would be compromised if anyone found a vulnerability in our system.</p><p>Ok, now let’s try to get a token for Salvatore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*RB4xNfS7Vf1-p56y" /><figcaption>Obtaining a token for Salvatore.</figcaption></figure><p>Yes! By obtaining a token, we can authenticate our requests to the API. As we noted before, we didn’t specify any authorization scheme yet, so our requests are still passing, but now the request.user will be correctly set to an instance of the User model (Salvatore in this case) once we include the token in our request headers, which will be fundamental to testing our permission classes.</p><p>To summarize, in a client-server architecture, we would:</p><ol><li>Obtain a token by making a POST request to /api/api-token-auth and retain or store that somewhere (when using a browser, we tend to store it in localStorage).</li><li>Set that token in the header for all our subsequent requests as follows:</li></ol><pre>&quot;Authorization&quot;: Token 81e584aebd6ccf9771ececd44234fb660aabc8a</pre><p>3. Send the request we want or need.</p><h3>Authorization (permissions)</h3><p>Along with authentication and<a href="https://technical-qa.com/what-is-request-throttling/"> throttling</a> (out of the scope of this series), permissions determine whether a request should be granted or denied access (even though what access is, is a relatively open definition).</p><p>Similar to authentication, permissions checks are always run before the main block of code of the view (usually the method handler for POST, GET, etc.) and will be typically associated with the identity established in the authentication process and stored in the request.user and/or request.auth objects</p><p>As stated in the<a href="https://www.django-rest-framework.org/api-guide/permissions/#permissions"> documentation</a>,</p><blockquote>The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.</blockquote><p>So, similarly to authentication, we’re using classes to establish permission either globally or per view, and before running the main body of the view, every class in the list is checked. If any permission check fails, a PermissionDenied or NotAuthenticated exception will be raised, and the main block of code won’t run.</p><p>Back to our project, let’s suppose that for some reason, you can use the endpoint to list the vehicles just by verifying your identity, which in our project, is achieved by passing the token in the Authorization header. Having that in mind, we’re going to import and set the IsAuthenticated permission class to the permission_classes list in the VehiclesList class-based view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab84fd3fd405df36ae8cb5e4504f0598/href">https://medium.com/media/ab84fd3fd405df36ae8cb5e4504f0598/href</a></iframe><p>Now, we are going to start the Django application and send a GET request to api/vehicles endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RJ73MKxTAg_JhejJ" /><figcaption>GET request after adding the IsAuthenticated permission class.</figcaption></figure><p>We got a 401 status code (Not Authorized) and a very clear message stating that we didn’t provide authentication credentials, which is true since we didn’t provide the Authorization header. So let’s try the same request after doing that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HPuLd_h1GDDqL0P5" /><figcaption>Successful request after properly authenticating.</figcaption></figure><p>Your day ends better when things go that smoothly. Why did that work? Inspecting the IsAuthenticated class might help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*Xr2fysx-OMiN3jz2" /><figcaption>IsAuthentication class definition.</figcaption></figure><p>Simple and effective. As that simple line reads, having truthy values for request.user and request.user.is_authenticated is enough to have permission, thanks to the TokenAuthentication class.</p><p>Ok, you might say holding your chin with your fist, but this is some generous permission policy to apply to a serious project, how can we implement something more specific? Glad you ask!</p><p>You can define any logic you want in a custom permission class. To write your own permission class, you just need to subclass the BasePermission class and implement has_permission and/or has_object_permission with the following signatures:</p><ul><li>has_permission(self, request, view)</li><li>has_object_permission(self, request, view, obj)</li></ul><p>The implemented methods should return True if the permission to access the resource is granted, and False if not.</p><p>To give a colorful example, let’s assume that Salvatore is an exemplary employee and Mario is not, so we don’t want Mario snooping around. We will create a permission class that implements some logic to prevent Mario from accessing resources. But since Mario doesn’t exist yet in our database, we need to add him using the User model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*w4jJ-SwIYYjbMhEJ" /><figcaption>Adding Mario.</figcaption></figure><p>Now, we need to create our custom permission class. We will add a new permission_classes module in the customers app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*iNHkUIECnXs2zew6" /><figcaption>New permission classes module.</figcaption></figure><p>The logic we want to implement is the following:</p><ul><li>If the request doesn’t have an authenticated user, reject it.</li><li>If the request is authenticated, but the user is Mario, reject it.</li><li>If the request is authenticated, and the user is not Mario, allow it.</li></ul><p>So that will translate into:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1401982d55331d3cf1881c4630818fbe/href">https://medium.com/media/1401982d55331d3cf1881c4630818fbe/href</a></iframe><p>You’ll notice that the last condition is exactly the same that is used in the IsAuthenticated class, so in theory, we could subclass it, and then call the super method, but to illustrate the custom class and avoid extending on<a href="https://www.geeksforgeeks.org/python-super/"> inheritance</a>, we will stick to our current approach.</p><p>To test our new class, we need to add it to the permission_classes list in the CustomersList class-based view:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30ddae80f0a4c0835421155cfddf346/href">https://medium.com/media/a30ddae80f0a4c0835421155cfddf346/href</a></iframe><p>A non-authenticated request will throw a classic 401, as expected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FtFRpo2sJUhG-tXc" /><figcaption>Not authenticated request.</figcaption></figure><p>What will happen with a “Mario-authenticated” request? After obtaining a token for Mario and making a request to get the customers list, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-TO-l_5fwRWyscPk" /><figcaption>Authenticated request for Mario.</figcaption></figure><p>We got a 403 status code, which means the request is authenticated (we know Mario is behind it), but it’s not authorized (Mario is not allowed). Finally, we are going to attempt a request to the same endpoint but for Salvatore (notice that the token now belongs to him):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*GkVU-gUr35YeUNFH" /><figcaption>Authenticated request to api/customers for Salvatore.</figcaption></figure><p>Working as expected! Our custom permission class:</p><ol><li>Does not allow unauthenticated requests.</li><li>Does not allow authenticated requests from Mario.</li><li>Allows authenticated requests from anyone else.</li></ol><h3>Conclusion</h3><p>Congrats! You made it through this series of articles. Hopefully, you now have a deeper understanding of how we can:</p><ol><li>leverage the DRF to keep out code DRY by using class-based views,</li><li>represent information that resembles the structure of the models we defined,</li><li>and lift a basic yet effective wall against curious people with a simple yet illustrative example project.</li></ol><p><strong>Next steps? Try some of these:</strong></p><ul><li>Look up how we can expose locally our API to have it listen to requests coming from a client (a frontend app).</li><li>Try to nest representations of information by using custom serializers as fields.</li><li>Connect an email server to send information from your Django app whenever a new user is created.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8828a547dae6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-iii-8828a547dae6">Using Django REST Framework to Quickly Get a Working API: part III</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como crear una aplicación de videollamadas]]></title>
            <link>https://medium.com/nicasource/como-crear-una-aplicaci%C3%B3n-de-videollamadas-e9617e55fe67?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/e9617e55fe67</guid>
            <category><![CDATA[agora]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[video-call]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Alan Antar]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 19:02:00 GMT</pubDate>
            <atom:updated>2022-12-02T19:01:59.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYMXKw7D0N0nPU0cvMCQ5Q.png" /></figure><p>Skype, Zoom, Google Meets, Discord entre otras han tomado un rol súper importante en nuestro dia a dia, con una reunión de trabajo, un curso online, entre muchas otras. Pero, qué tal crear tu propia aplicación de videollamadas? En este artículo te mostraré cómo puedes crear tu propia aplicación de videollamadas usando Agora SDK :).</p><p>LET ‘S START!</p><h3>AGORA SDK</h3><p>Agora SDK es una librería totalmente dedicada a las llamadas, video llamadas, streaming entre otras. Estas mismas se encuentran disponibles ya sea para Android Nativo, iOS nativo, Windows, Web, Unity, entre otros.</p><p>Hoy nos enfocaremos en cómo hacerlo funcionar en React Native!</p><p>Para mas info, no duden en visitar: <a href="https://www.agora.io/en/about-us/">https://www.agora.io/en/about-us/</a></p><h3>Consola</h3><h4>Creamos nuestra cuenta</h4><p>Antes de meternos a fondo en la aplicación, debemos de crearnos una cuenta en <a href="https://console.agora.io/">https://console.agora.io/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ip43U1eAmX9MZaT_" /></figure><h4>Creamos un Proyecto</h4><p>Una vez tengamos nuestra cuenta creada, ¡vamos a crear nuestro proyecto!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oAXPdTUHKpCSLamh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eFp9qRhlxTKwYM5V" /></figure><h4>Configuramos nuestro proyecto</h4><p>Una vez creado nuestro proyecto y cerrada la ventana que teníamos anteriormente, le damos a donde dice</p><p><strong>“config”</strong> -&gt; Bajamos a la sección de <strong>“Features”</strong> -&gt; ahí cliqueamos donde dice<strong> “Generate temp RTC Token”</strong>.</p><p>Una vez dentro, introducimos un <strong>“Channel name”</strong> como pueden ver en la imagen a continuación, y tocamos donde dice <strong>“Generate”</strong>.</p><p>Esto nos dará toda la información que vamos a necesitar para integrarlo en nuestra aplicación.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PQHQwhEs55fBWUyf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a3jLRSqmXwm16C6y" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GpUTNGxwcFeXvty8" /></figure><p><strong>Listo!</strong> Una vez creado y configurado nuestro proyecto podemos probar que nuestras credenciales funcionen correctamente desde esta web <a href="https://webdemo.agora.io/basicVideoCall/index.html">https://webdemo.agora.io/basicVideoCall/index.html</a> (aqui mismo ponemos los datos que nos brinda la consola y vemos que nos conectamos correctamente)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x2hvFH-yQHny3ulI" /></figure><p>No lo cierres, que lo vamos a necesitar para probar nuestra implementación desde la app.</p><h3>REACT NATIVE APP</h3><p>Teniendo una breve introducción sobre que es Agora y teniendo nuestro proyecto configurado. Vamos a implementar lo necesario para hacerla funcionar en nuestra app!</p><h3>Cómo funciona</h3><p>Este gráfico muestra cual es el flujo de trabajo para implementar esta funcionalidad en nuestra app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ueyauGHxPkO-f2SY" /><figcaption>Agora SDK workflow — made by Nicasource Team.</figcaption></figure><p>Tranquilos, no se asusten, vamos a verlo dentro de la app y se entenderá todo mucho más. Así que basta de tanta charla y pongámonos a programar.</p><h3>Preparando la app</h3><p>1- Creemos nuestro nuevo proyecto corriendo la siguiente línea en nuestra terminal (la línea incluye typescript en nuestro proyecto. No están obligados a usarlo, pero lo super recomiendo):</p><pre>npx react-native init ZoomTemeAnteNosotros - template react-native-template-typescript</pre><p>2- Nuestro proyecto está creado. ¡Probemos que todo haya salido correctamente!</p><p>Simplemente vayamos a nuestra carpeta recién creada desde nuestra terminal y corramos</p><pre>npx react-native run-android<br>npx react-native run-ios</pre><p>Si todo salió correctamente deberíamos estar viendo nuestra app corriendo en nuestro emulador.</p><p>3- Por último antes de arrancar con nuestra integración es agregar la librería a nuestro proyecto.</p><p>Tengamos en cuenta que para integrar el SDK tenemos que estar en la versión de React Native 0.60.0 o mayor.</p><h4>npm</h4><pre>npm i --save react-native-agora</pre><p><strong>yarn</strong></p><pre>// Instalamos yarn.<br>npm install -g yarn<br><br>// Descargamos el sdk de agora con yarn.<br>yarn add react-native-agora</pre><p>En el caso que estemos corriendo la app en iOS, ejecutemos la siguiente línea para instalar la librería correctamente:</p><pre>npx pod-install</pre><h4>Pequeño paso extra</h4><p>Video SDK usa módulos nativos escritos en Swift, por lo tanto nuestro proyecto tiene que soportar la compilación de archivos Swift, para eso vamos a crear el siguiente archivo File.swift:</p><p>En Xcode, abrimos ios/ZoomTemeAnteNosotros.xcworkspace</p><p>Click en File (archivo) &gt; New (nuevo) &gt; Swift File (archivo Swift), clickeamos en siguiente (next) &gt; Create (crear).</p><h3>¿Cómo implementarlo?</h3><h4>Importamos los módulos del SDK</h4><p>Borremos todo lo que se encuentra en nuestro <strong>App.tsx </strong>y ponemos lo siguiente:</p><pre>import React, {useRef, useState, useEffect} from &#39;react&#39;;<br>import {<br>    SafeAreaView,<br>    ScrollView,<br>    StyleSheet,<br>    Text,<br>    View,<br>} from &#39;react-native&#39;;<br>import {PermissionsAndroid, Platform} from &#39;react-native&#39;;<br>import {<br>    ClientRoleType,<br>    createAgoraRtcEngine,<br>    IRtcEngine,<br>    RtcSurfaceView,<br>    ChannelProfileType,<br>} from &#39;react-native-agora&#39;;</pre><h4>Importemos nuestras credenciales:</h4><p>Como vimos al principio de este artículo, hemos generado algunas credenciales para poder probar nuestra integración.</p><pre>const appId = &#39;&lt;--Insert app ID here--&gt;&#39;;<br>const channelName = &#39;&lt;--Insert channel name here--&gt;&#39;;<br>const token = &#39;&lt;--Insert authentication token here--&gt;&#39;;<br>const localUid = 0;<br><br>const App = () =&gt; {<br>   const agoraEngineRef = useRef&lt;IRtcEngine&gt;(); // Referencia a la instancia de Agora<br>   const [isJoined, setIsJoined] = useState(false); // Indicador de que estamos conectados<br>   const [remoteUid, setRemoteUid] = useState(0); // Uid del usuario remoto<br>  <br>   };<br><br>const styles = StyleSheet.create({<br>   button: {<br>       paddingHorizontal: 25,<br>       paddingVertical: 4,<br>       fontWeight: &#39;bold&#39;,<br>       color: &#39;#ffffff&#39;,<br>       backgroundColor: &#39;#0055cc&#39;,<br>       margin: 5,<br>   },<br>   main: {flex: 1, alignItems: &#39;center&#39;},<br> scroll: {flex: 1, backgroundColor: &#39;#ddeeff&#39;, width: &#39;100%&#39;},<br> scrollContainer: {alignItems: &#39;center&#39;},<br> videoView: {width: &#39;90%&#39;, height: 200},<br> btnContainer: {flexDirection: &#39;row&#39;, justifyContent: &#39;center&#39;},<br> head: {fontSize: 20},<br> info: {backgroundColor: &#39;#ffffe0&#39;, color: &#39;#0000ff&#39;}<br>});<br><br><br>export default App;</pre><h4>Permisos</h4><p>Dependiendo de la plataforma que estamos usando, vamos a tener que agregar lo siguiente para poder otorgar los permisos de la cámara y el micrófono.</p><p><strong>Android</strong><em><br></em>En nuestro <strong>App.tsx</strong> agregamos la siguiente función:</p><pre>const getPermission = async () =&gt; {<br>   if (Platform.OS === &#39;android&#39;) {<br>       await PermissionsAndroid.requestMultiple([<br>           PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,<br>           PermissionsAndroid.PERMISSIONS.CAMERA,<br>       ]);<br>   }<br>};</pre><p><strong>iOS</strong></p><p>En ios lo que tenemos que hacer es dirigiros al archivo <strong>info.plist </strong>y agregar estos dos valores</p><pre>NSMicrophoneUsageDescription<br>NSCameraUsageDescription</pre><p>Ahora, pongámosle algo de UI para poder probar la integración.</p><pre>return (<br>   &lt;SafeAreaView style={styles.main}&gt;<br>       &lt;Text style={styles.head}&gt;Agora Videollamadas Inicio Rapido&lt;/Text&gt;<br><br>       &lt;View style={styles.btnContainer}&gt;<br>           &lt;Text onPress={join} style={styles.button}&gt;<br>               Join<br>           &lt;/Text&gt;<br>           &lt;Text onPress={leave} style={styles.button}&gt;<br>               Leave<br>           &lt;/Text&gt;<br>       &lt;/View&gt;<br>       &lt;ScrollView<br>           style={styles.scroll}<br>           contentContainerStyle={styles.scrollContainer}&gt;<br>           {isJoined ? (<br>               &lt;React.Fragment key={0}&gt;<br>               &lt;RtcSurfaceView canvas={{uid: localUid}} style={styles.videoView} /&gt;<br>               &lt;Text&gt;Usuario local uid: {uid}&lt;/Text&gt;<br>               &lt;/React.Fragment&gt;<br>           ) : (<br>               &lt;Text&gt;Unirse al canal&lt;/Text&gt;<br>           )}<br>           {isJoined &amp;&amp; remoteUid !== 0 ? (<br>               &lt;React.Fragment key={remoteUid}&gt;<br>               &lt;RtcSurfaceView<br>                   canvas={{uid: remoteUid}}<br>                   style={styles.videoView}<br>               /&gt;<br>               &lt;Text&gt;Usuario remoto uid: {remoteUid}&lt;/Text&gt;<br>               &lt;/React.Fragment&gt;<br>           ) : (<br>               &lt;Text&gt;Esperando que un usuario remoto se una&lt;/Text&gt;<br>           )}<br>           &lt;Text style={styles.info}&gt;{message}&lt;/Text&gt;<br>       &lt;/ScrollView&gt;<br>   &lt;/SafeAreaView&gt;<br>);</pre><h4>Implementando la lógica de las llamadas</h4><p>Dentro de nuestro <strong>App.tsx</strong> vamos a pegar lo siguiente</p><pre>const setupVoiceSDKEngine = async () =&gt; {<br>   try {<br>   // usamos la funcion ya creada para obtener los permisos<br>   await getPermission();<br><br>   // Le damos el valor a nuestra instancia de Agora<br>   agoraEngineRef.current = createAgoraRtcEngine();<br>   const agoraEngine = agoraEngineRef.current;<br><br>   agoraEngine.registerEventHandler({<br>       onJoinChannelSuccess: () =&gt; {<br>       // Este es un listener que se ejecutará cada vez que nos conectemos a un canal correctamente.<br>           setIsJoined(true);<br>       },<br>       onUserJoined: (_connection, Uid) =&gt; {<br>          // Este es un listener que nos dirá cuando un usuario se conecta<br>           setRemoteUid(Uid);<br>       },<br>       onUserOffline: (_connection, Uid) =&gt; {<br>          // Este es un listener que nos dira cuando un usuario se desconecta<br>           setRemoteUid(0);<br>       },<br>   });<br>   agoraEngine.initialize({<br>       appId,<br>   });<br>   } catch (e) {<br>       console.log(e);<br>   }<br>};<br><br>useEffect(() =&gt; {<br>   // Inicializamos el motor de Agora cuando arranca la aplicación.<br>   setupVoiceSDKEngine();<br>}, []);</pre><h4>Unirse a un canal para comenzar la video llamada</h4><pre>const join = async () =&gt; {<br>   if (isJoined) {<br>     // Si ya nos encontramos en la llamada, no hacemos nada.<br>     return;<br>   }<br><br>   // Dejamos que la instancia de AGORA nos asigne el canal y nos una.<br>   try {<br>     agoraEngineRef.current?.setChannelProfile(<br>       ChannelProfileType.ChannelProfileCommunication,<br>     );<br>     agoraEngineRef.current?.startPreview();<br>     agoraEngineRef.current?.joinChannel(token, channel, localUid, {<br>       clientRoleType: ClientRoleType.ClientRoleBroadcaster,<br>     });<br>   } catch (e) {<br>     console.log(e);<br>   }<br> };</pre><h4>Abandonar un canal</h4><pre>const leave = () =&gt; {<br>   // Cuando deseamos salir del canal.<br>   try {<br>     agoraEngineRef.current?.leaveChannel();<br>     setIsJoined(false);<br>     setRemoteUid(0);<br>   } catch (e) {<br>     console.log(e);<br>   }<br> };</pre><h4>Probemos nuestra integración</h4><p>Es hora de correr la aplicación; personalmente les recomiendo que la corran en un dispositivo físico para no tener ningún problema ya que los emuladores no suelen funcionar super bien con estas librerías. Vamos a ingresar a la página anteriormente mencionada <a href="https://webdemo.agora.io/basicVideoCall/index.html">https://webdemo.agora.io/basicVideoCall/index.html</a> con nuestras credenciales donde podremos vernos a nosotros.</p><p>Si todo salió bien, y damos al botón de <strong>“Unirse al canal”</strong> deberíamos de poder vernos desde la app y desde la página.</p><p>Como ya vimos en nuestro ejemplo, la app funciona. Pero se ve medio precaria, ¿Qué tal si quiero mutear el micrófono? O si ¿Quiero cambiar la cámara? ¡Vamos a darle el estilo que se merece!</p><p>Let‘s go for it!</p><p>Antes que nada les recomiendo que agreguen estas dos librerias</p><ul><li><a href="https://github.com/th3rdwave/react-native-safe-area-context">https://github.com/th3rdwave/react-native-safe-area-context</a> (Nos dara un mejor uso sobre las Safe Areas de los dispositivos)</li><li><a href="https://www.npmjs.com/package/@sayem314/react-native-keep-awake">https://www.npmjs.com/package/@sayem314/react-native-keep-awake</a> (evitara que se apague la pantalla de la aplicación)</li></ul><p>Bien, ahora. Dentro de nuestro <strong>App.tsx</strong> haremos lo siguiente</p><pre>export default function App() {<br>  useKeepAwake();<br><br>  const agoraEngineRef = useRef&lt;IRtcEngine&gt;(); // Instancia de Agora<br><br>  const [isJoined, setIsJoined] = useState(false); // Indica si el usuario local se unio al canal<br>  const [isMute, setIsMute] = useState(false); // Indica si el usuario local se unio al canal<br><br>  const [remoteUid, setRemoteUid] = useState(0); // Uid of the remote user<br><br>  const getPermission = async () =&gt; {<br>    if (Platform.OS !== &#39;android&#39;) {<br>      // El info.plist es el que se ocupara del lado de iOS<br>      return;<br>    }<br><br>    // Pedimos los premisos adecuados para Android<br>    await PermissionsAndroid.requestMultiple([<br>      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,<br>      PermissionsAndroid.PERMISSIONS.CAMERA,<br>    ]);<br>  };<br><br>  const setupVideoSDKEngine = async () =&gt; {<br>    try {<br>      // Llamamos a los permisos<br>      await getPermission();<br><br>      // Le damos el valor a nuestra instancia de Agora<br>      agoraEngineRef.current = createAgoraRtcEngine();<br>      const agoraEngine = agoraEngineRef.current;<br><br>      agoraEngine.registerEventHandler({<br>        onJoinChannelSuccess: () =&gt; {<br>          // Este es un listener que se ejecutara cada vez que nos conectemos a un canal correctamente.<br>          setIsJoined(true);<br>        },<br>        onUserJoined: (_connection, Uid) =&gt; {<br>          // Este es un listener que nos dira cuando un usuario se conecta<br>          setRemoteUid(Uid);<br>        },<br>        onUserOffline: (_connection, _Uid) =&gt; {<br>          // Este es un listener que nos dira cuando un usuario se desconecta<br>          setRemoteUid(0);<br>        },<br>        onError: (errorCode, msg) =&gt; {<br>          console.log(&#39;Error Code&#39;, errorCode);<br>          console.log(&#39;Mesasge:&#39;, msg);<br>        },<br>      });<br>      agoraEngine.initialize({<br>        appId,<br>      });<br>      agoraEngine.enableVideo();<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  const join = async () =&gt; {<br>    if (isJoined) {<br>      // Si ya nos encontramos en la llamada, no hacemos nada.<br>      return;<br>    }<br><br>    // Dejamos que la instancia de AGORA nos asigne el canal y nos una.<br>    try {<br>      agoraEngineRef.current?.setChannelProfile(<br>        ChannelProfileType.ChannelProfileCommunication,<br>      );<br>      agoraEngineRef.current?.startPreview();<br>      agoraEngineRef.current?.joinChannel(token, channel, localUid, {<br>        clientRoleType: ClientRoleType.ClientRoleBroadcaster,<br>      });<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  const leave = () =&gt; {<br>    // Cuando deseamos salir del canal.<br>    try {<br>      agoraEngineRef.current?.leaveChannel();<br><br>      // setRemoteUids([]);<br>      setIsJoined(false);<br>      setIsMute(false);<br><br>      setRemoteUid(0);<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  const muteMic = () =&gt; {<br>    try {<br>      agoraEngineRef.current?.muteLocalAudioStream(!isMute);<br><br>      setIsMute(!isMute);<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  const switchCamera = () =&gt; {<br>    try {<br>      agoraEngineRef.current?.switchCamera();<br>    } catch (e) {<br>      console.log(e);<br>    }<br>  };<br><br>  useEffect(() =&gt; {<br>    // Inicializamos el motor de Agora cuando inicia la app<br>    setupVideoSDKEngine();<br><br>    // eslint-disable-next-line react-hooks/exhaustive-deps<br>  }, []);<br><br>  useEffect(() =&gt; {<br>    console.log(isJoined);<br>  }, [isJoined]);<br><br>  return (<br>    &lt;SafeAreaProvider&gt;<br>      &lt;View style={styles.container}&gt;<br>        {isJoined ? (<br>          &lt;ActiveCall<br>            localUid={localUid}<br>            remoteUid={remoteUid}<br>            isMute={isMute}<br>            onMuteMicPress={muteMic}<br>            onSwitchCameraPress={switchCamera}<br>            onLeavePress={leave}<br>          /&gt;<br>        ) : (<br>          &lt;InactiveoCall onJoinChannelPress={join} /&gt;<br>        )}<br>      &lt;/View&gt;<br>    &lt;/SafeAreaProvider&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>  },<br>});</pre><p>Bien, se preguntarán de donde salieron <strong>&lt;ActivaCall /&gt;</strong> e <strong>&lt;InactivaCall /&gt;</strong>. Estos dos serán componentes separados que nos ayudarán para mostrar las cosas un poco más prolijas, así que vamos a crearlos.</p><p>Primero que nada creamos una carpeta en nuestro proyecto que se llama <strong>“src”</strong> y dentro de ella otra carpeta más que se llama <strong>“components” </strong>para darle un poquito más de organización al proyecto.</p><p>Dentro de components vamos a crear dos archivos nuevos</p><p><strong>ActiveCall.tsx</strong></p><pre>import React from &#39;react&#39;;<br>import {Image, Pressable, StyleSheet, Text, View} from &#39;react-native&#39;;<br>import {RtcSurfaceView} from &#39;react-native-agora&#39;;<br>import {useSafeAreaInsets} from &#39;react-native-safe-area-context&#39;;<br><br>export default function ActiveCall({<br>  localUid,<br>  remoteUid,<br>  isMute,<br>  onSwitchCameraPress,<br>  onMuteMicPress,<br>  onLeavePress,<br>}: {<br>  localUid: number;<br>  remoteUid: number;<br>  isMute: boolean;<br>  onMuteMicPress: () =&gt; void;<br>  onSwitchCameraPress: () =&gt; void;<br>  onLeavePress: () =&gt; void;<br>}) {<br>  const insets = useSafeAreaInsets();<br>  return (<br>    &lt;View style={styles.container}&gt;<br>      {/* Remote user preview */}<br>      {remoteUid !== 0 ? (<br>        &lt;RtcSurfaceView<br>          canvas={{uid: remoteUid}}<br>          style={styles.remoteVideoView}<br>        /&gt;<br>      ) : (<br>        &lt;View&gt;<br>          &lt;Text&gt;Esperando a que alguien se una….&lt;/Text&gt;<br>        &lt;/View&gt;<br>      )}<br><br>      {/* Local user preview */}<br>      &lt;RtcSurfaceView<br>        canvas={{uid: localUid}}<br>        style={<br>          remoteUid === 0<br>            ? styles.remoteVideoView //Mostramos la cámara full size si no hay nadie           : [styles.localVideoView, {bottom: insets.bottom + 100}] // En el caso que haya un usuario unido, vamos a darle un estilo pequeño        }<br>      /&gt;<br>      &lt;View style={[styles.actionsContainer, {bottom: insets.bottom}]}&gt;<br>        {/* Boton para silenciar */}<br>        &lt;Pressable<br>          style={styles.actionButtonContainer}<br>          onPress={onMuteMicPress}&gt;<br>          &lt;Image<br>            style={styles.actionButtonImage}<br>            source={<br>              isMute<br>                ? require(&#39;../../assets/icons/ic_mute.png&#39;)<br>                : require(&#39;../../assets/icons/ic_unmute.png&#39;)<br>            }<br>            resizeMode=&quot;contain&quot;<br>          /&gt;<br>        &lt;/Pressable&gt;<br><br>        {/* Boton para cerrar la llamada */}<br>        &lt;Pressable style={styles.leaveButtonContainer} onPress={onLeavePress}&gt;<br>          &lt;Image<br>            style={styles.leaveButtonImage}<br>            source={require(&#39;../../assets/icons/ic_phone.png&#39;)}<br>            resizeMode=&quot;contain&quot;<br>          /&gt;<br>        &lt;/Pressable&gt;<br><br>        {/* Boton para cambiar la camara */}<br>        &lt;Pressable<br>          style={styles.actionButtonContainer}<br>          onPress={onSwitchCameraPress}&gt;<br>          &lt;Image<br>            style={styles.actionButtonImage}<br>            source={require(&#39;../../assets/icons/ic_camera.png&#39;)}<br>            resizeMode=&quot;contain&quot;<br>          /&gt;<br>        &lt;/Pressable&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>}<br><br>const styles = StyleSheet.create({<br>  container: {<br>    flex: 1,<br>    backgroundColor: &#39;white&#39;,<br>  },<br>  localVideoView: {<br>    overflow: &#39;hidden&#39;,<br>    position: &#39;absolute&#39;,<br>    right: 10,<br>    height: 200,<br>    width: 150,<br>    borderRadius: 10,<br>    borderWidth: 2,<br>    borderColor: &#39;white&#39;,<br>  },<br>  remoteVideoView: {<br>    flex: 1,<br>  },<br>  actionsContainer: {<br>    position: &#39;absolute&#39;,<br>    flexDirection: &#39;row&#39;,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;space-between&#39;,<br>    paddingHorizontal: 30,<br>    bottom: 10,<br>    left: 0,<br>    right: 0,<br>  },<br>  leaveButtonContainer: {<br>    width: 70,<br>    height: 70,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>    padding: 10,<br>    borderRadius: 40,<br>    backgroundColor: &#39;red&#39;,<br>  },<br>  actionButtonContainer: {<br>    width: 50,<br>    height: 50,<br>    alignItems: &#39;center&#39;,<br>    justifyContent: &#39;center&#39;,<br>    padding: 10,<br>    borderRadius: 40,<br>    backgroundColor: &#39;#000000CC&#39;,<br>  },<br>  leaveButtonImage: {<br>    width: 35,<br>    height: 35,<br>    tintColor: &#39;white&#39;,<br>  },<br>  actionButtonImage: {<br>    width: 25,<br>    height: 25,<br>    tintColor: &#39;white&#39;,<br>  },<br>});</pre><p><strong>InactiveCall.tsx</strong></p><pre>import React from &#39;react&#39;;<br>import {Pressable, StyleSheet, Text} from &#39;react-native&#39;;<br>import {SafeAreaView} from &#39;react-native-safe-area-context&#39;;<br><br>export default function InactiveoCall({<br> onJoinChannelPress,<br>}: {<br> onJoinChannelPress: () =&gt; void;<br>}) {<br> return (<br>   &lt;SafeAreaView style={styles.container}&gt;<br>     &lt;Pressable style={styles.buttonContainer} onPress={onJoinChannelPress}&gt;<br>       &lt;Text style={styles.buttonText}&gt;Unirme al canal -&amp;gt;&lt;/Text&gt;<br>     &lt;/Pressable&gt;<br>   &lt;/SafeAreaView&gt;<br> );<br>}<br><br>const styles = StyleSheet.create({<br> container: {<br>   flex: 1,<br>   alignItems: &#39;center&#39;,<br>   justifyContent: &#39;center&#39;,<br>   backgroundColor: &#39;#491A85&#39;,<br> },<br> contentContainer: {<br>   flex: 1,<br> },<br> buttonContainer: {<br>   alignItems: &#39;center&#39;,<br>   justifyContent: &#39;center&#39;,<br>   paddingHorizontal: 20,<br>   paddingVertical: 14,<br>   borderTopStartRadius: 10,<br>   borderBottomStartRadius: 30,<br>   borderTopEndRadius: 30,<br>   borderBottomEndRadius: 10,<br>   backgroundColor: &#39;#3BE261&#39;,<br> },<br> buttonText: {<br>   fontSize: 20,<br>   fontWeight: &#39;700&#39;,<br>   color: &#39;#DDFDE5&#39;,<br> },<br>});</pre><p>Y LISTO! Si todo sale bien deberían de estar viendo esto:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*r0azWz-hWgRju4xB" /></figure><p><em>Para las imagenes les recomiendo que entren a Flaticon.com y busquen ahí las que más le gusten. Una vez descargadas, crean en su proyecto una nueva carpeta llamada “assets” y dentro de ella “icons”</em></p><p>Cualquier cosa pueden observar el el repo de github.</p><p>(<a href="https://github.com/Alancito-Antar/agora-sdk-tutorial/tree/main">https://github.com/Alancito-Antar/agora-sdk-tutorial/tree/main</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9617e55fe67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/como-crear-una-aplicaci%C3%B3n-de-videollamadas-e9617e55fe67">Como crear una aplicación de videollamadas</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mentalidad del tester]]></title>
            <link>https://medium.com/nicasource/mentalidad-del-tester-f885e6f6bd73?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/f885e6f6bd73</guid>
            <category><![CDATA[testers]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mindset]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[qa-testing]]></category>
            <dc:creator><![CDATA[Jennyffer Solorzano]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 19:02:05 GMT</pubDate>
            <atom:updated>2022-11-23T19:02:05.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbSpcjmefPrfmtKJk5RLDw.png" /></figure><p>Esta imagen es perfecta para introducir el tema, dice mucho ¡Y lo sabes!</p><p>Si te preguntaran ¿Cuál es la principal diferencia entre un tester y un programador?, además de la diferencia obvia; el programador diseña y construye un producto y el tester verifica, valida, encuentra defectos en el mismo ¿Qué responderías?</p><p>Te diría que, una, es la habilidad de pensar que algo puede salir mal. Y no por ser el “pájaro de mal agüero” si no porque el tester inyecta la curiosidad de saber que pasa si: “toco aquí y allá, si escribo esto y no aquello”; haciendo preguntas que tal vez nadie ha hecho y pueden sonar “rebuscadas”. Además el programador tiene el sesgo de confirmación que le dificultará ver los errores en lo propio.</p><p>El pensamiento crítico es una habilidad que también distingue al tester y se debe ir cultivando y desarrollando. Y no se trata de llevar la contraria por hacerlo, nuestro fin es siempre ir de la mano con todo el equipo, comprometidos en entregar un producto de calidad y en hacer la experiencia del usuario lo mejor posible.</p><p>Cómo mencioné antes el programador tiene el sesgo de confirmación, y no sólo le impide ser juez y parte a la hora de validar también le crea “conexión” con lo programado con su conocimiento y esfuerzo; esto hace que cualquier observación pueda ser tomada cómo una crítica de connotación personal. En muchas ocasiones el testing es visto cómo una actividad destructiva, aunque aporte mucho al progreso de cualquier proyecto y a su calidad.</p><p>El testing no se trata sólo de encontrar errores y mostrarlos, el testing busca asegurar que el proceso completo de desarrollo se haga con calidad y es importante siempre dejarlo claro al equipo. Que estamos enfocados en el mismo objetivo global, que somos parte de la solución y no del problema.</p><h4>Empatía</h4><p>La empatía con el cliente inicia desde que te pones en su posición y te involucras de lleno con sus procesos y productos; abriendo nuestros sentidos a cada detalle, observando, averiguando, conociendo el negocio, proponiendo oportunidades de mejora. Asumís que el objetivo es un producto usable, que le facilite la vida y haga lo que él espera y hasta un poquito más: que sea un cliente feliz.</p><p>La empatía con el equipo de trabajo es vital para mantener el objetivo de calidad no sólo en el producto, además en el proceso. Conforme vamos trabajando vamos conociendo más de las personas con las que trabajamos: sus actitudes, aptitudes y cómo se relacionan. Creamos relaciones fuertes en el equipo. No somos robots y esto es parte de la esencia humana y del trabajo en equipo. Y es aquí dónde entra otra habilidad importante para un tester: saber comunicar; y no sólo la debemos usar en el <strong>qué</strong> comunicamos, si no el <strong>cómo.</strong> La empatía ayuda mucho a lograrlo con éxito.</p><p>Al ser humanos, no siempre los ánimos individuales van a ser los más óptimos o en el equipo la comunicación fluirá a cómo esperamos. Es el desafío que cómo tester nos toca asumir; comunicar los resultados de pruebas en un tono neutro evitando la crítica personal enfocados en que estamos buscando la mejor solución y empatizar nos hará reflexionar antes en cómo se sienten los otros y las razones que podrían hacer tomen a mal cierta información.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVvkvDXPuS29IGmrlNQ8mw.png" /></figure><p>Estas habilidades se van desarrollando conforme vas ganando experiencia, pero también puedes pedir ayuda, leer, hablar con otras personas; y no digo que sólo con otros tester porque de todas las personas podemos obtener algo que va abonando a agudizar estas habilidades. El testing es cómo un proceso social, para potenciarte en un proyecto se necesita más que conocer herramientas, programar o escribir casos de prueba.</p><p>Las pruebas están en tu cabeza y es ahí dónde debes comenzar a estudiar y practicar para lograr pruebas con mayor alcance. Coméntame cómo desarrollaste tú, la mentalidad de tester.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f885e6f6bd73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/mentalidad-del-tester-f885e6f6bd73">Mentalidad del tester</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tipos y niveles de prueba]]></title>
            <link>https://medium.com/nicasource/tipos-y-niveles-de-prueba-1a276651a60d?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/1a276651a60d</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[niveles-de-pruebas]]></category>
            <category><![CDATA[tipos-de-pruebas]]></category>
            <dc:creator><![CDATA[Jennyffer Solorzano]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 19:01:58 GMT</pubDate>
            <atom:updated>2022-11-18T19:01:58.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gbUIDlakfWn9m8Mlrwd-A.png" /></figure><p>Si acabas de comenzar el viaje como tester, este artículo tiene la intención de darte algo de luz sobre un tema que puede parecer bastante confuso: los tipos y niveles de prueba. Al “googlear’’ tipos de pruebas te aparecen listas dónde no logras diferenciar entre tipo y nivel y llega a crear desconocimiento en un tema bastante fundamental en el mundo testing.</p><p>Hasta el momento hay dos listas de estándares internacionales que tratan de orientarnos sobre los tipos de pruebas:</p><ul><li>La <a href="https://iso25000.com/index.php/en/iso-25000-standards/iso-25010">ISO/IEC 25010</a> estándar que define ocho características de calidad y a partir de estas los tipos de pruebas para validarlas. La ISO 25010 no agrupa los tipos según el objetivo y tampoco nos ofrece niveles de prueba.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsVeq8Nn3hukPjtMAPfZJw.png" /></figure><ul><li>El ISTQB (International Software Testing Qualifications Board) es el estándar internacional que se ha venido especializando en el campo de la certificación de pruebas, hace diferencia entre niveles y tipos y serán estos los ahondados en esta entrega.</li></ul><h3>Niveles de Prueba</h3><p>“Son grupos de actividades de pruebas que se organizan y administran juntas; cada nivel es una instancia en el proceso de pruebas” (ISTQB-CTFL Syllabus 2018 v3.1.1, p. 30) y son 4:</p><h4>Pruebas de Componentes</h4><p>Conocidas cómo pruebas unitarias, son las que están enfocadas en componentes que pueden ser probados de forma separada y son hechas usualmente por los programadores. Son excelentes candidatas a automatizarse y hechas de forma separada del resto del sistema. Algunos de los objetos de pruebas en este nivel son: código, estructura de datos, clases, módulo de bases de datos.</p><h4>Pruebas de Integración</h4><p>Son las pruebas que están enfocadas en la interacción entre los componentes o los sistemas, por tanto se subdividen en:</p><ol><li>Integración de componentes: prueba la interacción e interfaces entre los componentes, son hechas luego de las pruebas de componentes y son perfectas candidatas a automatizar.</li><li>Integración de sistemas: prueba la interacción e interfaz entre los sistemas, paquetes y microservicios. Además puede cubrir la interacción del sistema con interfaces que proveen sistemas externos. Estas pruebas se pueden hacer luego de las pruebas de sistemas o en paralelo.</li></ol><p>Algunos de los objetos de prueba en este nivel son: subsistemas, base de datos, interfaces, API’s, microservicios. En estas pruebas nos debemos enfocar en la comunicación entre módulos o sistemas; por ejemplo: desajuste de la interfaz, datos incorrectos o faltantes, suposiciones incorrectas de términos o unidades de datos que se transmiten entre los sistemas.</p><h4>Pruebas de Sistemas</h4><p>Se centran en el funcionamiento y capacidades de un sistema/producto completo, se consideran todas las tareas que el sistema puede realizar y los comportamientos no funcionales que muestra mientras cumple con estas tareas. Entre los principales objetivos de las pruebas de sistema tenemos:</p><ul><li>reducir el riesgo,</li><li>verificar si el comportamiento funcional y no funcional del sistema son los diseñados y especificados,</li><li>encontrar defectos,</li><li>validar que el sistema está completo y trabaja como se esperaba;</li><li>y en dependencia del tipo de sistema se debe validar la calidad de los datos.</li></ul><p>Los objetos de prueba son aplicaciones y sistemas enteros.</p><h4>Pruebas de Aceptación</h4><p>Al igual que las pruebas de sistema se centran en el comportamiento y capacidades de un sistema/producto completo y entre sus principales objetivos están: establecer confianza en la calidad del sistema completo, validar que el sistema está completo y trabaja como se esperaba. Estas pruebas producen la información para evaluar el despliegue y uso del cliente. Se pueden encontrar defectos pero no es el objetivo de estas pruebas, si se encuentran muchos defectos en este nivel se considera como un gran riesgo para el proyecto. Las formas más comunes de pruebas de aceptación son:</p><ol><li>Pruebas de aceptación de usuario (UAT): se enfocan en validar si el sistema se adapta al usuario final en un entorno operativo real o simulado.</li><li>Pruebas de aceptación operacional: son hechas por los usuarios administradores del sistema en un ambiente simulado de producción. Se enfocan en aspectos operacionales cómo: probar el respaldo y recuperación; instalación, actualización y desinstalación; administración de usuario y tareas de mantenimiento. Pero el principal objetivo es darle confianza, a los operadores o administradores del sistema, de que este se mantendrá trabajando apropiadamente en una ambiente operacional con condiciones excepcionales e inesperadas.</li><li>Pruebas de aceptación contractuales y regulatorias: son realizadas contra los criterios de aceptación de un contrato para producir software hecho a medida, los criterios de aceptación deben ser definidos cuándo las partes están de acuerdo con el contrato.</li><li>Pruebas de aceptación Alfa y Beta: son usadas por programadores de software comercial listo para usarse; que desean obtener comentarios de los usuarios, clientes u operadores potenciales antes de poner el software en el mercado.</li><li>Los objetos de prueba en este nivel son, principalmente; sistemas en pruebas, procesos de negocio, reportes, entre otros. Las pruebas de aceptación son responsabilidad de los clientes/product owners.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzqE4a70vjCQPDP-I-fvMQ.png" /></figure><h3>Tipos de Pruebas</h3><p>“Un tipo de prueba es un grupo de actividades de prueba destinadas a probar características específicas de un sistema de software, o una parte de un sistema, en función de objetivos de prueba específicos.” (ISTQB-CTFL Syllabus 2018 v3.1.1, p. 39). Entre los principales objetivos de los tipos de prueba están: evaluar la calidad de las características funcionales y no funcionales; evaluar si la estructura o arquitectura del componente/sistema está completa y conforme las especificaciones; evaluar los efectos de los cambios así como validar que los defectos encontrados fueron corregidos. Los tipos de pruebas son:</p><h4>Pruebas Funcionales</h4><p>Podríamos decir que son las más conocidas y mencionadas en el mundo testing, básicamente son las pruebas que validan las funciones que el sistema debe hacer. Las pruebas funcionales, esencialmente, validan el “qué” debe hacer el componente/sistema. Se deberían hacer en todos los niveles de prueba, aunque el foco es distinto en cada uno.</p><h4>Pruebas no Funcionales</h4><p>Las pruebas no funcionales de un sistema evalúan las características cómo usabilidad, rendimiento, eficiencia o seguridad. Las pruebas no funcionales son las encargadas de validar el “qué tan bien” el sistema se comporta. Contrario a lo que se piensa las pruebas no funcionales deben hacerse en todos los niveles de prueba y realizarse lo antes posible. Las pruebas no funcionales podrían requerir conocimientos especiales para poder ejecutarlas.</p><h4>Pruebas de Caja Blanca</h4><p>Las pruebas de caja blanca son las que validan la estructura interna del sistema. Esta estructura interna puede incluir el código, arquitectura, flujo de trabajo y flujo de datos dentro del sistema. En el nivel de Componente de Pruebas la cobertura de código está basada en el porcentaje de componentes que han sido probados. Para diseñar y ejecutar las pruebas de caja blanca es necesario tener conocimiento sobre cómo fue construido el código, cómo están guardados los datos, entre otros.</p><h4>Pruebas Asociadas al Cambio</h4><p>Cuándo son hechos cambios al sistema, ya sea por corregir un defecto o por una nueva o cambiante funcionalidad se deben hacer pruebas para verificar que los cambios han corregido el defecto o han implementado correctamente la funcionalidad y que no han causado consecuencias adversas.</p><ol><li>Pruebas de Confirmación: Luego que un defecto es corregido, el sistema se debe probar ejecutando todos los casos de prueba fallidos asociados al defecto; estos deben ser reprobados en la nueva versión del software. El propósito de las pruebas de confirmación es validar que el defecto original ha sido corregido de forma exitosa.</li><li>Pruebas de regresión: Es posible que los cambios hechos en una parte del código, ya sea una corrección u otro tipo de cambio, accidentalmente podrían cambiar el comportamiento de otras partes del software ya sea dentro del mismo componente, otros componentes del sistema e incluso en otros sistemas. Las pruebas de regresión validan que no se generaron nuevos defectos. Estas pruebas suelen ejecutarse luego de un traslado de ambiente (producción o pruebas), nueva versión del sistema operativo o incluso si el programador comunica que el cambio realizado podría afectar otros módulos ya probados. Podemos ejecutar un set de casos de pruebas específico para estos escenarios, ejecutar los mismos que se ejecutaron previamente o seleccionar los que abarcan las funcionalidades importantes del componente/sistema, esto se especificará más adelante.</li></ol><p>Las pruebas de confirmación y regresión se deberían ejecutar en todos los niveles de prueba, especialmente en ciclos de desarrollo incrementales e interactivos, estas pruebas son excelentes candidatas para automatizar.</p><p>Es importante hacer mención a las pruebas de humo y sanidad que muchas veces las encontramos listadas como tipos de pruebas, pero basados en el listado que ofrece el ISTQB no son un tipo particular de pruebas, ambas son pruebas rápidas para verificar la estabilidad de una versión del software; están dentro de las calificaciones dadas.</p><p>Las pruebas de humo son pruebas funcionales que consisten en hacer una validación inicial de la calidad del producto; pasando por las funcionalidades básicas/importantes dónde se prueba de todo un poco de forma rápida, una vez validamos está estable la versión se procede con la ejecución de todos los casos de prueba planeados.</p><p>Las pruebas de sanidad son pruebas asociadas a cambios; que se encargan de validar de forma rápida pero certera que ciertas funcionalidades nuevas o que han sufrido cambios están funcionando correctamente. Si en el proyecto se tiene el alcance de hacer pruebas en producción, luego de un despliegue, se validan las nuevas funcionalidades que se trabajaron en la iteración y luego se hace una “barrida” al resto de funcionalidades básicas de la aplicación.</p><p>Estos son los tipos y niveles de pruebas que plantea el ISTQB, cómo un referente del testing internacional; tratan de llenar el vacío que ha generado este tema a lo largo de los años en que se ha venido descubriendo y desarrollando el área de pruebas de software. No distan mucho de los que menciona la norma ISO 25010, que de hecho están contenidos en los tipos de pruebas funcionales y no funcionales.</p><p>Cuéntame ¿Cuáles de estos tipos o niveles ya conocías? ¿Cuáles son los que has elaborado? ¿Crees que la clasificación dada está completa?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a276651a60d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/tipos-y-niveles-de-prueba-1a276651a60d">Tipos y niveles de prueba</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[¿Qué es el Cuadrante de Pruebas Ágiles?]]></title>
            <link>https://medium.com/nicasource/qu%C3%A9-es-el-cuadrante-de-pruebas-%C3%A1giles-3b02c4ef6db0?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/3b02c4ef6db0</guid>
            <dc:creator><![CDATA[Lgarciacantillano]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 19:02:37 GMT</pubDate>
            <atom:updated>2022-11-11T19:02:37.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY5sxrVE_uDAGK5gPBf7tg.png" /></figure><h3>Introducción</h3><p>Anteriormente hablamos de <strong>La Pirámide de Pruebas</strong>, al igual que ella el <strong>Cuadrante de Pruebas</strong> <strong>Ágiles </strong>es una herramienta visual, pero mientras que la primera ayuda a ordenar las pruebas a realizar en la aplicación, el segundo ayuda a responder la pregunta ¿Qué<em> pruebas puedo realizar a la aplicación?.</em></p><p>El cuadrante de pruebas fue originalmente publicado por Brian Marick en 2003 como parte de una serie de artículos sobre Testeo Ágil y originalmente fue conocido como “Matriz de pruebas de Marick” (Marick Test Matrix”).</p><h3>El cuadrante de Pruebas Ágiles</h3><p>Los ejes de la matriz de Marick están divididos de la siguiente manera:</p><p>Eje de las abscisas:</p><ul><li><em>Pruebas que soportan al equipo: </em>son pruebas para apoyar al equipo mientras desarrollan el producto.</li><li><em>Pruebas que critican el producto:</em> son pruebas para revisar el software de una manera constructiva, con la meta de aprender como lo podemos mejorar. Mientras aprendemos, podemos incorporar nuevos requerimientos, pruebas, o ejemplos al proceso de desarrollo.</li></ul><p>Eje de las ordenadas:</p><ul><li><em>Pruebas orientadas a la tecnología: </em>son pruebas realizadas a bajo nivel, incluyendo a nivel de código y se utilizan en el proceso de desarrollo.</li><li><em>Pruebas orientadas al negocio: </em>son pruebas realizadas a alto nivel que se realizan para verificar que se cumplen los requerimientos del negocio.</li></ul><p>La intercepción de estos 2 ejes divide nuestra matriz en cuatro cuadrantes y es a lo que conocemos como <strong><em>El Cuadrante de Pruebas Ágiles</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lb8ckWbn01GSmyOEiXF8Zg.png" /><figcaption>Matriz de Marick</figcaption></figure><h3>Cuadrante uno (Q1)</h3><p>Este cuadrante comprende la práctica del <strong>Desarrollo Orientado a Pruebas</strong> (Test Driven Development — TDD). Las pruebas unitarias verifican la funcionalidad de pequeños subconjuntos del sistemas, mientras que las pruebas de componentes verifican el comportamiento de partes más grandes del sistema, tal como grupos de clases que proveen algún servicio. Ambos tipos de pruebas son normalmente automatizadas.</p><h3>Cuadrante dos (Q2)</h3><p>Este grupo de pruebas también son para apoyar el desarrollo del producto pero desde un nivel más alto. Estas pruebas orientadas al negocio se ejecutan a nivel funcional y cada una verifica que se cumpla una condición de negocio para garantizar la calidad externa y las características que los clientes desean.</p><h3>Cuadrante tres (Q3)</h3><p>Las pruebas de aceptación del usuario (UAT), la usabilidad y las pruebas exploratorias pertenecen a este cuadrante. Estos implican pruebas manuales por parte de ingenieros de control de calidad experimentados y pruebas de usuarios finales. Su objetivo aquí es obtener comentarios y mejorar la calidad del producto, asegurándose de que se ajuste al propósito diseñado.</p><h3>Cuadrante cuatro (Q4)</h3><p>Las pruebas en este cuadrante pretenden criticar características del producto tales como el performance, la robustez, y la seguridad. Estas pruebas son principalmente apoyadas por herramientas.</p><p>Los cuadrantes ayudan al equipo a visualizar cuales son los tipos de pruebas que se requieren para verificar que el producto cumpla con todas las expectativas de los exigentes usuarios a los que se enfrentará y aunque no en todos los casos se debe cumplir con todos los tipos de pruebas de todos los cuadrantes, estas pruebas no se omitirán por desconocimiento, si el equipo maneja con destreza el cuadrante de pruebas ágiles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b02c4ef6db0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/qu%C3%A9-es-el-cuadrante-de-pruebas-%C3%A1giles-3b02c4ef6db0">¿Qué es el Cuadrante de Pruebas Ágiles?</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creando pruebas BDD en Flutter]]></title>
            <link>https://medium.com/nicasource/creando-pruebas-bdd-en-flutter-d83ffee8d653?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/d83ffee8d653</guid>
            <dc:creator><![CDATA[Roger Sanchez]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 19:02:48 GMT</pubDate>
            <atom:updated>2022-11-10T19:02:48.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zPyNeJHRea7JCGjypLoSw.png" /></figure><p>Para este nuevo post estaremos hablando un poco acerca de las pruebas BDD (Behavior Driven Developer ) un lenguaje que nos permitirá describir el comportamiento de la aplicación a desarrollar. BDD es una estrategia de desarrollo que fomenta el trabajo entre el desarrollador y el usuario final del proyecto, por lo cual las pruebas se enfocan en el cumplimiento de la capa de negocio.</p><p>Para representar los requerimientos de las pruebas BDD haremos uso de Gherkins, este es un Lenguaje Específico de Dominio (DSL) que permitirá definir los criterios de aceptación.</p><p>En este post veremos el funcionamiento de BDD en Flutter con un sencillo ejemplo.</p><p>Así que, mano a la obra</p><p>Antes de ir al código, abordaremos un poco más de información acerca de Gherkins. Cada lenguaje tiene su palabras reservadas y Gherkins no es la excepción, este lenguaje trabaja bajo el patrón “Given, When,Then ”, a continuación explicaremos el funcionamiento de esta palabra con ejemplo un ejemplo:</p><blockquote><strong>Feature: Acceder al sistema</strong></blockquote><blockquote><strong># El primer ejemplo tiene tres pasos</strong></blockquote><blockquote><strong>Scenario: El usuario se inicia sesión en el sistema</strong></blockquote><blockquote><strong>Give: El usuario está en la pantalla principal</strong></blockquote><blockquote><strong>When: El usuario escribe la credenciales correctamente</strong></blockquote><blockquote><strong>Then: El usuario accede al funcionamiento de la aplicación</strong></blockquote><blockquote><strong>Las palabras clave especifican los siguiente:</strong></blockquote><blockquote><strong>Feature: Título de la prueba a realizar .</strong></blockquote><blockquote><strong>Scenario: Descripción del escenario a realizar.</strong></blockquote><blockquote><strong>Given: Información del estado Inicial.</strong></blockquote><blockquote><strong>When: Acción a realizar.</strong></blockquote><blockquote><strong>Then: Resultado esperado.</strong></blockquote><p>Ahora crearemos un nuevo proyecto en flutter y luego nos iremos al <strong>pub.yaml </strong>para instalar la siguiente librería que nos ayudará a implementar BDD en nuestro proyecto.</p><p><a href="https://pub.dev/packages/flutter_gherkin/install">flutter_gherkin | Flutter Package</a></p><p>Esta sería la estructura que estaremos usando, como ejemplo haremos uso del proyecto que nos ofrece Flutter al iniciar una nueva aplicación.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*eGodJ7RoquMO_adW" /></figure><p>En el archivo <strong>app.dart</strong> dentro de la carpeta <strong>test_driver</strong> definiremos la pantalla a la que realizaremos pruebas, en este caso importamos la clase <strong>MyApp(),</strong> el código se vería de la siguiente manera:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5278b7f55d4f1268e34ac740c1cba42/href">https://medium.com/media/f5278b7f55d4f1268e34ac740c1cba42/href</a></iframe><p><strong>EnableFlutterDriverExtension();</strong></p><p>Esta línea permitirá ejecutar la aplicación.</p><p>Ahora pasaremos a definir los escenarios que realizaremos pruebas, para el ejemplo crearemos un escenario relacionado al incremento de un contador, para esto iremos a la carpeta <strong>feature</strong> dentro de <strong>test_driver</strong> y crearemos un archivo con el nombre <strong>increment_counter.feature</strong>, el código sería el siguiente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5c08d475aba9a6b01ed1fbde49567f4/href">https://medium.com/media/f5c08d475aba9a6b01ed1fbde49567f4/href</a></iframe><p>Para que esta prueba muestre una interacción con la pantalla, deberemos colocar un Key a cada unos de los widget de los que haremos uso, para este ejemplo estamos haciendo uso de estos widgets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65fe109eedb8378a279923ef2916ef1f/href">https://medium.com/media/65fe109eedb8378a279923ef2916ef1f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3792636450a5b55dd7ee70933c6e7f7d/href">https://medium.com/media/3792636450a5b55dd7ee70933c6e7f7d/href</a></iframe><p><strong>Procederemos a explicar cada uno de los pasos detallados en el escenario en el archivo increment_counter.feature.</strong></p><p><strong>Paso 1: Given I expect the “counter” to be “0&quot;</strong></p><p>Este paso comprobará que “<strong>counter”</strong>esté en el key de un widget y que este refleje el valor de cero, una vez definido el paso pasaremos a la implementación de este, pero en esta ocasión no será necesario porque ya está incorporado en la librería de <strong>flutter_gherkin</strong>.</p><p><strong>Paso 2: When I tap the “Increment” button 10 times.</strong></p><p>El siguiente paso decimos que se pulsara 10 veces el botón y una vez esta acción termine el widget <strong>Text</strong> deberá de mostrar el valor de 10 en pantalla.</p><p>Ahora pasaremos explicar la implementación de este paso, iremos a la carpeta <strong>test_driver</strong> y crearemos un archivo dentro del directorio de <strong>step</strong> que pondremos por nombre <strong>increment_button_step.dart</strong>, este contendrá la siguiente información:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a574e3ce1f5c215062a2562b4c132d50/href">https://medium.com/media/a574e3ce1f5c215062a2562b4c132d50/href</a></iframe><p>como puedes ver el método <strong>tapButtonStep() </strong>implementa a <strong>when2</strong> que especifica 3 tipos de parámetros a recibir, el primer parámetro “<strong>key”</strong> representaría al widget que estamos utilizando, el segundo “<strong>count”</strong> la veces que se realizará el evento click y el tercero “<strong>context”</strong> que permite el acceso a la instancia del controlador de Flutter.</p><p><strong>final locator = find.byValueKey(key)</strong></p><p>nos permitirá comprobar si este widget se encuentra en pantalla.</p><p><strong>await FlutterDriverUtils.<em>tap</em>(context.world.driver, locator);</strong></p><p>Este paso realizará la acción de clic al widget que anteriormente habíamos declarado, ejecutándose así 10 veces.</p><p><strong>‘I tap the {string} button {int} times’.</strong></p><p>El texto que pasamos a <strong>when2</strong> debe asegurarse de que sea exactamente como está escrita en el archivo <strong>increment_counter.feature</strong>, en caso contrario al ejecutar esta prueba nos mostraría un mensaje de error.</p><p><strong>Paso 3</strong></p><p>La definición del tercer paso no será necesario implementarlo ya que está incorporado en la librería.</p><p>Ya nos acercaremos al final de este pequeño post, pero la pregunta es cómo haremos para conectar la implementación de estos pasos con nuestra pantalla??. En este caso iremos al archivo <strong>app_test</strong> en la carpeta <strong>test_driven</strong> y escribimos los siguiente:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98cc1ca11145b22df37b3fb1da1e120f/href">https://medium.com/media/98cc1ca11145b22df37b3fb1da1e120f/href</a></iframe><p>En este archivo definiremos los escenario y cada uno de los pasos, la opción de <strong>features</strong> permitirá acceder a todos los escenario que tengamos en nuestra carpeta features y <strong>spetDefinitions</strong> permitirá declarar todos los pasos que se realizaran las pruebas.</p><p>Una vez agregado este código, solo nos quedará ejecutar la prueba, en consola se mostrará los siguiente:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*dp2hcP9FhKRpJXmx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i8zDGon4pV4MleZF" /></figure><p>Hemos llegado al final de este post, espero que este post haya sido de tu agrado, cualquier duda o sugerencia deja tu comentario.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d83ffee8d653" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/creando-pruebas-bdd-en-flutter-d83ffee8d653">Creando pruebas BDD en Flutter</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Django REST Framework to Quickly Get a Working API: part II]]></title>
            <link>https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-ii-c19b950e86f3?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/c19b950e86f3</guid>
            <category><![CDATA[drf]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Fabricio Saavedra]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 19:02:35 GMT</pubDate>
            <atom:updated>2022-11-09T19:02:34.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCGNgvDm3czzdqL2PaZ43g.png" /></figure><p>In the <a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95">first part</a> of this three-part series of articles, we set up the base of a Django project to build an API leveraging some tools provided by the DRF. In this article, we’ll pick up where we left off. We’ll introduce you to the views responsible for request handling.</p><h3>Views</h3><p>Django uses a <a href="https://developer.mozilla.org/en-US/docs/Glossary/MVC">Model View, Controller (MVC) architecture</a>. The Django dev team <a href="https://docs.djangoproject.com/en/4.1/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names">gives their interpretation</a> of what this means for its project, but basically:</p><ul><li>The model is how we organize information in the database. Django uses the model abstraction to establish how the database tables are organized and how they relate to each other.</li><li>The view describes the data that gets presented to the user. It’s not necessarily how the data looks but which data is presented. This is achieved with Python callback functions, such as the functions we specified in the urlpatterns variable.</li><li>The controller is the framework itself: the machinery that sends a request to the appropriate view, according to the Django URL configuration.</li></ul><p>The rules the views use to decide what information needs to be presented to the user can be expressed by decorators or by <a href="https://www.tutorialspoint.com/python/python_classes_objects.htm">class members</a> if we’re using class-based views. And just like that, we got into naming one of the cool features that come from using the DRF: <strong>class-based views</strong>.</p><p>For fairly simple APIs, we use Django to perform repetitive CRUD operations on tables, that is, on rows in a relational database. Writing the instructions to perform those operations can quickly become time-consuming, and the statements themselves can end up being quite verbose, even with a concise programming language, like Python. To mitigate that, the DRF comes with a set of generic API views, classes from which you can inherit to avoid writing repetitive code by specifying class members to fit the needs of your business logic. As we have pointed out, views are functions, so to comply with this, we call the as_view method on the classes that inherit from the generics when we pass them as arguments to the path function call. Remember this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06486a01ffa3974712ac1ba96e80ebff/href">https://medium.com/media/06486a01ffa3974712ac1ba96e80ebff/href</a></iframe><p>If we go through the DRF<a href="https://www.django-rest-framework.org/api-guide/views/"> documentation for API views</a>, we will see that the DRF offers two ways to build a view:</p><ol><li>Class-based views (CBV from here on).</li><li>Function-based views (FBV from here on).</li></ol><p>Both take a Request object and return a Response object (instead of Django’s HttpRequest and HttpResponse respectively), but their use cases are different.</p><p>With FBV, what you see is what you get. Method handling is done by conditional branching and reusability is implemented by using decorators (not without some considerable limitations). For simple views, you can’t complain about them. Take this example<a href="https://www.django-rest-framework.org/tutorial/2-requests-and-responses/#pulling-it-all-together"> from the documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*pK6cTgcKbFfn1_f9T-c7jQ.png" /><figcaption>A FBV to handle snippets objects.</figcaption></figure><h3>Class-Based Views and Serializers</h3><p>You’ll want to use CBV to improve method separation and keep your code DRY. The views module from rest_framework provides the APIView class, which subclasses the Django View class. As we previously stated, the APIView class takes a Request object and returns a Response object (rigorously, the handle methods of the APIView class does that), but also API exceptions will be caught and mediated into appropriate responses. Last but not least, incoming requests will be authenticated, and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. This seems like a lot of features just from inheriting from the APIView class, but that is the beauty of using CBV, and they leverage on mixins and multiple inheritances. To illustrate that, we’ll come back to our project.</p><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-fbe5dec69d95">In part I of this series</a>, we defined VehiclesList and CustomersList and we knew that they were CBV, but not much more than that. For this simple project, I’d write the following VehicleList class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*2Wv69aEgu7nWqkoN_hHZhw.png" /><figcaption>The class definition for the view.</figcaption></figure><p>Ok, what’s that? What is serializer_class? What is ListCreateAPIView? What is VehicleSerializer? That’s just 10 lines long, but many concepts are packed in there, so let’s break them down. Since generics it is imported from the rest_framework module, I think it’s fair to start from this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*2pN0780QNAjdj-sIry3Baw.png" /><figcaption>The class definition for ListCreateAPIView.</figcaption></figure><p>The<a href="https://peps.python.org/pep-0257/#what-is-a-docstring"> docstring</a> is pretty straightforward. That’s what it does, but how? We see that ListCreateAPIView has definitions for handling the GET HTTP method and the POST HTTP method. Both HTTP methods rely on instance methods (list and create), but we can’t see any definition for them directly. The class signature states that ListCreateAPIView inherits from ListModelMixin, CreateModelMixin, and GenericAPIView , so it seems logical to keep pulling the thread on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*r83YBpq37Flv0BCiGEtpww.png" /><figcaption>Class definition for ListModelMixin.</figcaption></figure><p>Ok, now we know where that list instance method came from in the ListCreateAPIView class. Just by reading the method definition, we can get an idea of what it does. Somehow, we get a<a href="https://docs.djangoproject.com/en/4.1/topics/db/queries/#retrieving-objects"> queryset</a> and then filter it to store it in the queryset variable. If the paginate_queryset method returns a truthy value, the list method returns a paginated response of the serializer data, which, oversimplifying, is the queryset in an understandable format for Javascript. If page is a falsy value, we return a non-paginated response with the serializer data. We still haven’t got a formal definition of what a serializer is, but that was some nice piece of self-documented code. Notice that we don’t see any definition for get_serializer, get_queryset, filter_queryset, and so on, but given that this is a<a href="https://www.pythontutorial.net/python-oop/python-mixin/"> mixin</a>, it makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Hq23snBcvmeqFOmcFQzrqw.png" /><figcaption>The class definition for CreateModelMixin.</figcaption></figure><p>Intuitively, the CreateModelMixin would be the place where we could find a definition for the create instance method. It gets a serializer, but instead of passing a queryset or a page to the get_serializer method, it passes a data keyword argument with the request data as a value. Then it validates the serializer, saves it (assuming everything is ok with the validation), and returns the serializer data in an Response object. Why do we have to run a validation on the data in this case? We’ll get to that later on.</p><p>Finally, if we inspect the GenericAPIView class, we’ll see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*uJ7q1C2sjByPmuF5i4auug.png" /><figcaption>Class definition for GenericAPIView.</figcaption></figure><p>Ok, that’s a lot, but you can see that this class has the method definitions we saw both in ListModelMixinand CreateModelMixin. Let’s inspect the most important ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*kU_tSZcVhhnJwgZtnW7R5g.png" /><figcaption>get_queryset function definition.</figcaption></figure><p>get_queryset makes an initial check on the presence of a queryset class member. If it exists, it checks that it is in fact, a queryset, evaluates, and returns it. I compressed the docstring for readability, but it basically says<a href="https://www.django-rest-framework.org/api-guide/generic-views/#attributes"> why we need to get the queryset using this method</a>, especially if we’re overriding the method handlers. What about get_serializer?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*mLjZUnzskYlUU6Xq_8ulNg.png" /><figcaption>get_serializer function definition.</figcaption></figure><p><em>Docstring</em> gave it all away here, get_serializer takes whatever arguments it receives and generates a serializer instance with that. Calling get_serializer_class just returns the serializer_class class member defined in the CBV that inherits from GenericAPIView, after asserting it is not “None”.</p><p>Still, <strong>what is this serializer we’ve been mentioning?</strong> The <em>docstring</em> indicates that a serializer instance <em>should be used for validating and deserializing input, and for serializing output.</em> Furthermore, the<a href="https://www.django-rest-framework.org/api-guide/serializers/"> documentation</a> indicates:</p><blockquote>Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</blockquote><p>It couldn’t be clearer than that. The VehiclesList CBV has two HTTP method handlers.</p><ul><li>When it receives a GET request, the get function will perform a list the operation, which is meant to read information or strictly talking, serializing output, from Django querysets and objects to Python datatypes, which can be rendered into JSON (as to say, understandable to a React app).</li><li>On the other hand, when it receives a POST request, the post function will perform a create operation, which “creates information” by validating input and creating Django model instances.</li></ul><p>So, by defining a serializer class and passing information to it, we can:</p><p>a. Convert Django objects and Python datatypes to JSON, XML, etc.</p><p>b. Convert input into a Django object if said input complies with the validation</p><p>In our brief but conceptually strong example, we defined the serializer_class class member with, but didn’t get to see how the latter was defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*4iIOPAfg17iJlGynKfkwgQ.png" /><figcaption>VehicleSerializer serializer definition.</figcaption></figure><p>We’re clearly taking advantage of the DRF since we’re importing from rest_framework the serializers module, and then inheriting from the ModelSerializer class attribute.<a href="https://www.django-rest-framework.org/api-guide/serializers/#modelserializer"> Another peek at the documentation</a> will shed some light on what a ModelSerializer is:</p><blockquote>Often you’ll want serializer classes that map closely to Django model definitions.</blockquote><blockquote>The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.</blockquote><p>So the ModelSerializer comes in really handy when we want to serialize and deserialize information in fields which resemble a Django Model we have defined.</p><p>In the Meta class, we define some basic information to tell the serializer how it should behave (actually this is a Django pattern, not a serializer thing since we can define Meta for a model definition too). In this case, we specify that the model we want to map is Vehicle. The fields Meta member will specify which model fields we want the serializer to use by defining a tuple or list of strings with field names. You can set this attribute to the special value __all__ to say that all model fields should be used. Since version 3.3.0, it’s mandatory to define this class member (or its counter-part exclude).</p><p>A ModelSerializer provides three really useful features:</p><ol><li>It will create a series of serializer fields from the model.</li><li>It will include a validator for each of the fields.<br> — Do you remember that when we were using the create method of the CreateModelMixin, it had to run a validation on data? That’s because, for new objects, it needs to make sure the input data doesn’t break the rules for the target model.</li><li>It will include default implementations for create and update (the former will be called if we’re not passing an existing instance to the serializer class along with the request data, and the latter if we do).</li></ol><p>Before we test the functionality of our VehiclesList view (that sounds very far at this point, right?), we need to update the Vehicle model. We’d like to illustrate something cool about serializers. But first, we need to add a field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTNAnPH8N4EBIWTPfQdEvA.png" /><figcaption>Updated definition of Vehicle model.</figcaption></figure><p>In the initial definition of Vehicle, we didn’t say <em>“we want this vehicle to be related to this customer”</em>. Imagine the mechanic shop has wealthy customers. There is a chance that a customer will have many vehicles, but a vehicle can only be owned by a customer. This kind of relation is a one-to-many relationship, and it’s commonly represented by using a ForeignKey field. In relational databases, it means a row in the table customers is related to many rows in the table vehicles. Since we’re altering the Vehicle model definition, we need to generate a migration file to communicate this change to the database schema. Then migrate will commit the newest migration files:</p><pre>python manage.py makemigrations<br>python manage.py migrate</pre><p>By now, you should be able to<a href="https://docs.djangoproject.com/en/4.1/ref/django-admin/#runserver"> start a development server</a> by running:</p><pre>python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6p7rZ3Lmy-Luxc1TrqrO3g.jpeg" /><figcaption>Successful start of the development server.</figcaption></figure><p>By default, this development server runs on port 8000. If you’re getting a log similar to the one in the picture above, it means your server started without errors, but that doesn’t mean it won’t crash when we actually make requests to it.</p><p>We will use<a href="https://www.postman.com/downloads/"> Postman</a> to see what happens when we make some requests to the paths we have previously exposed. You can use curl or any other utility to make the request, but for the sake of illustration, I’ll prefer a GUI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzYb4POUf6rJ8Aoz2Qbltg.png" /><figcaption>GET request for /api/vehicles.</figcaption></figure><p>If you remember, making a GET request to the /api/vehicles path performed a list operation from the VehiclesList CBV, returning the serialized data from the queryset of that view. Since we didn’t create any vehicle, it’s natural to receive an empty array as a response. It’s in our hands to have the GET request to return something more interesting. Let’s try to make a POST request to the same path, but we’re going to have an empty body for this attempt to see what happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_Hyp01NafKXx-x3-t91ZA.gif" /><figcaption>POST request to /api/vehicles/ with empty body.</figcaption></figure><p>That’s a very informative response. We got a 400 status code (bad request) and an indication of the fields required to make a successful request. At this point, it’s only saying “we need you to define these fields” but it doesn’t say anything about the data types for the values of those fields. Let’s send a more convenient POST body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dk8tGbSkImP36hgrzoaHcw.png" /><figcaption>POST request to /api/vehicles/ with validation complying data.</figcaption></figure><p>That returned a 200 status code and a serialized representation of the Django object created. We see that it automatically added a id field with a value 1 for it. That means we did a successful insertion in the vehicles table and that the information was saved in a row with an id equal to 1.<a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#primary-key"> Django has that default behaviour</a>, and you can review or update that in the VehiclesConfig class that was generated when we started the vehicles service/app, or globally if you want to change the behaviour across the entire project.</p><p>Ok, that seems pretty easy, we send the fields required, and we create a Django object, right? Let’s try to insert another car, but this time let’s pass the kilometers as a string, and the last oil check date in another format (MM/DD/YYYY):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4OzmAen92M1N_MBpOQ5CKw.png" /><figcaption>POST request to /api/vehicles/ with different input.</figcaption></figure><p>Bad request on sight! The built-in validation from using a ModelSerializer is very clear, the last_oil_check datetime field does not accept that format right out of the gate. It didn’t bother about passing the kilometers as string, presumably because it did a type cast, but it had its concerns about the datetime format, so let’s accommodate that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FjdA8rFLSH1WHncR9ZW3g.png" /><figcaption>POST request to /api/vehicles/ with corrected payload.</figcaption></figure><p>Another successful insertion! Two things to notice here. First, it inserted the second object with id equal to 2. Cool! In the first insertion and this one, we received responses customer equal to null. That’s because the customer field we defined in the Vehicle model took blank=True and null=True as arguments, or, in other words, we didn’t make it a required field. We didn’t create a single customer before making the POST request to the vehicles endpoint neither, so we wouldn’t know what to send there. Still, being a SQL-type database, we can’t omit that “column” when we save the data.</p><p>If you were following along and you try a GET request now, things will look different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3-QF_vsJN1UOWrBgnQ0_w.png" /><figcaption>GET request to /api/vehicles.</figcaption></figure><p>Those ten lines of code in the vehicles/views.py module, plus the serializer definition, gave us the ability to list and create Vehicle objects. For simple operations, using the appropriate generic view will be enough most of the time.</p><p>What if we try to define a customer while inserting a vehicle? We must define the CBV for listing and creating Customer objects first, but that’s pretty similar to what we’ve done for the Vehicle objects, so I won’t write the details and you can take that as an exercise or<a href="https://github.com/fabriccio27/drf_tutorial/commit/c0d3fa926efde61937b895e8711dcae6f517a0de"> check the repo</a> to make sure you got the idea. Once we defined the serializer class and the CBV CustomersList we can make an insertion like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmxIng_kDKcLE-Q0-U1hfg.gif" /><figcaption>POST request to /api/customers/</figcaption></figure><p>Ok, now that we successfully inserted an Customer object, how would we specify that a vehicle belongs to a certain customer while inserting? We know that Vehicle it has a foreign key field for customer, so maybe we can try the following request body:</p><pre>{<br>    &quot;name&quot;: &quot;Civic&quot;,<br>    &quot;brand&quot;: &quot;Honda&quot;,<br>    &quot;kilometers&quot;: 7000,<br>    &quot;last_oil_check&quot;: 2021-12-31,<br>    &quot;customer&quot;: 1<br>}</pre><p>If you make a POST request to /api/vehicles/ with that body, you’ll get a 201 status code. Don’t believe me?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKnM2v03FyEzwGYNTYPVTg.png" /><figcaption>POST request to /api/vehicles/ defining a customer.</figcaption></figure><p>Yeah, it worked, but wouldn’t it be more intuitive to define customer_id = 1 while specifying the relationship? Probably, but by default, while using the ModelSerializer,<a href="https://www.django-rest-framework.org/api-guide/relations/#inspecting-relationships"> serializer fields and relationships will be automatically generated for you</a>. ForeignKey fields use the PrimaryKeyRelatedField serializer field by default, so that’s the reason why we directly pass an id to customer. Of course, you could override this behaviour to pass a customer_id, and exclude the automatically generated customer serializer field.</p><p>Another pertinent question: is it useful to receive a response with customer represented by an id? It’d be more practical to receive a response with more descriptive information about the customer (name, address, etc). You can write<a href="https://www.django-rest-framework.org/api-guide/relations/#nested-relationships"> nested representations</a> to achieve that, but that would require us to override the get method in the CBV to use a different serializer class from the one used to perform create operations, and I believe that would be a little out of the scope of the present article.</p><p><strong>That was a lot.</strong> We need to digest this as if it was a big plate of spaghetti. Just a last question playing the part of a digestive expresso. Do you think it is cool to have your API exposed <strong>so that anyone</strong> with its URLs can get to read and insert data in your database? Most definitely, it is not. Authentication and permissions are the next and last topic in this three-part series on building an API with DRF, so stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c19b950e86f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/using-django-rest-framework-to-quickly-get-a-working-api-part-ii-c19b950e86f3">Using Django REST Framework to Quickly Get a Working API: part II</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SECURING SMART CONTRACTS: A PHISHY BUSINESS]]></title>
            <link>https://medium.com/nicasource/securing-smart-contracts-a-phishy-business-d919dbdfe69b?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/d919dbdfe69b</guid>
            <dc:creator><![CDATA[Lruedalaje]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 19:01:47 GMT</pubDate>
            <atom:updated>2022-11-03T19:01:46.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOtzPIcL3hmjKFJ11OBEHQ.png" /></figure><p><em>In a previous article, we discussed what Smart Contracts are, which are their use cases and which challenges are tackled with blockchain technology. As we stated, a smart contract is a piece of executable code that automatically runs on the blockchain to enforce an agreement between parties involved in the transaction. In practice, many security issues have been reported when using these contracts. This poses a new challenge, which is avoiding potential financial losses and users’ distrust of this perfectible tool.</em></p><p><em>In this article, we will go through security pitfalls when drafting a smart contract and the possible ways to mitigate them.</em></p><h4>GLOBAL VARIABLES VULNERABILITIES</h4><h4>Contracts using ‘tx.origin’ for authorization are vulnerable to phishing</h4><p>Phishing is a cyber-attack by which an attacker disguises himself as a trustworthy entity and deceives the user into doing something they would not want to do otherwise. For example, an attacker can scam a user into sending all of his ether to the attacker’s address.</p><p>tx.origin is a global variable in Solidity <strong>that is vulnerable to phishing</strong>. It is well-known for storing the address where a transaction originates. Let’s see it in an example.</p><p>Alice calls contract A, and contract A calls contract B. Inside contract B, ‘msg.sender’ will be equal to A, but ‘tx.origin’ will be equal to Alice since it is equal to the address where the transaction originated. In other words, since Alice created the transaction, tx.origin will always be equal to Alice.</p><p>Let’s see this variable in the code. Imagine you had the following smart contract:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*1YzuqG6qf3g_vGEE" /></figure><p>Anyone can deposit ethers into this contract, but only the owner can transfer from it.</p><p>As you can see, the transferTo function checks that tx.origin is equal to the owner state variable, and this variable is set to msg.sender in the constructor.</p><p>Let’s say that someone named Alex deploys the TxUserWallet contract, so the owner state variable will be equal to Alex. He will be able to withdraw ethers from this contract by calling the function transferTo. When he does call this function, it will first check that tx.origin is equal to Alex. In this case, he will be able to transfer ethers.</p><p>But what happens if Eve calls this function? tx.origin will be equal to Eve, but the owner will be equal to Alex, so Eve won’t be able to withdraw ethers from this contract. Therefore, if Eve can trick Alex into calling this function, tx.origin will be equal to Alex, the owner will be equal to Alex, and Eve will be able to trick Alex into withdrawing ether from this contract.</p><p>So, if Eve can trick Alex into calling her malicious contract (TxAttackWallet, as shown below), as a consequence, the transfer function from the wallet contract will be called, and the tx.origin will still be equal to Alex. By doing this, Eve will be able to withdraw ethers from Alex’s wallet.</p><p>Let’s take a more careful look at the code that allows Eve, or anyone, to trick you into sending ethers to their address:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5jpuq7DBVq30E7-K" /></figure><p>The function transferTo from TxUserWallet contract is called in the TxAttackWallet contract, and the address of the owner’s attack contract is passed as a parameter, as well as all the balance from the wallet contract to steal all the ether found inside that contract.</p><p>In this case, if TxUserWallet contract had checked msg.sender for authorization, it would get the address of the attack wallet, instead of the owner’s address. But by checking tx.origin, it gets the original address that kicked off the transaction, which is still the owner’s address. The attack wallet instantly drains all your funds!</p><h4>How to prevent it?</h4><p>Instead of using tx.origin for authentication purposes, it is advisable to use msg.sender as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sm-fhWdmm0v0u3Rx" /></figure><p>This will prevent the phishing attack because msg.sender always points to the contract or the account that calls the contract.</p><p>In the end, that’s what we should not forget, using tx.origin might make your contract vulnerable to phishing attacks!</p><h4>You should watch out for timestamps and miners!</h4><p>Another global variable worth mentioning is the block.timestamp.</p><p>To address this issue, we first need to know that the timestamp provides information about the date and time in which the block is mined.</p><p>For example, if you go to the etherscan you can find the timestamp of each block that was mined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40087vzoYn79kOfV" /></figure><p>Often, the timestamp of a current block is used as input for a critical operation, such as determining the winner of a toss.</p><p>Block timestamps can be manipulated by miners and then used to their advantage to attack a smart contract since they can know in advance which will be the input number.</p><p>Let’s see how in an example in code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EBEBupNdfrwiuwPo" /></figure><p>This contract named Roulette has ten ethers stored in it. It will reward the user with all the ethers saved in the contract if he can send a transaction at the right time. The right time will be calculated with the use of the block.timestamp.</p><p>As you can see in this contract, for a user to play, he has to call the function spin and send two ethers. Then, if the value of the block.timestamp is divisible by seven, then the user wins all of the ether stored in the contract. Everyone has one out of seven chances of winning.</p><p>Everyone but miners.</p><p>What can a miner do to improve his chances?</p><p>The miner could send a transaction to play this game by calling the function spin and then try to submit a timestamp divisible by seven for the next block. If the miner is lucky enough to mine the next block, then he will win the reward. Miners have more control over the value in the block.timestamp than regular users.</p><p>Furthermore, if a powerful miner is the one attempting to attack the contract, say its mining power is 30% of the whole network, this will mean that his chances of winning this game would be at least 30%, which is a better chance than one out of seven.</p><h4>How to prevent it?</h4><p>Do not use block.timestamp!</p><p>If you MUST use it, follow the 15-second rule. It states that if the scale of your time-dependent event can vary by 15 seconds and still maintain integrity, it is safe to use block.timestamp. This means that if the contract’s code does not rely on a time interval of fewer than 15 seconds then it is probably safe to use block.timestamp.</p><h4>STORAGE VARIABLES VULNERABILITIES</h4><h4>OVERFLOW &amp; UNDERFLOW</h4><p>The uint overflow/underflow, also known as uint wrapping around, is an arithmetic operation that produces a result that is larger than the maximum above for an N-bit integer or produces a result that is smaller than the minimum below for an N-bit integer.</p><p>Let’s see it in an example so as to make it clearer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*-HzvDzF7q7GRtZny" /></figure><p>In the previous contract, we have a function that counts kilometers and a function that subtracts kilometers.</p><p>We have an unsigned integer that can only have 16 bits. This means that the largest number that can be stored is the decimal number 65535.</p><p>Let’s compile and deploy the KilometersCount contract. As you can see, kilometers are first initialized at 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*V9v0lwpA54dBIfXM" /></figure><p>If we subtract kilometers, they should be decremented by one. Let’s see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*kzwO75S06NZdzB_F" /></figure><p>Kilometers are now 65535, which is the maximum value possible that the variable can store. This is an underflow example. If we now add a kilometer to the maximum value (65535), instead of being incremented by one, kilometers will be 0. This is an example of overflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*95kOl67vsR_uuTwT" /></figure><p>This can represent a major flaw in balances.</p><h4>How to prevent it?</h4><p>The easiest way is to use at least a 0.8 version of the Solidity compiler. The compiler will automatically check for overflow and underflow. Let’s see it in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*T5xtcpI0eAef3Yxc" /></figure><p>This is the same smart contract compiled with version 0.8.0. If we try to subtract kilometers initially, we will get the following error in the Remix console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOSi6vbldkwsdc7-" /></figure><p>Bear in mind that there are many contracts out there that were implemented in older versions of the compiler and will unfortunately still have this problem.</p><p>The solution would be to:</p><ul><li>Update the compiler to the latest versions.</li><li>Implement libraries to operate safely.</li></ul><h4>PRIVATE VARIABLES</h4><p>Have you ever wondered if there is still something that can be private? If you haven’t, it is time to do so.</p><p>As you know, everything in a smart contract is accessible for anyone to see, which means that sensitive information can not be hidden.</p><p>You might be wondering, what about PRIVATE variables? Spoiler alert: they are not REALLY private.</p><p>In order to explain this, some basis of Solidity programming language must be recalled. In essence, there are four types of visibility for functions and state variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1G9NVffAT-B71tgun8JDVQ.png" /></figure><p>Therefore, EVERYTHING that is inside a contract is visible to ALL external observers.</p><p>Making something private only prevents other contracts from accessing and modifying the information, but it will still be visible to the whole world outside of the blockchain.</p><p>But how can these private variables be hacked?</p><p>Variables in a contract will be stored as follows:</p><ul><li>All state variables in Solidity are stored in storage in order of declaration.</li><li>Local variables of structs and arrays are always stored in storage by default. Variables declared as constants or as immutable are directly compiled and do not occupy a slot.</li><li>Each slot can store up to 256 bits (32 bytes).</li><li>Multiple variables can be stored in the same slot, if they fit.</li><li>Booleans only need one byte. Addresses take 20 bytes.</li><li>If the size of the variable exceeds the remaining size of the slot it will be passed to a new slot.</li><li>Struct creates a new slot, and the struct elements are put in the slot as described above.</li><li>A fixed-size array creates a new slot, struct elements are put into the slot, and the same procedure is followed again.</li><li>A dynamic size array creates a new slot. This slot only stores the length of the array, while the values in the array will be stored at other locations.</li><li>Mapping always creates a new slot to hold a place, yet the values ​​in the array will be stored in other locations.</li><li>String creates a new slot that stores both data and data length.</li></ul><p>Now let’s see in code how the hacking would work…</p><p>Below we have a contract named Privado, which stores, in slot 0, a variable called “numeroSecreto”. In the constructor, we define the variable as equal to block.timestamp. We can see in the terminal the block timestamp is 1639681587.</p><p>Then, we can access the value of the variable by typing web3.eth.getStorageAt(“”). The first input inside the parentheses is the contract address and the second input is the slot number where the variable whose value we are trying to find out is stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aYFxrNTZtMz3TU5Y" /></figure><p>As you can see below, the output is ‘0x61bb8e33’, which is 1639681587 when converted from hexadecimal to decimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4wk9fRwoD1434sCe" /></figure><p>That’s it. The private variable has been unveiled.</p><h4><strong>INTERACTING WITH OTHER CONTRACTS</strong></h4><p>AVOID DELEGATECALL</p><p>To begin with this topic, we will first explain what a call is. A call is a low-level function used to interact with other contracts. Let’s see how to use it in an example that is going to call the contract TestCall written below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OdFNXk5yRt2rGQ7k" /></figure><p>As you can see below, we have coded a contract named Call that will call the TestCall contract function foo by executing the callFoo function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALQ-lOmcAQ568Cjy" /></figure><p>We will deploy both contracts, TestCall and Call. When we call the function callFoo we will pass the address of TestCall. That is why we have included a variable named _test of type address as an input of the function.</p><p>To call the function foo using the low-level function call we type _test.call(). Inside the parentheses, we need to encode the function that we will be calling followed by the inputs that we are going to be passing. This is why we type “abi.encodeWithSignature()”. The first input will be the function that we are going to be calling, “foo(string,uint256)”. Next, we need to pass the function inputs. In this case, the first input needs to be a message of type string, ‘“call foo”, and the second one a uint, 123.</p><p>Using call will return two outputs. The first one is a boolean that tells whether the call was successful or not, “bool success”, and the second one is any output that was returned by calling the function foo,” bytes memory_data”.</p><p>Next, we will check if the call was successful by typing require(success, “call failed”). If the call was not successful we will define a message saying ”call failed”.</p><p>When we use call to call other functions we can specify the amount of gas and the amount of ethers that we are going to be sending. For that, after _test.call, inside curly braces, we have specified the number of ethers, 111.</p><p>We will also create the variable data and store the output returned once the function finishes its execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/0*SqAuTYcGUbhFqmgw" /></figure><p>After that, we will deploy both contracts and will call the callFoo function adding the TestCall contract address, as shown below.</p><p>Then, if we successfully call the callFoo function and transfer our ethers, we’ll see something as shown in the Remix terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f4aY-Sz7Q6jjbQZb" /></figure><p><strong>So, what are DELEGATECALLS, and why should we avoid them?</strong></p><p>delegatecall is a low-level function similar to call. The difference is that it executes code in another contract in the context of the contract that has called it.</p><p>This means that when contract A executes the delegatecall to contract B, B’s code is executed with contract A’s storage, msg.sender, and msg.value.</p><p>What does this mean?</p><p>A calls B and sends 100 weis. B delegateCall to C. In this last case, msg.sender will be A. This is because when we query msg.sender inside B, it will be equal to A. A called B and inside B thus msg.sender is A. Delegatecall preserves the context, so when B delegateCalls to C, msg.sender remains and is equal to A. The same happens to msg.value, which will be equal to 100.</p><p>Let’s see an example in code. First, we coded the contract TestDelegateCall with the function setVars that gives values to the variables num, sender, and value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*IQbHb0WuQulVgftx" /></figure><p>Then we have the DelegateCall contract, from where we will delegateCall the function setVars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UCoEmN55O7XPwLBD" /></figure><p>We then compile and deploy both contracts. We will call the function setVars from DelegateCall contract, and this will delegatecall to TestDelegateCall and execute the code inside the setVars function inside the TestDelegateCall contract. Nevertheless, since we are executing delegateCall, the state variables that you see in the contract TestDelegateCall will not be updated. Instead, the state variables in the contract that made the call, DelegateCall, are the ones that will be updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*DFy9lGlIV5qgHekT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*kbK-s2S0waj4Dysm" /></figure><p><strong>So, why do we need to avoid it?</strong></p><p>This low-level function has been very useful as it’s the backbone for implementing libraries and modularizing code. However, it opens up the doors to vulnerabilities as, essentially, your contract is allowing anyone to do whatever they want with their state.</p><p>Here is a contract named HackMe. It has a state variable called owner, which is set inside the constructor when the contract is deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*SAgsjNdYpSJYoqv3" /></figure><p>We will try to hijack the contract by changing the variable owner even though the contract does not have any functions that update the value of the variable owner.</p><p>As you can see above, the only function that the contract has is a fallback function that doesn’t update the owner state variable. Inside this function, the delegatecall function is used. And who does it delegatecall to? To the state variable lib, that is another contract inside the constructor.</p><p>Let’s take a look at contract Lib:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*NyC4SlZkR_yBqSdD" /></figure><p>It declares a single state variable called owner, and has a single function called pwn, and when this function is called, it sets the single declared variable to msg.sender.</p><p>We are now going to change the value of the owner variable from the HackMe contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*w78KT6eLBvw966r8" /></figure><p>We will store the address of the hackMe contract in a state variable called hackMe. The actual address will be set when we deploy the contract. This is why we pass the address into the constructor and then set it to the state variable hackMe.</p><p>We create a function called attack which is the one we will be calling to update the state owner variable from the hackMe contract. Our goal here is to call the “pwn” function inside the lib contract, which we can do by calling the fallback function inside the hackMe contract and then passing in the function signature of pwn as msg.data (we know that fallback functions get triggered when a function that does not exist inside the contract is called).</p><p><strong>But how did the hack work?</strong></p><p>When we call the attack function, the HackMe contract is called, and the function that tries to be called inside the HackMe contract is “pwn”. Since the “pwn” function does not exist inside the HackMe contract, the fallback function will be called instead. The fallback function will delegatecall to the Lib contract and forward the msg.data.</p><p>Delegatecall calls the Lib contract, and since we sent msg.data to match the pwn function, the function pwn inside lib contract will be executed and consequently will run the code to update the owner state variable.</p><p>Since delegatecall runs code using the storage of hackMe contract, it will actually update the owner state variable inside the hackMe contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*J_Wo8uuiPxNjzfZD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*OMxDopmViiRba295" /></figure><p>Alice (0x5B38Da6a701c568545dCfcB03FcB875f56beddC4) deployed the Lib contract. Next, she took the address of the Lib contract and deployed the HackMe contract.</p><p>Eve (0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2) deployed the Attack contract with the address of the HackMe contract.</p><p>As can be seen, the owner of the contract changed. Eve hijacked Alice’s contract.</p><p><strong>This is why we recommend avoiding the use of delegatecall. In case you MUST use it, then you should never forget that delegatecall preserves context.</strong></p><h3>TRANSFER’S ATTACKS</h3><p><strong>FORCEFULLY SENDING ETHER</strong></p><p>selfdestruct is a Solidity function that transfers the funds from a contract to an account and then removes a contract from the network.</p><p>Let’s see how a contract can be hacked when using this function.</p><p>etherGame is a contract in which the seventh person to deposit one ether becomes the winner and can claim the seven ethers stored in this contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-YZUw_PudXUOT10-" /></figure><p>To play this game, the players will call the function deposit. If the current balance stored in this contract is greater than seven ethers, the game is over. After seven ethers have been achieved, no one should be able to send more ethers.</p><p>If the current balance is equal to seven ethers, then we set the winner to msg.sender. This means that if msg.sender is the seventh person to deposit one ether, then that person becomes the winner.</p><p>The winner can claim its reward by calling the function claimReward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4SKrAWzUPaM9QMzr" /></figure><p>Let’s now write a contract that can tamper with this game. The basic idea is to use selfdestruct so that the balance exceeds the target amount of seven ethers. By doing so, the balance will never equal the target amount, and the winner will never be set. No one will be able to call the function claimReward and all of the ethers from the players will be stuck in this contract.</p><p>Let’s see it in code.</p><p>The contract Attack has a single function named attack that will be called to break the contract above. For the input, we pass the target address and then declare it as payable. The reason that it is payable is that the address that is passed to selfdestruct must be a payable address. We will send ether to this function and have that ether forcefully sent to the contract above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KgCe9Fd7M8-lk6DH" /></figure><p>Inside the function, we will call selfdestruct passing our target address.</p><p>We deploy the two contracts, etherGame and Attack contract. We will say that account 1 is Alice’s, account 2 is Bob’s, and account 3 is Eve’s.</p><p>Eve is going to play this game and deposit one ether. Bob also joins in and deposits the same amount. At this point, the contract has two ethers. Alice and Bob are both trying to become the seventh person to deposit one ethe, become the winner, and finally, claim all the ethers stored.</p><p>Eve decides to break this game. She knows there are two ethers stored in this contract and that if she forcefully sends five ether at once, she can break the game. Every user who then sends one ether will get the message ‘Game is Over’, since the balance will always be greater than the target amount. The winner won’t be set.</p><p>As we can see, after Eve sends five ethers, the balance of the contract is seven and the winner has not been set. All rewards are then locked in this contract, with no winner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*IWSxyorsCPjFF5KA" /></figure><p>In this specific case, this could have been avoided. The value of the balance can be manipulated, so the decision of who is the winner should not rely on it. If the contract was coded as shown below, attackers might still forcefully send ethers to the contract, but they won’t be able to update the variable state balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oTOl1gCfM4xGfwqo" /></figure><p>This is why we recommend knowing how selfdestruct works and if you must implement it, we advise you to do it in a very careful way.</p><p><strong>REENTRANCY</strong></p><p>What is a reentrancy attack?</p><p>Over here we have contract A and contract B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rvA1ZG8zzPYQySQl" /></figure><p>Let’s imagine that contract A calls contract B. The very basic idea of reentrancy is that contract B can call back into contract A while contract A is still being executed.</p><p>Now imagine that contract A has ten ethers and contract B has none. Inside contract A, there is also a record of how many ethers are owed to other contracts and addresses. Imagine there is also a function called withdraw that checks if your address is included in the record, that is to say, if you have some ethers stored in that contract, so that you are able to withdraw them.</p><p>Contract B can use the reentrancy to exploit the withdraw function. It will have two functions. The fallback function and the attack function, in both functions contract B will call the withdraw function from contract A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rBqfpEuaSEWsmOdJ" /></figure><p>First, Eve calls the attack function. This will call the withdraw function inside contract A. Inside contract A, since contract B is the caller, it will check that the balance of contract B is greater than 0. In this case, it is, since the balance is equal to one. Therefore it sends the ether back to contract B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LiSOX0iLbPTVrGDl" /></figure><p>Inside contract B, the fallback function is triggered. Now, contract B has one ether, and contract A has nine ethers. The fallback function inside contract B calls the withdraw function from contract A, and checks the balance of B.</p><p>As you can see, the balance of contract B is still one, so it will once more send one ether to contract B. Now, contract B has two ethers while the balance of B inside contract A is still one ether. This could keep on going because the state variable balance is not updated until the last line of code inside the withdraw function, and it is not reached because it keeps on looping between the fallback function and the withdraw function. Therefore, contract B can keep on withdrawing ether from contract A.</p><p><strong>How can we prevent the reentrancy attack?</strong></p><ul><li>Update state variables before you make any external calls to other contracts. In the example below, the state variable balance inside the withdraw function is updated before calling another contract.</li><li>Use a modifier to lock the contract while a function is being executed. In this way, only one function will be executed per time, causing attacks to fail.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/0*SSzb9ajudj-9Kpyn" /></figure><p><strong>CONCLUSION</strong></p><p>In this article, we have addressed security risks that exist when coding a smart contract. Additionally, we have discussed variable and storage vulnerabilities and some concerns that may arise when interacting with other contracts or transferring ether. To enrich our experience, we have also coded and hacked every contract to demonstrate the security issues we have mentioned.</p><p>Evidently, our aim was not to encourage hacking. We believe spreading information about these vulnerabilities might contribute to improving developers’ coding skills and eventually help in decreasing hacking. So, if you have any questions or comments, don’t hesitate in contacting us.</p><p><strong>BIBLIOGRAPHY</strong></p><p><a href="https://medium.com/haloblock/unit-underflows-and-overflows-ethereum-solidity-vulnerability-39a39355c422">Yuan He, Security Researcher from HaloBlock.io</a></p><p><a href="https://solidity-by-example.org/delegatecall/">https://solidity-by-example.org/delegatecall/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d919dbdfe69b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/securing-smart-contracts-a-phishy-business-d919dbdfe69b">SECURING SMART CONTRACTS: A PHISHY BUSINESS</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OUTSMARTING SMART CONTRACTS]]></title>
            <link>https://medium.com/nicasource/outsmarting-smart-contracts-ea4918c95850?source=rss----76ea101e9a71---4</link>
            <guid isPermaLink="false">https://medium.com/p/ea4918c95850</guid>
            <dc:creator><![CDATA[Lruedalaje]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 19:02:39 GMT</pubDate>
            <atom:updated>2022-11-02T19:02:39.405Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg6E-B-lzhrIIj_GXzsqUg.png" /></figure><blockquote>Traditional contracts are sets of agreed-upon terms which are enforceable by law and are described in a natural, human language. Nowadays, smart contracts coexist with traditional contracts. But, what is so smart about them? In essence, they are computer programs that automate the enforcement of terms. In this article, we will try to outsmart smart contracts by grasping their concept and deeply exploring possible use cases and benefits.</blockquote><h3><strong>LET’S SET IT ON BLOCKCHAIN!</strong></h3><p>‘Let’s set this agreement in stone!’. That’s the phrase used when two parties reach an agreement after an exhausting negotiation.</p><p>Even though it is just a phrase, it seems a little… outdated, at least. Web 3.0 has arrived, and with it, it is fair to say that it is time to set it on the blockchain</p><p>Blockchain is probably the best invention since the Internet itself. The unique mix of cryptography and decentralization gives this technology the properties of permanence, transparency, and neutrality.</p><p>Its magic resides in allowing value exchange without needing a third party or central authority. With only a few lines of code, transactions can be managed quicker, cheaper, and more securely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y89pQ7s3nxN3XRAzN0x15w.png" /></figure><h3>What is a SMART CONTRACT?</h3><p>The easiest way to explain smart contracts is by picturing them as a vending machine.</p><p>As you already know, when using a vending machine you decide what you want and enter the money into the machine. Once you click the button or insert the code for the item, the machine automatically releases the selected product. After certain conditions are met, you receive the desired good.</p><p>Smart contracts essentially work in the same way. After certain conditions are met, they automatically execute themselves and enforce the contract clauses on the parties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*nmSzPU0gVIc4l5lo" /></figure><blockquote><strong>To recap, a smart contract is a CODE intended to implement the negotiation or performance of an agreement. It allows us to complete credible transactions without third parties because these transactions are embedded in </strong><a href="https://www.sciencedirect.com/topics/computer-science/blockchain"><strong>blockchains</strong></a><strong>, which automatically triggers the contractual terms of an agreement to be enforced.</strong></blockquote><h3><strong>SMART CONTRACT USE CASES.</strong></h3><p>Use cases can be found in banking, insurance, energy, e-government, telecommunications, music and film industry, fine art, mobility, education, and many more. Their applications may vary from simple to complex. They can be used for</p><ul><li>A simple economic transaction like sending money from A to B</li><li>Registering any kind of ownership and property rights, like land registries, intellectual property, or even managing smart access control for the sharing economy.</li></ul><p>In this article, we will explore some areas in which the use of smart contracts becomes even more tempting since we get to solve well-known challenges that were not resolved until blockchain arrived.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgoC0Wh3q233k-dRP3vA-A.png" /></figure><h4>DIGITAL IDENTITY</h4><p>Digital identity is a set of data living on the Internet and representing real-world’s identity. A significant section of society uses digital identities for daily tasks, such as accessing government benefits, bank accounts, education, etc. Some services are inaccessible without a digital identity.</p><p>Yet, issues regarding authentication and privacy are challenges that are yet to be addressed. Guaranteeing that the user’s identity corresponds to whom it claims to be or that the user’s information is shared with those they authorize is still a challenge.</p><p>Fortunately, blockchain can answer these challenges regarding authentication and privacy.</p><h4>BLOCKCHAINS TO THE RESCUE!</h4><p><strong>Tackling authentication challenges</strong></p><p>Nowadays, blockchain-driven solutions are the best options to deal with authentication challenges.</p><p>But how is it done?</p><p>Essentially, each user has a wallet, and each blockchain wallet has a private and a public key. The private key generates a signature, which is used in each transaction to guarantee the user’s identity. Inside the blockchain, nodes will verify that the signature was generated correctly utilizing the user’s public key.</p><p>Hence, each transaction that is added to the blockchain will have a digital signature that ensures that the user who has created the transaction is who he claims to be.</p><p>And voilá! The authentication problem is solved.</p><p>Let’s see an example in code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHdnzCCTtKp055L0" /></figure><p>This smart contract is named Authentication.</p><p>It is written in Solidity programming language. <strong>In this article, we won’t explain the basics of this programming language, but after coding, we will revisit the code for further clarification.</strong></p><p>As you can see, there is a mapping named <em>users</em> that relates a wallet address with a boolean value. There is also a function that registers the user who wants to authenticate the address and assigns him the boolean value of true.</p><p>In essence, when the authenticate method is called, a transaction is created and added to a block inside the blockchain, which is signed with the public and private keys of the user.</p><blockquote><strong>What about tackling privacy issues?</strong></blockquote><p>Let’s walk through an example in code.</p><p>The following smart contract is named Identity and is coded to illustrate how to protect the users’ privacy.</p><p>It has two structs with users’ information. The BasicInfo struct has basic information, such as name and email. The PersonalInfo struct has more personal data, such as salary and address.</p><p>Then, we have created an enum with the different user types that the user who deploys the contract can have: Basic and Personal. Basic users can access BasicInfo, and Personal users can access PersonalInfo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azl3ZOeSq7J6cw13" /></figure><p>We have created an error that will be launched when one of the users attempts to retrieve information without being authorized.</p><p>Then, we have defined three variables:</p><ul><li>‘basicInfo’ stores the user’s basic information.</li><li>‘personalInfo’ stores the user’s personal information.</li><li>‘owner’ stores the address of the user who is deploying the contract.</li></ul><p>We have added a mapping named ‘basicUser’ to store all the basic users who have access to basic information and a ‘personalUser’ with all the users who have access to personal information.</p><p>The constructor defines the values that will have the ‘basicInfo’ and the ‘personalInfo’ and establishes who is the owner of the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SwlAhwzrtmx55FXV" /></figure><p>The function ‘getBasicInfo’ returns the basic information of the contract’s owner. The function is of type ‘view’ as it only returns a value and does not modify any value of the contract’s body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SfenXjRDkhqy28kq" /></figure><p>The function uses the ‘authorizeUser’ modifier. This modifier checks if the user has the required permissions to access the desired information. If the user is the owner or if he/she is authorized to access personal information, then permission will be granted. If the user is type basic, the modifier will check if the user is inside the mapping ‘basicUser’ and in which case the information will be given. If none of the above conditions are met, then we will launch the error stating that the user is not authorized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3qeRRUenxq2UoUlI" /></figure><p>The function ‘registerUser’ can only be used by the owner. The ‘onlyOwner’ modifier checks if who is calling the function is indeed the contract’s owner. The function will receive the user that we want to authorize and its type. If the user type is ‘basic’, we will add them to the ‘basicUsers’ mapping, and if it is ‘personal’, to the ‘personalUsers’ mapping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c4j5uok3QOA6ngKi" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t0PeDUgQChb8x2Mj" /></figure><p>In this way, information can only be accessed if the user is authorized. This successfully solves all challenges regarding the user’s privacy.</p><h4>FINANCIAL SERVICES</h4><p>Financial services are the<a href="https://en.wikipedia.org/wiki/Service_(economics)"> economic services</a> provided by the<a href="https://en.wikipedia.org/wiki/Finance"> finance</a> industry. It encompasses a broad range of<a href="https://en.wikipedia.org/wiki/Business"> businesses</a> that manage money. Among them, we may include <a href="https://en.wikipedia.org/wiki/Credit_union">credit unions</a>,<a href="https://en.wikipedia.org/wiki/Bank"> banks</a>,<a href="https://en.wikipedia.org/wiki/Credit-card"> credit-card</a> companies,<a href="https://en.wikipedia.org/wiki/Insurance"> insurance</a> companies,<a href="https://en.wikipedia.org/wiki/Accountancy"> accountancy</a> companies,<a href="https://en.wikipedia.org/wiki/Consumer_finance"> consumer-finance</a> companies,<a href="https://en.wikipedia.org/wiki/Brokerage_firm"> stock brokerages</a>,<a href="https://en.wikipedia.org/wiki/Investment_management"> investment funds</a>, individual asset managers, and some<a href="https://en.wikipedia.org/wiki/Government-sponsored_enterprise"> government-sponsored enterprises</a>.</p><p>The truth is that financial institutions become a sort of black box for users who do not know how their money is moving inside these institutions.</p><p>With blockchain, light can be shed into that darkness.</p><p>All network participants have a copy of the ledger, which grants absolute transparency. This will provide complete information about all the participants on the network and their transactions. Also, the P2P nature of payments enabled by smart contracts reduces transaction costs, which means that micropayments could become economically more feasible than they are today.</p><h4>OUR OWN NICACOIN!</h4><p>So, once again, blockchain offers a solution. Changing the paradigm from a centralized system to a decentralized one means that:</p><ul><li>There will be no more intermediaries</li><li>The responsibility for money management rests with the user</li><li>There is equal access for all users who just need to have a wallet.</li></ul><p>These systems are frequently based on DApps. They allow users to interact with the blockchain more naturally without having to know the technical details of how it works</p><p>Let’s create our own NicaCoin!</p><p>First, we have assigned a name to our token, ‘NicaCoin’. Then, we defined a symbol for our token ‘NIC”, which usually goes from 3 to 5 letters. Finally, we have added how many decimals our token can have. A balance of our token can be written with 18 decimals.</p><p>The variable _totalSupply will store the number of tokens to be created for distribution.</p><p>Mappings are used in Solidity to store data in the form of key-value pairs. We have created two mappings. In the first one, the key is the wallet address, and the value is the balance of the account. In that way, we keep track of how many tokens a user owns. In the second one, the key is associated with a value of type mapping. An address can grant other addresses the right to spend a certain amount of tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UcYDbO7oFU0YH5SH" /></figure><p>We have also created two events. The ‘Transfer’ event will be executed every time we transfer NicaCoins from one account to another, and the Approval event will be executed each time the owner allows a third-party spender to use his tokens on his behalf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dy9O2Lm3gGTA0JNo" /></figure><p>The constructor initializes the ‘totalSupply’ and gives the total amount of created tokens to the account of the user who displays the contract.</p><p>The ‘totalSupply’ function returns the tokens generated at the beginning.</p><p>The ‘balanceOf’ function returns how many tokens belong to a specific account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T_DlDlyahf-gcmAZ" /></figure><p>The transfer function transfers tokens from the owner’s wallet to another one. Inside the function, we validate that the account from which our NicaCoins are being transferred has a sufficient amount of coins. Then, it subtracts from the balance of the NicaCoins being transferred. Finally, the event transfer is launched.</p><p>The approve function will allow a third-party spender to use a certain quantity of tokens on behalf of the owner. It will allow someone or another smart contract to use our NicaCoins on our behalf. It will launch the approval event with the corresponding information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jF4KIzPcuQwwDru2" /></figure><p>The allowance function will verify how many tokens are remaining in the owner’s wallet.</p><p>The ‘transferFrom’ function allows us to transfer tokens from one account to another. It will first validate that there are sufficient tokens to be transferred and that the third-party spender is authorized to use those tokens. Then, the tokens being transferred are subtracted and added to each corresponding balance, and the event transfer is launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VCQw7kJPBhJyhhkd" /></figure><h4>DIGITAL ASSETS</h4><p>Digital assets are files that can be saved digitally, such as images, videos, audio, or other documents. They have an owner and can be distributed to the general or specific public.</p><p>But… how do we guarantee that our digital asset won’t be modified during its distribution? How do we guarantee that our digital assets won’t be duplicated? How do we guarantee our authorship?</p><p>What’s the solution? Blockchain’s immutability. This means a blockchain ledger remains unchanged, unaltered, and indelible. Setting something on a blockchain is like setting something in stone.</p><p>Once it is set on the blockchain, <em>it’s on!</em></p><h4>WELCOME TO TOKEN-LAND. LET’S CREATE OUR NFT</h4><p>Tokens or digital assets, also known as crypto tokens, are units of value that represent an asset or provide unique utility within its native blockchain network.</p><p>There are a variety of token standards that enable interoperability within a given blockchain. For example, within the Ethereum network, the most widely used token standard is the <a href="https://www.investopedia.com/news/what-erc20-and-what-does-it-mean-ethereum/">ERC-20 standard</a>, which allows the creation of interoperable tokens with the rest of the Ethereum ecosystem and applications (our own NicaCoin!)</p><p>There are also various archetypes of tokens, including asset-backed tokens, non-fungible tokens, digital currencies, utility tokens, governance tokens, security tokens, and much more.</p><p>Therefore, NFTS are digital assets that live inside the blockchain. This guarantees that they have a unique value and a unique owner. The standard ERC-721 defines which features must be followed by a smart contract for it to be considered as an NFT inside the Ethereum network.</p><p>Let’s create an NFT and go through our code.</p><p>As can be seen, we use OpenZeppelin, which is in charge of creating standards for blockchain security.</p><p>First, we import the contract ERC721 from OpenZeppelin and then an extension to this contract that will allow us to store the URI of this token. The URI is where all the metadata of our NFT will be stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oQHgoj8NdpeQFpYV" /></figure><p>In our contract, we have defined two variables. The first one, ‘tokenIds’, will define which token will be assigned each time a user wants to obtain our NFT. The ‘tokenIds’ must be unique.</p><p>The second variable is ‘owner’, which defines who has deployed this contract.</p><p>In the constructor, we will call the contract ERC721 with the token name and a symbol as function parameters. The variable ‘owner’ will assign the address of who is deploying the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eZ2a6LCtN3xrSMY6" /></figure><p>After that, we have defined a function mintNFT that will allow us to assign our NFT to another user inside the blockchain. The function receives the user’s wallet and the tokenURI. The function has the modifier ‘onlyOwner’ that verifies that whoever is deploying the contract is the real owner. Inside the function, the tokenId will be increased by one, and the function mint, provided by OpenZeppelin, will be called. This function will add the generated token to the account balance.</p><p>Finally, we will call the function setTokenURI, provided by OpenZeppelin, which will relate the tokenId with the tokenURI. That unique tokenId that has been generated will be returned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BTORFWoj6pzcX6mE" /></figure><h4>SUPPLY CHAIN</h4><p>A supply chain is the series of activities that a product requires to reach an end user. The process starts with the raw material and ends with the final product that the user buys.</p><p>But.. how can we coordinate all the intermediaries in the supply chain? How can we scale the manufacturing process of a product?</p><p>Guess what? Once again, blockchain through smart contracts gives us an answer.</p><p>A Blockchain does not need intermediates, and all coordination is given by the rules stated in the smart contract. Also, once a transaction is added to the blockchain, all nodes are informed. All nodes will have the final version of the blockchain. This will allow an automatic synchronization between all the intermediates that participate in the manufacturing of the product. Last but not least, automatic payments will be able to be made between all those who have participated in the supply chain.</p><p>Wondering how it could be implemented? Let’s take a look at the code…</p><h4>NEITHER RAW, OVERCOOKED, NOR WELL-DONE… I WANT MY STEAK IN BLOCKCHAIN!</h4><p>We will now draft a smart contract for obtaining a meat stake all the way from the farm through the processor, the distributor, and the retailer until it finally reaches the user’s table.</p><p>As you can see, in the contract, we have defined a struct named ‘Step’, which will save the status of the product and the metadata that will be needed by each intermediate in every step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N7oWZJjT00UNXphB" /></figure><p>After that, we created an enum with the following states: ‘created’, ‘ready_for_pick_up’, ‘picked_up’, ‘ready_for_delivery’, and ‘delivered’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uRDPYzo_cFQffGmx" /></figure><p>An event named ‘RegisteredStep’ has been created and will inform us every time a step in the manufacturing of the product is concluded. It has the following characteristics: productId, a status that has been registered, the metadata of this step, and finally, who was the one that called this event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_BjiVoCwl_1kDHSx" /></figure><p>We have created a mapping that will relate a productId with every step named ‘product’.</p><p>The function ‘registerProduct’ allows us to create a new product. It will receive a productId and will validate that the productId does not have steps associated and will then assign the first status of ‘CREATED’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T-2n9EdsbSGucTaM" /></figure><p>The function ‘registerStep’ receives a productId, and the metadata that intermediates will need to be able to act. This function will validate that: a) the product exists and there are steps associated with it; b) the last step’s status is correct; c) this status is no greater than the last one named “Delivered”. After that, we will assign the corresponding next state, and it will be added to our product mapping. Finally, the event that informs us that a new step has been concluded is launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4vmNFaZsqEv0WhSj" /></figure><h4>CYBERSECURITY</h4><p>Cybersecurity is the set of practices used to protect a system’s information. This information is protected through integrity, confidentiality, and availability.</p><p>But… how can we guarantee that information will arrive as we expect it to? How can we be certain that only authorized people have access to it? How can we ensure that information will always be available when needed?</p><p>Once more, the answer lies in blockchain.</p><p>Since it is immutable, its network is permanent and unalterable. This means that any validated records are irreversible and cannot be changed. Hence, no one will be able to edit, change or delete it.</p><p>Also, being a distributed network means that the blockchain will continue to answer with no problem, even if one of the nodes fails.</p><p>Lastly, I know confidentiality does not seem to go hand in hand with blockchains since they aim to provide transparency. Nevertheless, setting access rules in smart contracts or building private blockchains make it possible to keep critical data confidential.</p><h4>BLOCKCHAIN FOR BUSINESS</h4><p>Imagine a private company with its private blockchain. We will draft a contract in which each node will inform the events inside the blockchain to cybersecurity.</p><p>Let’s see it in code….</p><p>First, we have defined an event that will be launched each time a node adds an event inside the blockchain.</p><p>Also, we have set a mapping named ‘events’ that will relate the wallet address of the node that publishes the event, the eventId, and the event data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mpMWzzlvWBnPdSz9" /></figure><p>We have also added another mapping named ‘eventsCounter’ to store the number of events published by a blockchain node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I0A5AHK_Gfd6AN9b" /></figure><p>The variable ‘threshold’ defines how many events a node can register. We need to take into account that if we store a great deal of data in the blockchain, our contract’s gas will rise, and therefore it will become more expensive.</p><p>The variable ‘owner’ will store the contract’s owner. In our constructor, we have assigned the threshold and the owner values.</p><p>The function createEvent receives the event as a parameter. Inside the function, we will have a counter of how many events have been added by a node, and we will increment it in one so that each event has a unique id.</p><p>We then verify if the ‘eventId’ is greater than our threshold, and in that case, we will overwrite all events so as not to store too many events.</p><p>Then, we add the ‘eventId’ in our ‘eventCounter’ mapping, and in our ‘event’ mapping we will add the node that has added that event, the ‘eventId’, and its metadata. Lastly, we call our event ‘newEventCreated’ to inform our network about the new event that has been created. The function ‘setThreshold’ is for changing the variable threshold and will only be used by the owner of the contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ffNe8UCHa8qj1xYH" /></figure><h4>CONCLUSION</h4><p>In this article, we have thoroughly examined smart contracts and their use cases. We have highlighted the challenges that are solved with the use of blockchain and have displayed the code that aids in its implementation.</p><p>Nevertheless, it is important to underline that these are only a set of examples of how this disruptive technology named blockchain, through smart contracts, can offer solutions to well-known problems.</p><p>The exponential growth of smart contract implementation is due to the obvious benefits that blockchain technology provides. Technology itself does not add value to society, but when it is addressed to solving society’s real problems, that is when the true difference is made. Smart contracts are the quintessential example of it.</p><p>As developers, all that is left is outsmarting their smartness and truly mastering them. As individuals living in society, we have no better option than to seize their huge benefits.</p><h3>BIBLIOGRAPHY</h3><ul><li><a href="https://leasepilot.co/blog/smart-contracts-vs-traditional-contracts-can-we-bridge-the-gap/">Smart Contracts vs. Traditional Contracts: Can We Bridge the Gap?</a></li><li><a href="https://platzi.com/cursos/usos-smart-contracts/">Blockchain and Cryptocurrency — Platzi School</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea4918c95850" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nicasource/outsmarting-smart-contracts-ea4918c95850">OUTSMARTING SMART CONTRACTS</a> was originally published in <a href="https://medium.com/nicasource">NicaSource</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>