teleren/devto huggingface dataset:
Using eth-gas-reporter
Tags: solidity, gasestimation, gasreporter, hardhat
Published: 2022-05-17 19:39:37

A good smart contract is the one which is gas-optimized and not-vulnerable to attacks. 
And there are some tools which help us analyze these aspects before deploying contract to production.
(_I have made a series of blogs on [Gas Optimization techniques](https://dev.to/rushanksavant/series/17966) and [Security Vulnerabilities](https://dev.to/rushanksavant/series/18119) if you are interested_)

In this blog, we will see how to use **eth-gas-provider** to get report of gas-consumption and gas-price for deployment and function calls of the contract.
If reading bores you, head over to my [GitHub repo](https://github.com/Rushanksavant/eth-gas-reporter) and follow along the steps.

### So let's begin:
- Install hardhat if you haven't done already:
  ```npm install --save-dev hardhat```
- Create a sample hardhat project:
  ```npx hardhat```
This will create a Greeter.sol in contracts directory along with some other files and directories.
- Installing dependencies:
```npm i hardhat-gas-reporter``` 
```npm i dotenv``` 
- create a **.env** file(in main directory) as follows:
```env
coinMarketCap_API= //get your api-key at https://coinmarketcap.com/api/pricing/
REPORT_GAS= true // set to false when you don't want gas-report
```
- Now goto **hardhat.config.js** file, and replace the content in it with the following:
```javascript
require("@nomiclabs/hardhat-waffle");
require("hardhat-gas-reporter");
const dotenv = require("dotenv");
dotenv.config();

module.exports = {
  solidity: "0.8.4",
  gasReporter: {
    enabled: (process.env.REPORT_GAS) ? true : false, // will give report if REPORT_GAS environment variable is true
    currency: 'USD', // can be set to ETH and other currencies (see coinmarketcap api documentation)
    coinmarketcap: process.env.coinMarketCap_API // to fetch prices from coinmarketcap api
  }
};
```
- And finally, use the following command to compile, test, and get gas-report for the sample contract:
```npx hardhat test```

### Output:
You can expect a similar output as follows:

![Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jxjwcbzzswdmcawkblx.PNG)

The **usd (avg)** might vary, based on price of ETH and current gas price. The ***Avg*** shows the gas consumption for function call and contract deployment.
Buy Me a Coffee | Made with Nuxt JS
Published: 2022-05-17 19:20:41

![Buy Me a Coffee | Made with Javacript | Nuxt JS](https://res.cloudinary.com/madewithjavascript/image/upload/v1652675537/large_buy_me_a_coffee_made_with_nuxt_js_507ae7ee81.png "Buy Me a Coffee | Made with Javacript | Nuxt JS")

### Buy Me a Coffee is the best way for creators and artists to accept support and membership from their fans.

> A supporter is worth a thousand followers.
> 
> Accept donations. Start a membership. Sell anything you like. It’s easier than you think.
> 
> It’s free, and takes less than a minute.
> 
> Buy Me a Coffee help creators receive support from their audience in a friendly way 🎉
> 
> 😻Set up a page like this in 2 minutes
> 
> 💰Accept donations via Paypal, Card & Apple/Android Pay
> 
> 🎁Reward your supporters

## Check out more such amazing projects on our website

[Made with Javascript](https://madewithjavascript.club)

## Want us to feature your project


Simply Fill out this Google Forms page.

[Submit your Project to Made with Javascript](https://madewithjavascript.club/submit-project)


You can also write to us for any of your queries at:

[Email Made with Javascript](mailto:madewithjavascript@gmail.com)

## Project already shared on our social media handles.

| SocialMedia | SharedLink |
| ----------- | ---------- |
| Twitter | [Buy Me a Coffee on Twitter](https://twitter.com/withjavascript/status/1526642690451984386?s=20&t=SxpMKm-5Lefz5wk9YJM0bg)
 |
| Medium | [Buy Me a Coffee on Medium](https://medium.com/@madewithjavascript/buy-me-a-coffee-made-with-nuxt-js-57fd392c546)
 |
| Facebook | [Buy Me a Coffee on Facebook](https://www.facebook.com/madewithjavascript/posts/pfbid02rPrYNbcvWVMJTQeN775iPwSi9kCFKnsKJCeJLWxhHFsJc8qY3w6rmQxa2qy5qwUxl)
 |
| Tumblr | [Buy Me a Coffee on Tumblr](https://madewithjavascript.tumblr.com/post/684526254154792960/buy-me-a-coffee-made-with-nuxt-js-buy-me-a)
 |
| LinkedIn | [Buy Me a Coffee on LinkedIn](https://www.linkedin.com/feed/update/urn:li:activity:6932408505073115136)
 |


Filled Under:

 - [Made with Javascript](https://madewithjavascript.club)
    
 - [Made with Nuxt JS](https://madewithjavascript.club/categories/nuxt-js)
Rest vs Spread Operator
Tags: javascript, webdev, react, beginners
Published: 2022-05-17 19:12:25

I remember being asked about the difference between the rest and spread operator and drawing a blank. I hadn't used the spread operator since I was in my bootcamp, and even on that occasion it seemed a bit glossed over. 

<img width="100%" src="https://media.giphy.com/media/7NUR5Qvr93ed8T2dsG/giphy.gif">

So I wanted to address this knowledge gap by walking through the use and differences between the rest and spread operator. 

It's easy to confuse the spread operator and the rest operator because their syntax is so similar. 

**Spread Operator**: we can spread the content of an iterable into individual elements.

**Note**: An iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables


Let's look at the Spread Example:

```JavaScript

const arr = ["My", "name", "is", "Melissa"]

const copyArr = [...arr]

console.log(copyArr)

console.log(...copyArr)

```

Let's see what the console returns when we `console.log(copyArr)`


![Spread operator returning the array of strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1iwzc7vbtt270my2xf4v.png)

We return `["My", "name", "is", "Melissa"]`


The **spread operator** allows us unpack collected elements into their own single elements.



---


**Rest**: allows a function to accept an indefinite number of arguments as an array


Let's look at an example: 

```JavaScript
function logFullName(firstName, ...familyName) {
  console.log(firstName);
  console.log(familyName);
}

logFullName("Robert", "Alfred", "Cole"); 

```

**Update: thank you [Bryce Dorn](https://dev.to/bryce) for correcting my code! 

The elements of myName is being broken apart and reorganized into a new subarray. This is called destructuring, an array or object is broken into smaller pieces.

Let's look at our console:


![Fixed use of spread in function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3fw5d5dc8uveiszah7ab.png)


The first `console.log` of `console.log(firstName)` returns the first element in the array, 'Robert'. The rest of the elements in the array are collected and put into a new sub array called familyName. This is why when we `console.log(familyName)` we get the new sub array consisting of the rest of the original array `["Alfred", "Cole"]`.


Think of rest as a mnemonic device that means it creates its own collection of the rest of the array. In this example, that would be the new sub array `["Alfred", "Cole"]`.

**Update: Thanks to [hacker4world](https://dev.to/hacker4world) for giving an example on the use and syntax with functions: 

```JavaScript
function logParams(...params) {
     console.log(...params);
}

logParams(1,  2,  3, 4);

```

To further understand the logic at play, create your own examples and test them in your console of your choosing. Practicing this achieves a better understanding of rest and spread!
Novedades .NET en mayo 2022
Tags: dotnet, netcore, maui
Published: 2022-05-17 19:09:00

---
title: Novedades .NET en mayo 2022
published: true
description: ¿Quieres saber lo que está llegando al panorama .NET en mayo?
tags: dotnet, netcore, maui 
cover_image: https://pbs.twimg.com/card_img/1524104828632412160/7E97haUk?format=jpg&name=900x900 
canonical_url: https://geekstorming.wordpress.com/2022/05/12/novedades-dotnet-mayo-2022/
---

El ecosistema .NET está más que vivo, porque estamos viendo una cantidad de novedades increíbles en varias áreas: móvil, Entity Framework, eventos...

En este post vamos a descubrir algunas de ellas, ¡empezamos!

### Sobre MAUI

Por si no lo conoces, NET Multi-platform App UI (MAUI para las amistades) es el framework que evoluciona de Xamarin.Forms. Sigue en desarrollo, y nos abrirá la puerta para desarrollar apps para Windows, Android, iOS y Mac.

Pues bien, al momento de escribir este post ya se ha publicado la [Release Candidate 3](https://devblogs.microsoft.com/dotnet/dotnet-maui-rc-3/).

Además, Visual Studio Installer ya incluye el workload específico de MAUI en la preview de Visual Studio 2022:

{% twitter 1524433653501239296 %}

Porque Visual Studio 2022 tampoco para, ya se ha lanzado la [versión 17.2](https://devblogs.microsoft.com/visualstudio/visual-studio-2022-17-2-is-now-available/), incluyendo las siguientes features:

-   Mejoras para el debugging de colecciones
-   Live preview de webs para ASP.NET
-   Mejoras para el desarrollo con Azure
-   Mejoras de experiencia con Git dentro del IDE

#### Taller de .NET MAUI

Javier Suárez está publicando, vídeo a vídeo, un taller introductorio a .NET MAUI en su canal de YouTube. Si estás deseando crear tus próximas futuras aplicaciones multiplataforma con una nueva herramienta, aquí tienes la solución:

{% youtube uWQt95m6Zic %}

Al momento de escribir esto, tenemos 7 episodios, pero puedes ver todo el [temario planificado en el repositorio de GitHub](https://github.com/jsuarezruiz/taller-dotnet-maui), junto con todas las diapositivas y demos.

### Novedades de .NET 7 Preview 4

En el [artículo original de esta noticia](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-4/) podéis ver todos las novedades relacionadas con ASP.NET Core, entre las que se encuentran:

-   Mejoras para OpenAPI en minimal APIs
-   Client results en SignalR
-   Mejoras de performance en HTTP/2
-   Devolver múltiples tipos de resultados en minimal APIs
-   Route groups

Entre otras cositas, como las novedades para [Entity Framework 7 preview 4](https://devblogs.microsoft.com/dotnet/announcing-entity-framework-7-preview-4/) y las que también [anuncian de la última preview de .NET 7](https://devblogs.microsoft.com/dotnet/announcing-dotnet-7-preview-4/) en general.

### #MSBuild 2022

Y esto no acaba aquí, porque se acerca el Microsoft Build.

Este evento es en el que Microsoft saca toda su artillería para mostrar todos los productos que están por venir, mejorar y sorprendernos. Más juguetes y herramientas con las que seguir creando y aprendiendo.

{% twitter 1518985549591289856 %}

¡Nos veremos en #MSBuild, del 24 al 26 de mayo!
Firebase Cloud Functions
Published: 2022-05-17 18:59:51

Quoting verbatim from the docs, Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests.

See https://firebase.google.com/docs/functions

https://firebase.google.com/docs/functions/get-started

```
mkdir cloud-functions-101
cd cloud-functions-101
nvm use
npm install -g firebase-tools
firebase login
firebase init firestore
firebase init functions
firebase emulators:start
```

For killing emulator, find and kill the process running on 8080.

```
lsof -i tcp:8080
kill -9 pid
```
Prevent External Contracts
Tags: solidity, security, bestpractice
Published: 2022-05-17 15:30:21

Almost every vulnerability you see in solidity smart contracts are caused by hackers developing some attacker contract and this attacker contract then harming the vulnerable contract.
By the way, I have made a series on smart contract vulnerabilities if you find it interesting ([link](https://dev.to/rushanksavant/series/18119))

But what if there is a way by which we can know if function caller is a contract or a normal wallet address? 
Then we can stop any external contract from interacting with our contract, hence saving our contract from being hacked.

Let's see how this can be achieved:
- consider a contract vulnerable to re-entrancy (check my [re-entracy](https://dev.to/rushanksavant/re-entrancy-44m9) blog)
- in this case, hacker will take advantage of late balance update in state mapping, and will keep on re-entering contract using his attacker contract until all funds are drained.
- but not if we stop external contracts to call `MyContract` functions. 😎

```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.1;

contract MyContract { // this contract is vulnerable to re-entracy attack

    mapping (address => uint) balances;

    modifier noContract { // this won't allow external contracts to interact with this contract
        require(tx.origin == msg.sender, "No contracts allowed");
        _;
    }

    function deposit() external payable noContract { // using noContract 
        balances[msg.sender] += msg.value;
    }

    function withdraw() external payable noContract { // using noContract 
        uint amount = balances[msg.sender];
        require(amount > 0, "Nothing to withdraw");

        (bool sent, ) = msg.sender.call{value: amount}("");
        require(sent, "Send operation failed");

        balances[msg.sender] = 0;
    }

    function getBalance() external view returns(uint balance) {
        balance = address(this).balance;
    }
}
```

We are stopping external smart contracts using `noContract` modifier. It verifies if function caller(`msg.sender`) is same as transaction initiator(`tx.origin`). 
Wanna know more about `tx.origin`? Visit [here](https://dev.to/rushanksavant/careful-while-using-txorigin-5c90)

Now when some Attacker contract will try to steal funds from MyContract, transaction will fail.
Attacker contract:
```solidity
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.1;

interface IMyContract{
    function deposit() external payable;
    function withdraw() external payable;
}

contract Attacker {
    IMyContract myContract;

    constructor(address _myContract) payable {
        myContract = IMyContract(_myContract);
    }

    fallback() external payable {
        if (address(myContract).balance > 0) {
            myContract.withdraw();
        }
    }

    function attack() external payable {
        myContract.deposit{value: 1 ether}();
        myContract.withdraw();
    }

    function getBalance() external view returns(uint balance) {
        balance = address(this).balance;
    }
}
```
ALL YOU NEED TO KNOW ABOUT AMAZON RELATIONAL DATABASE SERVICE (RDS)
Tags: aws, database, beginners, cloud
Published: 2022-05-17 18:30:44

Amazon Relational Database Service (RDS) is a collection of managed services that makes it simple to set up, operate, and scale databases in the cloud. Amazon RDS gives the user the options to choose from many RDS Engines such as Amazon Aurora, MYSQL, MariaDB, PostgreSQL, Oracle, and Microsft SQL Server. Amazon RDS also gives users a wide variety of computing instances to run their databases on.  The users need to choose these instances according to their work needs and load. Some of these instance types are Amazon Ec2 Mac Instances powered by Mac computers (with Intel Core i7-8700 processors) and built on the AWS Nitro System, T4g powered by  Arm-based custom-built AWS Graviton2 processors, and many more. If you wish to know more about the instance types, visit [Amazon EC2 Instance Types - Amazon Web Services](https://aws.amazon.com/ec2/instance-types/). An RDS instance can be hosted in a single availability Zone and Multisite Availability zones depending on the user's needs. Multi-site Az’s offers users resiliency and high availability benefits. It typically takes the database application 60 to 120 seconds to switch to the secondary instance when there is a failure and it happens automatically. The failover process can happen in the following scenarios; If patching maintenance has been performed in the primary instance, if the instance of the primary database has a host failure, if the availability zone of the primary database fails, if the primary instance was rebooted with failover, and if the primary database instance class on the primary database is modified.
In making sure, your database instance is able to meet the growing demands of your workloads, it is advisable to use a feature called **Autoscaling**. Most of the engines supported by Amazon RDS use Elastic Block Storage. Those engines are MySQL, PostgreSQL, MariaDB, Oracle, and SQL Server.

![Features Of Amazon RDS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vfvdhqrsl208ny6god0.png)  Amazon RDS IN Graphics (source - AWS)

FEATURES OF AMAZON RDS
Amazon RDS has the following features which the users can benefit from.

1. Security and Compliance
2. Performance and Scalability
3. Automated Patching and Upgrades
4. Data durability and Redundancy
5. Monitoring and alerting 
6. Backup and recovery

If you want to learn more about Amazon Relational Database Service, visit [Fully Managed Relational Database - Amazon RDS - Amazon Web Services
](https://aws.amazon.com/rds/)
Take our Backend, Mobile, Web and Desktop developer survey this week and win $100 USD Amazon gift card
Tags: mobile, programming, developer, backend
Published: 2022-05-17 18:21:48

---
title: Take our Backend, Mobile, Web and Desktop developer survey this week and win $100 USD Amazon gift card
published: true
description: 
tags: #mobile #programming #developer #backend
//cover_image: https://direct_url_to_image.jpg
---

We have created a survey for **Backend, Mobile, Web and Desktop developers**. As we’re trying to get an understanding of the platforms and the technologies you use, your input is very helpful! Are you interested to check this out?

You can take our survey **[here](https://survey.developernation.net/name/wcs2?utm_medium=post&utm_source=dev_to&utm_campaign=devto_post_wcs)** and win prizes!
Paracetamol.js💊| #118: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-05-17 17:58:01

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Intermedio</mark></center>

```js

const res = async() => {
  try{
    const y = await Promise.reject("Chau");
    console.log(y)
  }catch(err){
    console.log(err)
  }
}
res()
```

A. `Chau`
B. `Promise { <fulfill> }`
C. `Promise { <pending> }`
D. `Promise { <reject> }`

Respuesta en el primer comentario.

---
How to use previously packaged ReactJS component in static website
Tags: react, lit
Published: 2022-05-17 17:35:02

Hi,
I have been given a ReactJS web component whose cource code is as follows:

```javascript
import * as React from 'react';
import {createComponent} from '@lit-labs/react';
import {Button} from '../../components';

export const ExButton = createComponent(
    React,
    'ex-button',
    Button
);
```

This react app is bundled into `index.esm.js`
file

My task is to use this component in a static website. I have created an html file as follows

```html 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <xml:namespace prefix="v" ns="urn:schemas-microsoft-com:vml"> </xml:namespace>
    <title>React JS</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://unpkg.com/react@18.1.0/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18.1.0/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/browserify@17.0.0/index.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  </head>
  <body>

 <!-- pre-packaged React web component-->
    <script type="module" src='./react/index.esm.js'></script>
<!-- script to render the above component -->
    <script type="text/babel" src='./react/reactjs-btn.js'></script>
  </body>

</html>
```

The contents of reactjs-btn.js is as follows:
```javascript
'use strict';

const btnContainer1 = document.querySelector('#button_container');
const btnroot = ReactDOM.createRoot(btnContainer1);

let element = <ExButton type="primary"></ExButton>;
btnroot.render(element);
```

I am running the html file on apache server. However, I get an error 
`Uncaught ReferenceError: ExButton is not defined`

_Is it even possible to render a **previously packaged** React component in a static website?_

I would appreciate any help
Regards,
John
8 Marvelous UI Components for Your Design Inspiration 🎨😍
Tags: webdev, design, ui, css
Published: 2022-05-17 17:34:14

---
title: 8 Marvelous UI Components for Your Design Inspiration 🎨😍
published: true
description: 
tags: webdev, design, ui, css
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zchbwzg2af92tdmfye7c.png
canonical_url: https://madza.hashnode.dev/8-marvelous-ui-components-for-your-design-inspiration
---
Modern web development is component-based. Coming up with an eye-catching design might be challenging, especially if you are a less experienced web developer. 

In this article, I have compiled some of my favorite components that you can use for inspiration for your own projects. To provide diversity, I included projects from buttons, bars, and menus to cards, calendars, and neumorphic elements. 

For each component, I will include a direct link to the code, an embedded interactive preview, as well as author links so you can check their other work as well.

## 1. [Neumorphic Elements](https://codepen.io/myacode/pen/PoqQQNM)

By: [Maria M. Muñoz](https://codepen.io/myacode)

{% codepen https://codepen.io/myacode/pen/PoqQQNM %}

## 2. [Animated Tab Bar](https://codepen.io/abxlfazl/pen/VwKzaEm)

By: [abxlfazl khxrshidi](https://codepen.io/abxlfazl)

{% codepen https://codepen.io/abxlfazl/pen/VwKzaEm %}

## 3. [Overlay menu](https://codepen.io/ig_design/pen/VgaXaY)

By: [Ivan Grozdic](https://codepen.io/ig_design)

{% codepen https://codepen.io/ig_design/pen/VgaXaY %}

## 4. [Log In / Sign Up](https://codepen.io/ig_design/pen/KKVQpVP)

By: [Ivan Grozdic](https://codepen.io/ig_design)

{% codepen https://codepen.io/ig_design/pen/KKVQpVP %}

## 5. [Blog Card Slider](https://codepen.io/JavaScriptJunkie/pen/WgRBxw)

By: [Muhammed Erdem](https://codepen.io/JavaScriptJunkie)

{% codepen https://codepen.io/JavaScriptJunkie/pen/WgRBxw %}

## 6. [Pricing card](https://codepen.io/ig_design/pen/VwedgWj)

By: [Ivan Grozdic](https://codepen.io/ig_design)

{% codepen https://codepen.io/ig_design/pen/VwedgWj %}

## 7. [CSS grid calendar](https://codepen.io/knyttneve/pen/QVqyNg)

By: [Mert Cukuren](https://codepen.io/knyttneve)

{% codepen https://codepen.io/knyttneve/pen/QVqyNg %}

## 8. [Glowing buttons](https://codepen.io/bhadupranjal/pen/vYLZYqQ)

By: [Pranjal Bhadu](https://codepen.io/bhadupranjal)

{% codepen https://codepen.io/bhadupranjal/pen/vYLZYqQ %}

<hr>

Writing has always been my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!

Connect me on [Twitter](https://twitter.com/madzadev), [LinkedIn](https://www.linkedin.com/in/madzadev/) and [GitHub](https://github.com/madzadev)!

Visit my [Blog](https://madza.dev/blog) for more articles like this.