津田  直子

津田 直子

1649784360

ブラウザでDialog要素サポート!TypeScriptチームがECMAScriptに型構文を提案!

 ブラウザでDialog要素サポート! GoにGenerics登場! Remix Stacksリリース! TypeScriptチームがECMAScriptに型構文を提案! React 18RCリリース!

#dialog #go #remix #react #aws  #circleci 

ブラウザでDialog要素サポート!TypeScriptチームがECMAScriptに型構文を提案!

Documentation for Remix IDE

Remix

This repository contain only Remix's official Read the Docs documentation source code. Documentation is available here.

If looking for Remix IDE codebase, it has been moved to https://github.com/ethereum/remix-project

About Remix Project

Remix Project is a platform for development tools that use a plugin architecture. It encompasses sub-projects including Remix Plugin Engine, Remix Libraries, and of course Remix IDE.

Remix IDE is an open source web and desktop application. It fosters a fast development cycle and has a rich set of plugins with intuitive GUIs. Remix is used for the entire journey of contract development with Solidity language as well as a playground for learning and teaching Ethereum.

Start developing using Remix on browser, visit: https://remix.ethereum.org

For desktop version, see releases: https://github.com/ethereum/remix-desktop/releases

Remix libraries work as a core of native plugins of Remix IDE. Read more about libraries here

Remix screenshot

Build

Steps to build this project as as:

pip3 install sphinx sphinx_rtd_theme
pip3 install recommonmark
git clone https://github.com/ethereum/remix-ide.git
cd docs/
make html

Go to docs/_build/html ann open index.html on the browser.

Contributing

Everyone is very welcome to contribute. Suggestions, issues, queries and feedbacks are our pleasure. Please reach us on Gitter in case of any query.

Download Details:
Author: ethereum
Source Code: https://github.com/ethereum/remix-ide
License:

#ethereum  #blockchain  #smartcontract #remix 

Documentation for Remix IDE

Remix - Ethereum IDE & Community

Remix Project

Remix Project is a platform for development tools that use a plugin architecture. It encompasses sub-projects including Remix Plugin Engine, Remix Libraries, and of course Remix IDE.

Remix IDE is an open source web and desktop application. It fosters a fast development cycle and has a rich set of plugins with intuitive GUIs. Remix is used for the entire journey of contract development with Solidity language as well as a playground for learning and teaching Ethereum.

Start developing using Remix on browser, visit: https://remix.ethereum.org

For desktop version, see releases: https://github.com/ethereum/remix-desktop/releases

Remix screenshot

:point_right: Remix libraries work as a core of native plugins of Remix IDE. Read more about libraries here

Offline Usage

The gh-pages branch of remix-live always has the latest stable build of Remix. It contains a ZIP file with the entire build. Download it to use offline.

Note: It contains the latest supported version of Solidity available at the time of the packaging. Other compiler versions can be used online only.

Setup

  • Install NPM and Node.js. See Guide 

Supported versions:

"engines": {
    "node": "^14.17.6",
    "npm": "^6.14.15"
  }
  • Install Nx CLI globally to enable running nx executable commands.
npm install -g @nrwl/cli
  • Clone the github repository (wget need to be installed first):
git clone https://github.com/ethereum/remix-project.git
  • Build remix-project:
cd remix-project
npm install
npm run build:libs // Build remix libs
nx build
nx serve

Open http://127.0.0.1:8080 in your browser to load Remix IDE locally.

Go to your text editor and start developing. Browser will automatically refresh when files are saved.

Production Build

To generate react production builds for remix-project.

npm run build:production

Build can be found in remix-project/dist/apps/remix-ide directory.

npm run serve:production

Production build will be served by default to http://localhost:8080/ or http://127.0.0.1:8080/

Docker:

Prerequisites:

Run with docker

If you want to run latest changes that are merged into master branch then run:

docker pull remixproject/remix-ide:latest
docker run -p 8080:80 remixproject/remix-ide:latest

If you want to run latest remix-live release run.

docker pull remixproject/remix-ide:remix_live
docker run -p 8080:80 remixproject/remix-ide:remix_live

Run with docker-compose:

To run locally without building you only need docker-compose.yaml file and you can run:

docker-compose pull
docker-compose up -d

Then go to http://localhost:8080 and you can use you Remix instance.

To fetch docker-compose file without cloning this repo run:

curl https://raw.githubusercontent.com/ethereum/remix-project/master/docker-compose.yaml > docker-compose.yaml

Troubleshooting

If you have trouble building the project, make sure that you have the correct version of node, npm and nvm. Also ensure Nx CLI is installed globally.

Run:

node --version
npm --version
nvm --version

In Debian based OS such as Ubuntu 14.04LTS you may need to run apt-get install build-essential. After installing build-essential, run npm rebuild.

Unit Testing

Run the unit tests using library name like: nx test <project-name>

For example, to run unit tests of remix-analyzer, use nx test remix-analyzer

Browser Testing

To run the Selenium tests via Nightwatch:

  • Install Selenium for first time: npm run selenium-install
  • Run a selenium server: npm run selenium
  • Build & Serve Remix: nx serve
  • Run all the end-to-end tests:

for Firefox: npm run nightwatch_local_firefox, or

for Google Chrome: npm run nightwatch_local_chrome

  • Run a specific test case instead, use one of following commands:
 - npm run nightwatch_local_ballot

 - npm run nightwatch_local_usingWorker
 
 - npm run nightwatch_local_libraryDeployment
 
 - npm run nightwatch_local_solidityImport
 
 - npm run nightwatch_local_recorder
 
 - npm run nightwatch_local_transactionExecution
 
 - npm run nightwatch_local_staticAnalysis
 
 - npm run nightwatch_local_signingMessage

 - npm run nightwatch_local_specialFunctions

 - npm run nightwatch_local_solidityUnitTests

 - npm run nightwatch_local_remixd # remixd needs to be run

 - npm run nightwatch_local_terminal

 - npm run nightwatch_local_gist

 - npm run nightwatch_local_workspace

 - npm run nightwatch_local_defaultLayout

 - npm run nightwatch_local_pluginManager

 - npm run nightwatch_local_publishContract

 - npm run nightwatch_local_generalSettings

 - npm run nightwatch_local_fileExplorer

 - npm run nightwatch_local_debugger

 - npm run nightwatch_local_editor

 - npm run nightwatch_local_compiler

 - npm run nightwatch_local_txListener

 - npm run nightwatch_local_fileManager

 - npm run nightwatch_local_runAndDeploy

NOTE:

  • The ballot tests suite requires to run ganache-cli locally.
  • The remixd tests suite requires to run remixd locally.
  • The gist tests suite requires specifying a github access token in .env file.
    gist_token = <token> // token should have permission to create a gist

Important Links

Download Details:
Author: ethereum
Source Code: https://github.com/ethereum/remix-project
License: MIT License

#ethereum  #blockchain  #smartcontract #remix 

Remix - Ethereum IDE & Community

SMTChecker, Remix & Dapptools in Solidity

The SMTChecker is a formal verification module inside the Solidity compiler. Historically it has been complicated to run the SMTChecker on your own contracts, since you had to compile the compiler with an SMT/Horn solver, usually z3. We have been working on different solutions to this, and nowadays it is quite easy to run it.

The Solidity compiler ships binaries targeting 4 different systems, with different SMTChecker support:

  • soljson.js, a WebAssembly binary that comes with z3.
  • solc-macos, an OSX binary that comes with z3.
  • solc-static-linux, a Linux binary that does not come with z3, but is able to dynamically load z3 at runtime if it is simply installed in the system.
  • solc-windows.exe, a Windows binary that does not come with z3.

This means that if your development framework uses soljson.js or the OSX binary, or the Linux binary and you have z3 installed, the SMTChecker should be available.

The old but still supported way to enable the tool is by using pragma experimental SMTChecker; in your source code, but we are deprecating that in favor of the JSON field settings.modelChecker and the --model-checker-* CLI options. Solidity 0.9.0 will not accept the pragma anymore, only the JSON and CLI options.

Remix

Remix uses the WebAssembly binary, so the SMTChecker works out of the box. It does not yet let you tweak the settings.modelChecker JSON field, but you can still use the pragma version.

remix_code

The warning on line 15 comes from the SMTChecker:

remix_cex

Note that the compilation time may increase considerably if you enable the SMTChecker, since the SMT solver will run in the background, trying to solve potentially several queries.

Dapptools

Dapptools has a tight integration with hevm and makes it quite easy to apply formal verification. Dapptools uses solc’s system’s binary via Nix, so if you use OSX you are all set, and if you use Linux you just need to install the SMT solver z3.

This section is almost a transcript of the first part of my talk at Formal Verification in the Ethereum Ecosystem, where I demoed SMTChecker + Dapptools.

The easiest way to run the SMTChecker here is by using solc’s standard JSON interface. You can generate a solc JSON input file of your Dapptools project with

$ dapp mk-standard-json &> smt.json

and then modify it manually to add the object

"modelChecker": {
	"engine": "chc",
	"contracts": {
		"src/MyContract": [ "MyContract" ]
	},
	"targets": [ "assert" ]
}

Or use a one liner to do the same:

$ dapp mk-standard-json | jq '.settings += {"modelChecker": {"engine": "chc", "contracts": {"src/MyContract.sol": ["MyContract"]}, "targets": ["assert"]}}' &> smt.json

In the next release of Dapptools, this will become even easier:

DAPP_SMTCHECKER=1 dapp mk-standard-json

If the environment variable DAPP_SMTCHECKER is set to 1, dapp mk-standard-json already outputs the desired input JSON file with standard values for the settings.modelChecker object. You can simply modify them directly to change the model checker options.

Since the SMTChecker runs at Solidity’s compile time, now all you have to do is tell Dapptools to use that input JSON file and re-compile:

$ DAPP_STANDARD_JSON=smt.json dapp build

The SMTChecker does not handle Dapptools’ DSTest well, so it is recommended that you write a specific contract with properties (assertions) you want to verify, and make that contract inherit from your main contract instead of calling it externally. Then use this new contract as the target in the settings.modelChecker.contracts object above.

dapptools_code

New object in the input JSON file:

"modelChecker": {
	"engine": "chc",
	"contracts": {
		"src/BinaryMachine.t.sol": [ "BinaryMachineProperties" ]
	},
	"targets": [ "assert" ]
}

By combining the properties contract, which can also be seen as specification, and DSTest, one can use both the SMTChecker and hevm in the same setup.

SMTChecker analysis run:

dapptools_smtchecker

hevm fuzzer run:

dapptools_hevm

Both tools show that our property is actually wrong, and give us a counterexample that breaks the assertion. Let’s fix the assertion and change the property function to:

function propertyOne() public view {
	assert(x <= 2);
}

Now we don’t get a warning about the assertion anymore, which means that the solver managed to prove that the assertion is always true.

If we use Solidity 0.8.10 or greater, we can now ask the SMTChecker to give us any contract inductive invariants that the solver may have found:

"modelChecker": {
	"engine": "chc",
	"contracts": {
		"src/BinaryMachine.t.sol": [ "BinaryMachineProperties" ]
	},
	"targets": [ "assert" ],
	"invariants": [ "contract" ]
}

Here we tell Dapptools to use a solc different from its default (I downloaded the latest release):

DAPP_SOLC=./solc-static-linux DAPP_STANDARD_JSON=smt.json dapp build

Now we get:

Info: Contract invariant(s) for src/BinaryMachine.t.sol:BinaryMachineProperties:
!(x >= 2)

So the solver tells us not only that our assertion is true, but that there is also a stronger property that is true: x < 2, instead of our x <= 2. This property is automatically inferred by the Horn solver, together with many other useful properties such as reentrancy properties and loop invariants.


Now let’s check a small but a bit more complex example:

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;

interface Unknown {
	function callMe() external;
}

contract ExtCall {
	uint x;

	function setX(uint y) public {
		x = y;
	}

	function xMut(Unknown u) public {
		uint x_prev = x;
		u.callMe();
		// Can `x` change?
		assert(x_prev == x);
	}
}

We built the JSON input:

$ dapp mk-standard-json | jq '.settings += {"modelChecker": {"engine": "chc", "contracts": {"src/ExtCall.sol": ["ExtCall"]}, "targets": ["assert"]}}' &> smt.json

Since we are using smt.json just for the SMTChecker we can remove the ExtCall.t.sol source and the selected outputs, so that we get:

{
  "language": "Solidity",
  "sources": {
    "src/ExtCall.sol": {
      "urls": [
        "src/ExtCall.sol"
      ]
    }
  },
  "settings": {
    "modelChecker": {
      "engine": "chc",
      "contracts": {
        "src/ExtCall.sol": [
          "ExtCall"
        ]
      },
      "targets": [
        "assert"
      ]
    }
  }
}

Running

DAPP_SOLC=./solc-static-linux DAPP_STANDARD_JSON=smt.json dapp build

we get

Warning: CHC: Assertion violation happens here.
Counterexample:
x = 1
u = 0
x_prev = 0

Transaction trace:
ExtCall.constructor()
State: x = 0
ExtCall.xMut(0)
    u.callme() -- untrusted external call, synthesized as:
        ExtCall.setX(1) -- reentrant call
  --> src/ExtCall.sol:18:3:
   |
18 | 		assert(x_prev == x);
   | 		^^^^^^^^^^^^^^^^^^^

Now the counterexample tells us that x can actually change during an unsafe external call. Furthermore, the solver synthesizes a reentrant call, performed by the externally called contract, that eventually causes the assertion to fail.

One way to solve this is by applying a mutex modifier to both setX and xMut:

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.6;

interface Unknown {
	function callme() external;
}

contract ExtCall {
	uint x;

	bool lock;
	modifier mutex {
		require(!lock);
		lock = true;
		_;
		lock = false;
	}

	function setX(uint y) mutex public {
		x = y;
	}

	function xMut(Unknown u) mutex public {
		uint x_prev = x;
		u.callme();
		assert(x_prev == x);
	}
}

Now the SMTChecker issues no warnings for the assertion, so it was proven safe. Similarly to the previous example, we can also ask for a proof artifact here, that being properties that are true for every unsafe external call in the contract. That can be done with Solidity >=0.8.10 by requesting reentrancy invariants in the settings.modelChecker object:

"invariants": [ "contract" ]

The property we get is:

Info: Reentrancy property(ies) for src/ExtCall.sol:ExtCall:
((lock' || !lock) && (<errorCode> <= 0) && (!lock || ((x' + ((- 1) * x)) = 0)))
<errorCode> = 0 -> no errors
<errorCode> = 1 -> Assertion failed at assert(x_prev == x)

The property may look a little complex, but it is rather simple. Primed state variables (x') represent the state variable after the external call returns, and non-primed state variables (x) represent its value before the call is made. The last term of the given conjunction is the most meaningful part of this property. After a small simplification, we see that it states that lock -> x' = x, that is, if the mutex variable lock is true at the moment of the external call, x must be the same when the call returns.


Note that CHC is the recommended engine, and you are advised to always set the single contract you want to be verified, as this helps the solver a lot. It may also be useful to set which verification targets you would like to be verified, as well as a custom timeout if the solver is failing at your properties.

You can find all these options and their description in the SMTChecker docs.

Other frameworks

The tool is of course not limited to only these two frameworks, and you can pretty much use the same technique above to enable the SMTChecker in development frameworks that allow the user to run solc in the standard JSON mode.

Final Remarks

Hopefully we got to a point where at least running the SMTChecker is considered easy. However, using it in a way that gives meaningful results can still be tricky. It is important to be aware of the model checker options, to tell the tool which specific contracts need to be verified, and to use the best engine.

It is also important to write properties about the contract. Those can be used as specification, and can be verified (at least attempted) by multiple tools, as seen in the Dapptools example above.

Lastly, the tools cannot do more than the underlying solvers they use. In the Formal Verification industry it is essential to try as many engines, solvers, and configurations as possible when dealing with complex problems and properties. It is often the case that one different parameter can cause the solver to go the right way and prove/disprove a property that other solvers and configurations may timeout or run out of memory. Currently the SMTChecker only uses one solver and one configuration by default, which causes it to not be able to answer many properties. It is possible, however, to use different solvers and any desired configuration.

Link: https://fv.ethereum.org/2021/12/01/smtchecker-dapptools/

#solidity  #blockchain  #ethereum #dapp #remix 

SMTChecker, Remix & Dapptools in Solidity

Comparación Entre Hardhat, Truffle Y Remix

Con el reciente auge del desarrollo de blockchain, muchos desarrolladores quieren conocer las mejores herramientas para comenzar a trabajar en este nuevo y sorprendente mundo. Si pasa 10 segundos buscando en Google o buscando consejos de las comunidades de blockchain, las opciones más populares de las que todos hablarán son Hardhat, Truffle y Remix.

Estos son entornos de desarrollo de blockchain realmente buenos para compilar, probar e implementar software de blockchain. Pero al final del día, es difícil no comenzar a hacer comparaciones de qué herramienta es la mejor para las necesidades de su proyecto y cuál le ahorrará tiempo y le brindará la mejor experiencia de desarrollo.

Este artículo es una comparación entre Hardhat, Truffle y Remix, centrándose en sus características y ecosistema para poder tomar una decisión sobre qué biblioteca usar para su caso de uso particular.

icono de casco¿Qué es Hardhat?

Hardhat fue creado por Nomic Labs , ayuda a los desarrolladores a administrar y automatizar las tareas comunes del proceso de creación de contratos inteligentes y Dapps, además de introducir fácilmente más funciones en torno a este flujo de trabajo. Eso significa que puede compilar, ejecutar y probar contratos inteligentes en su núcleo.

Se centra en la depuración de solidez, presenta seguimientos de pila explícitos y mensajes de error cuando fallan las transacciones. Hardhat viene integrado con Hardhat Network, una red Ethereum local diseñada para el desarrollo y una CLI para interactuar con las funcionalidades principales.

Ejemplo de la CLI de Hardhat:

$ npx hardhat
888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888


Welcome to Hardhat v2.0.8


? What do you want to do? …
❯ Create a sample project
  Create an empty hardhat.config.js
  Quit

Comandos de casco disponibles:

$ npx hardhat
Hardhat version 2.0.8


Usage: hardhat [GLOBAL OPTIONS] <TASK> [TASK OPTIONS]


GLOBAL OPTIONS:


  --config              A Hardhat config file.
  --emoji               Use emoji in messages.
  --help                Shows this message, or a task's help if its name is provided
  --max-memory          The maximum amount of memory that Hardhat can use.
  --network             The network to connect to.
  --show-stack-traces   Show stack traces.
  --tsconfig            Reserved hardhat argument -- Has no effect.
  --verbose             Enables Hardhat verbose logging
  --version             Shows hardhat's version.




AVAILABLE TASKS:


  accounts      Prints the list of accounts
  check         Check whatever you need
  clean         Clears the cache and deletes all artifacts
  compile       Compiles the entire project, building all artifacts
  console       Opens a hardhat console
  flatten       Flattens and prints contracts and their dependencies
  help          Prints this message
  node          Starts a JSON-RPC server on top of Hardhat Network
  run           Runs a user-defined script after compiling the project
  test          Runs mocha tests


To get help for a specific task run: npx hardhat help [task]

icono de trufa¿Qué es la trufa?

Truffle fue creado por Consensys , es un entorno de desarrollo, un marco de prueba y una canalización de activos para cadenas de bloques que utilizan Ethereum Virtual Machine (EVM). Con Truffle, obtiene muchas características importantes que pueden ayudarlo a desarrollar Dapps como una consola interactiva para la comunicación directa de contratos, administración de redes para implementar en cualquier red pública y privada, compilación de contratos, vinculación y administración binaria.

Otra parte del ecosistema de Truffle es Ganache , una cadena de bloques de Ethereum local para probar contratos de solidez, puede usar Ganache de dos maneras diferentes, puede usar Ganache CLI (la versión más completa) o puede usar Ganache UI (la versión más amigable especialmente para principiantes) depende de usted probar y ver qué versión prefiere.

Interfaz de usuario de Ganache

Interfaz de usuario de Ganache ejecutándose.

Tarde o temprano tendrá que desarrollar una interfaz de usuario para que las personas puedan comenzar a interactuar con sus Dapps, es por eso que Ganache tiene Drizzle una colección de bibliotecas front-end. El núcleo de Drizzle usa redux para que pueda usar todas las herramientas disponibles alrededor de redux y dejar la sincronización de los datos de contratos y transacciones en redux.

¿Qué es Remix?

Remix es una aplicación web y de escritorio de código abierto. Remix se usa para escribir, probar e implementar contratos inteligentes, puede usarlo como un patio de recreo para aprender y enseñar el desarrollo de blockchain. El IDE de Remix (cada vez que vea remix en este artículo, me refiero al IDE de Remix a menos que se especifique lo contrario) es parte del proyecto Remix, que es una plataforma para herramientas de desarrollo que utilizan una arquitectura de complemento.

Remix se compone de una cadena de subproyectos que incluyen Remix Plugin Engine, Remix Libs y, por supuesto, Remix IDE. Está escrito en javascript y es compatible con una versión de navegador y de escritorio.

remezclar IDE

El Remix IDE con código de solidez.

icono de cascoDocumentación

La documentación de Hardhat es muy clara y organizada, puede encontrar diferentes guías sobre cómo comenzar con hardhat desde los conceptos básicos de CLI para comenzar a ejecutar su cadena de bloques local hasta los aspectos centrales de Hardhat como las tareas, los complementos, el soporte de mecanografiado y cómo lidiar con diferentes marcos e integraciones.

Otra sección realmente útil de la documentación es la página del tutorial . Esta es una guía paso a paso para crear un contrato inteligente simple desde cero con la ayuda de Hardhat y cómo usar el código del contrato en el Front End con React. Esto es muy útil para comenzar a descubrir cómo usar Hardhat e incluso si es nuevo en el desarrollo de blockchain, es un buen recurso para saber cómo armar todo.

La desventaja de la documentación es que no encontrará muchos tutoriales o videos fuera de la documentación principal o de las comunidades internas, al menos en el momento de escribir este artículo. Lo bueno es que más empresas y desarrolladores están creando recursos y artículos sobre cómo usar funcionalidades simples y complejas, además de agregar comentarios sobre cómo resolver los problemas y problemas más comunes, esto es realmente crucial para aumentar la popularidad de cualquier biblioteca o marco.

icono de trufaDocumentación

La documentación de Truffle es clara y puede comenzar a aprender los conceptos básicos de cómo crear un proyecto, migrar con Truffle Develop o Ganache, conectar Truffle a metamask y comenzar a interactuar con los contratos.

Truffle tiene una sección de guías para guiarlo a las tareas comunes del desarrollo de Truffle, estas guías no son una guía paso a paso de un solo proyecto y no están tan actualizadas. El lado bueno es que Truffle no es una herramienta nueva para el desarrollo de blockchain, hay más artículos y tutoriales, por lo que puede encontrar muchos recursos debido a la longevidad y el ecosistema de desarrollo creado a su alrededor.

Documentación

La documentación de Remix está hecha de tal manera que incluso si no tiene experiencia en el desarrollo de software de cadena de bloques, le resultará fácil comenzar a aprender. Verá varias imágenes con flechas y texto para identificar cada herramienta de Remix, por lo que se familiarizará con ella muy rápido y comenzará a personalizar Remix según sus propias necesidades. La documentación no se limita solo a mostrarle partes de la interfaz de usuario, sino que le muestra cómo usar remix con diferentes integraciones, por ejemplo , Hardhat , cómo realizar pruebas unitarias y otros aspectos importantes para dominar Remix.

explicación del compilador de remixes

Ejemplo de documentación de Remix que explica la pestaña del compilador.

La otra parte buena es que actualizan la documentación con frecuencia, esto es algo muy bueno porque la documentación sobre las herramientas de blockchain generalmente no está actualizada y este es un aspecto importante para este entorno tan cambiante, incluso si ve un error, puede abrir un problema en Github o arregle eso, edítelo usted mismo e hizo una solicitud de extracción al repositorio de documentación.

remezclar documentos github editar

Puede editar la documentación de Remix si ve algún error o desea agregar más contenido.

icono de cascoComunidad

La comunidad es muy activa y útil, puede encontrar a los miembros principales y desarrolladores experimentados en el servidor oficial de Discord, allí puede encontrar muchos canales para diferentes temas relacionados con Hardhat y la ayuda amistosa de muchos miembros.

La desventaja de la comunidad es el hecho de que solo encontrará ayuda más específica en el servidor Discord, no hay un foro de soporte o muchas preguntas relacionadas o resueltas sobre Hardhat en lugares como StackOverflow porque es relativamente nuevo pero lo bueno es que esto cambiará con el tiempo y el uso.

icono de trufaComunidad

La comunidad de Truffle no está detrás de otras comunidades de desarrolladores, puede encontrar todos los canales de la comunidad en la sección de la comunidad del sitio web principal de Truffle, recomiendo hacer preguntas en el servidor Discord de Consensys, hay un canal solo sobre Truffle. Por lo tanto, puedes hacer todas las preguntas que tengas y tendrás una respuesta lo antes posible.

Puede encontrar respuestas cuando está atascado fuera de los principales canales de la comunidad, en lugares como StackOverflow o Stackexchange , la comunidad es grande, por lo que encontrar respuestas en estos lugares y otros tipos de blogs o foros es algo común.

icono de remezclaComunidad

La comunidad de Remix es muy solidaria, puede encontrar la respuesta a sus preguntas si está atascado en el canal principal del gitter y pedir ayuda a cualquier miembro de la comunidad.

Si desea ayudar a desarrollar un complemento personalizado o tiene dudas sobre cómo desarrollar un complemento para usted o la empresa en la que trabaja, puede ir al canal de colaboradores si desea obtener más información sobre cómo trabajar en las herramientas de Remix.

La comunidad tiene algún tiempo para encontrar respuestas en otros lugares fuera de la comunidad principal, cuando esté atascado, su fuente principal será StackOverflow y luego seguirá Stackexchange .

icono de cascoBibliotecas y complementos

Hardhat tiene un ecosistema completo en torno a los complementos. Los complementos son la columna vertebral de Hardhat, son piezas de configuración reutilizables que puede usar en cualquier tipo de proyecto, puede usar complementos oficiales creados por Hardhat, puede usar complementos creados por otros miembros de la comunidad de Hardhat o puede crear los suyos propios. .

Los complementos detrás de escena están ampliando el entorno de tiempo de ejecución de Hardhat (HRE) , definiendo nuevas tareas o anulando las existentes. Por ejemplo, puede crear un complemento para leer su código de solidez y crear ganchos listos para usar para React.

Puede crear un complemento básico y agregar esto ahardhat.config.js

// Will make hi available everywhere where the environment is accessible
extendEnvironment((hre) => {
  hre.hi = "Hello, Hardhat!";
});


task("envhello", (args, hre) => {
  console.log(hre.hi);
});


module.exports = {};
});

Producción:

$ npx hardhat envhello
Hello, Hardhat!

icono de trufaBibliotecas y complementos

El ecosistema de la Trufa gira en torno a las cajas . Las cajas de trufas son útiles repetitivos que aceleran el desarrollo de su proyecto para que pueda concentrarse en las partes importantes. Las cajas tienen una combinación de contratos de solidez, bibliotecas y front-end listos para usar, puedes encontrar cajas oficiales, hechas por la comunidad o puedes hacer las tuyas también.

Cada Box esencialmente gira en torno a un truffle-box.jsonarchivo de configuración. Este archivo dicta qué comandos se deben ejecutar en el punto de desempaquetado para que esté listo para funcionar. Si está comenzando desde cero, hay un cuadro de blueprint con el archivo de configuración con valores comunes.

// Example of truffle-box.json
{
  "ignore": ["README.md", ".gitignore"],
  "commands": {
    "Compile contracts": "truffle compile",
    "Migrate contracts": "truffle migrate",
    "Test contracts": "truffle test"
  },
  "hooks": {
    "post-unpack": ""
  }
}

La desventaja de las cajas es que no son flexibles cuando quieres cosas específicas. Debe usar el cuadro completo, no solo una parte de él, y cuando desea anular o extender Truffle para agregar una funcionalidad específica, como generar una gramática UML para cada contrato y usarla en diferentes proyectos, esta no es una funcionalidad fácil de usar. agregar.

icono de remezclaBibliotecas y complementos

Remix tiene un administrador de complementos, donde puede acceder a los complementos creados por el equipo de Remix ( compilador de solidez, prueba de unidad de solidez ) y realizados por otros miembros de la comunidad ( compilador de optimismo , celo ). Si hace clic en el ícono del complemento, verá la lista de todos los complementos disponibles, puede conectar los complementos locales creados por usted mismo cuando desee crear una funcionalidad personalizada de su proyecto.

lista de complementos de remezcla

El administrador de complementos de Remix con la lista de todos los complementos disponibles.

La desventaja de los complementos de Remix es que no hay una diversidad de complementos, pero esto se solucionará cuando el ecosistema de la cadena de bloques crezca y más desarrolladores participen en la codificación y proporcionen más complementos para cada marco.

icono de cascoPruebas

Para probar sus contratos inteligentes con Hardhat, debe usar javascript o mecanografiado. La opción más popular para probar sus contratos es la biblioteca Ethers.js para interactuar con los contratos inteligentes y Waffle para probar los contratos inteligentes (las pruebas que usan Waffle se escriben con Mocha y Chai ).

Ejemplo de la prueba usando Ethers.js y Waffle:

const { expect } = require("chai");
const { ethers } = require("hardhat");


describe("Greeter", function () {
  it("Should return the new greeting once it's changed", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy("Hello, world!");
    await greeter.deployed();


    expect(await greeter.greet()).to.equal("Hello, world!");


    const setGreetingTx = await greeter.setGreeting("Hola, mundo!");


    await setGreetingTx.wait();


    expect(await greeter.greet()).to.equal("Hola, mundo!");
  });
});

Producción:

$ npx hardhat test


  Contract: Greeter
    ✓ Should return the new greeting once it's changed (762ms)


  1 passing (762ms)

También puede usar Truffle y Web3.js para probar sus contratos inteligentes, con esto tendrá compatibilidad con el paquete @truffle/contract . Truffle 4 y Truffle 5 son compatibles con @nomiclabs/hardhat-truffle4 y @nomiclabs/hardhat-truffle5 .

Ejemplo de una prueba usando Web3.js y Truffle:

const Greeter = artifacts.require("Greeter");


// Truffle test
contract("Greeter", (accounts) => {
  it("Should return the new greeting once it's changed", async function () {
    const greeter = await Greeter.new("Hello, world!");
    assert.equal(await greeter.greet(), "Hello, world!");


    await greeter.setGreeting("Hola, mundo!");


    assert.equal(await greeter.greet(), "Hola, mundo!");
  });
});


describe("Greeter contract", function () {
  let accounts;


  before(async function () {
    accounts = await web3.eth.getAccounts();
  });


  describe("Deployment", function () {
    it("Should deploy with the right greeting", async function () {
      const greeter = await Greeter.new("Hello, world!");
      assert.equal(await greeter.greet(), "Hello, world!");


      const greeter2 = await Greeter.new("Hola, mundo!");
      assert.equal(await greeter2.greet(), "Hola, mundo!");
    });
  });
});

Producción:

$ npx hardhat test


Contract: Greeter
    ✓ Should return the new greeting once it's changed (265ms)


  Greeter contract
    Deployment
      ✓ Should deploy with the right greeting (114ms)




  2 passing (398ms)

icono de trufaPruebas

Truffle viene con un conjunto de bibliotecas de prueba para facilitar las pruebas desde el primer momento, la primera forma de probar sus contratos inteligentes es con javascript y mecanografiado. Truffle viene con Mocha, Chai y Web3.js para escribir pruebas de JavaScript.

const MetaCoin = artifacts.require("MetaCoin");


contract("2nd MetaCoin test", async (accounts) => {
  it("should put 10000 MetaCoin in the first account", async () => {
    const instance = await MetaCoin.deployed();
    const balance = await instance.getBalance.call(accounts[0]);
    assert.equal(balance.valueOf(), 10000);
  });


  it("should call a function that depends on a linked library", async () => {
    const meta = await MetaCoin.deployed();
    const outCoinBalance = await meta.getBalance.call(accounts[0]);
    const metaCoinBalance = outCoinBalance.toNumber();
    const outCoinBalanceEth = await meta.getBalanceInEth.call(accounts[0]);
    const metaCoinEthBalance = outCoinBalanceEth.toNumber();
    assert.equal(metaCoinEthBalance, 2 * metaCoinBalance);
  });


  it("should send coin correctly", async () => {
    const account_one = accounts[0];
    const account_two = accounts[1];
    let balance;


    const amount = 10;


    const instance = await MetaCoin.deployed();
    const meta = instance;


    balance = await meta.getBalance.call(account_one);
    const account_one_starting_balance = balance.toNumber();


    balance = await meta.getBalance.call(account_two);
    const account_two_starting_balance = balance.toNumber();
    await meta.sendCoin(account_two, amount, { from: account_one });


    balance = await meta.getBalance.call(account_one);
    const account_one_ending_balance = balance.toNumber();


    balance = await meta.getBalance.call(account_two);
    const account_two_ending_balance = balance.toNumber();


    assert.equal(
      account_one_ending_balance,
      account_one_starting_balance - amount,
      "Amount wasn't correctly taken from the sender"
    );
    assert.equal(
      account_two_ending_balance,
      account_two_starting_balance + amount,
      "Amount wasn't correctly sent to the receiver"
    );
  });
});

Producción:

Contract: MetaCoin
    √ should put 10000 MetaCoin in the first account (83ms)
    √ should call a function that depends on a linked library (43ms)
    √ should send coin correctly (122ms)




  3 passing (293ms)

La otra forma de hacer pruebas es en Solidity, para probar tus contratos en escenarios más avanzados. El marco de prueba de solidez de Truffle se creó teniendo en cuenta este tipo de problemas:

▪︎ Las pruebas de solidez no deben extenderse desde ningún contrato. Esto le da un control completo de los contratos que escribe.

▪︎ Las pruebas de solidez no deben estar sujetas a ninguna biblioteca de aserciones. Truffle viene con una biblioteca de afirmaciones predeterminada, pero puede cambiar esta biblioteca para que se ajuste a los requisitos de su proyecto.

▪︎ Debería poder ejecutar sus pruebas de solidez contra cualquier cliente de Ethereum.

Ejemplo de prueba de solidez:

pragma solidity >=0.4.25 <0.6.0;


import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MetaCoin.sol";


contract TestMetaCoin {
  function testInitialBalanceUsingDeployedContract() {
    MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin());


    uint expected = 10000;


    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
  }


  function testInitialBalanceWithNewMetaCoin() {
    MetaCoin meta = new MetaCoin();


    uint expected = 10000;


    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
  }
}

Producción:

$ truffle test


Compiling your contracts...
===========================
> Compiling ./test/TestMetaCoin.sol


  TestMetaCoin
    ✓ testInitialBalanceWithNewMetaCoin (65ms)


  Contract: MetaCoin
    ✓ should put 10000 MetaCoin in the first account (38ms)


  1 passing (7s)

Pruebas

Las pruebas con Remix se realizan solo con solidez y es la forma más fácil de implementar pruebas en sus contratos inteligentes, especialmente cuando está comenzando a aprender sobre el desarrollo de blockchain. El complemento de prueba de unidad de solidez ya está activo y verá un ejemplo de prueba de contrato para tener un ejemplo de cómo funcionan las pruebas dentro de Remix.

Ejemplo de prueba de solidez con Remix:

// SPDX-License-Identifier: GPL-3.0


pragma solidity >=0.7.0 <0.9.0;
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "../contracts/3_Ballot.sol";


contract BallotTest {


    bytes32[] proposalNames;


    Ballot ballotToTest;
    function beforeAll () public {
        proposalNames.push(bytes32("candidate1"));
        ballotToTest = new Ballot(proposalNames);
    }


    function checkWinningProposal () public {
        ballotToTest.vote(0);
        Assert.equal(ballotToTest.winningProposal(), uint(0), "proposal at index 0 should be the winning proposal");
        Assert.equal(ballotToTest.winnerName(), bytes32("candidate1"), "candidate1 should be the winner name");
    }


    function checkWinninProposalWithReturnValue () public view returns (bool) {
        return ballotToTest.winningProposal() == 0;
    }
}

Para ver si su prueba pasa o falla, haga clic en el ícono de verificación y haga clic en ejecutar para ejecutar sus pruebas. Si su prueba pasa, verá un texto verde. Si su prueba falla, verá una etiqueta roja. Puede investigar la razón por la que están fallando, habrá detalles de afirmación sobre la razón de la falla si hace clic en la prueba fallida, verá la línea de código donde falla la prueba.

ejemplo de prueba de remezcla de solidez

Prueba de remezcla usando el complemento de prueba de unidad de solidez.

Puede personalizar sus pruebas con solo unos pocos clics, como la versión compiladora de Solidity o la versión EVM para probar sus contratos inteligentes en diferentes escenarios.

pestaña de personalización de remezclas

Pestaña de personalización de remezclas.

icono de casco¿Qué empresas utilizan cascos?

zepelín abierto

OpenZeppelin proporciona productos de seguridad para crear, automatizar y operar aplicaciones descentralizadas. OpenZeppelin es la principal empresa de tecnología y servicios de ciberseguridad criptográfica, en la que confían los proyectos DeFi y NFT más utilizados para organizaciones líderes en criptografía, incluidas Coinbase, Ethereum Foundation, etc.

Optimismo

Optimism es una solución de escalado de Capa 2 para Ethereum que puede admitir todas las Dapps de Ethereum. En lugar de ejecutar todos los cálculos y datos en la red Ethereum, Optimism pone todos los datos de transacciones en la cadena y ejecuta los cálculos fuera de la cadena, lo que aumenta las transacciones de Ethereum por segundo y reduce las tarifas de transacción.

Aave

Aave es un protocolo descentralizado de mercado de liquidez sin custodia donde los usuarios pueden participar como depositantes o prestatarios. Los depositantes proporcionan liquidez al mercado para obtener un ingreso pasivo, mientras que los prestatarios pueden pedir prestado de forma sobrecolateralizada (perpetuamente) o subcolateralizada (liquidez de un bloque).

icono de trufa¿Qué empresas utilizan la trufa?

bitgo

BitGo es el líder en custodia, comercio y finanzas de activos digitales institucionales. BitGo permite a los clientes navegar por el complejo panorama de los activos digitales con un conjunto de soluciones conectadas, compatibles y seguras.

1 pulgada

El protocolo de 1 pulgada extrae muchos DEX para encontrar la plataforma más barata, teniendo en cuenta las tarifas y el precio del activo en sí. Este agregador DEX identifica automáticamente la operación más barata para ejecutar, lo que lo convierte en una herramienta valiosa para cualquier comerciante. En lugar de confiar en un solo protocolo DeFi para comprar un activo criptográfico

JPMorgan Chase & Co.

JPMorgan Chase & Co. es un banco de inversión multinacional estadounidense y un holding de servicios financieros con sede en la ciudad de Nueva York. es un importante proveedor de diversos servicios financieros y de banca de inversión. A partir de 2021, es el mayor prestamista de la industria de los combustibles fósiles en el mundo.

¿Qué empresas utilizan Remix?

Mar abierto

OpenSea es un mercado descentralizado de tokens no fungibles (NFT) para comprar, vender y comercializar NFT. OpenSea se marca a sí mismo como el mercado más grande para bienes digitales y se construyó a través de una colaboración eficiente y un entusiasmo por invertir en nuevas y emocionantes tecnologías.

Organización Ethereum

Ethereum.org es un recurso público de código abierto para la comunidad de Ethereum al que cualquiera puede contribuir, es un recurso educativo, diseñado para ayudar a los nuevos usuarios a familiarizarse con Ethereum y sus conceptos clave.

Rayo de luna

Moonbeam es una cadena de bloques orientada al desarrollador que se esfuerza por proporcionar compatibilidad con la cadena de herramientas y la red de desarrolladores de Ethereum existentes. Lo hace proporcionando una implementación EVM completa, una API compatible con Web3 y puentes que conectan Moonbeam a las redes Ethereum existentes.

icono de cascoicono de trufaicono de remezclaPopularidad

Afortunadamente para saber cuáles son los framework blockchain más utilizados puedes consultar los datos de la última encuesta de desarrolladores de Solidity 2020 . La encuesta recibió 193 respuestas de 48 países diferentes. En la pregunta sobre el entorno de desarrollo específico de Ethereum, Truffle fue la más popular con el 35 % de las respuestas, seguida de Remix con el 29 % y Hardhat con el 23 %.

Incluso si se trata de un pequeño número de personas que participan en esta encuesta, puede tener una idea de cómo se distribuyen estos marcos entre los desarrolladores de blockchain profesionales y aficionados.

Los marcos más populares de blockchain

Resultados de la encuesta de Solidity Developer Survey 2020 .

icono de cascoicono de trufaicono de remezclaConclusión

Con toda la información de este artículo, es posible que tenga una mejor idea de las opciones que le brindan las herramientas de desarrollo de blockchain más populares, tal vez incluso sepa qué opción desea comenzar con su próximo proyecto.

Mi consejo es que puede comenzar con Remix porque ni siquiera tiene que lidiar con la instalación de dependencias en su local y puede comenzar sin tantos problemas de codificación y aprender los conceptos básicos de solidez, prueba e implementación para probar net incluso mainnets.

Luego, puede optar por Hardhat debido a su naturaleza sin opiniones, puede instalar exactamente lo que desea y expandir el entorno de tiempo de ejecución de Hardhat, la buena documentación y la creciente comunidad es una de las razones por las que muchas empresas y yo mismo usamos Hardhat como nuestra principal herramienta de desarrollo de blockchain. .

Al final del día, lo único que debe hacer es comenzar con una herramienta y comenzar a crear cosas con ella, luego puede traducir todo el conocimiento que tiene a cualquier herramienta. Lo más importante es el conocimiento y la experiencia que llevará cualquier proyecto que desee sin preocuparse demasiado por la herramienta que está utilizando. 

Enlace: https://theblockchainguy.dev/hardhat-vs-truffle-vs-remix

 #remix #truffle #hardhat 

Comparación Entre Hardhat, Truffle Y Remix
藤本  結衣

藤本 結衣

1647236529

Hardhat、Truffle、Remixの比較

最近のブロックチェーン開発のブームに伴い、多くの開発者は、この新しくて素晴らしい世界で働き始めるための最良のツールを知りたがっています。10秒間グーグルをしたり、ブロックチェーンコミュニティのアドバイスを探したりする場合、誰もが話題にする最も人気のあるオプションは、ヘルメット、トリュフ、リミックスです。

これらは、ブロックチェーンソフトウェアをコンパイル、テスト、およびデプロイするための非常に優れたブロックチェーン開発環境です。しかし、結局のところ、どのツールがプロジェクトの必需品に最適で、どのツールが時間を節約し、最高の開発体験を提供するかを比較し始めるのは難しいことです。

この記事は、Hardhat、Truffle、およびRemixの比較であり、特定のユースケースに使用するライブラリを決定できるように、それらの特性とエコシステムに焦点を当てています。

ヘルメットアイコンヘルメットとは何ですか?

HardhatはNomicLabsによって作成され、開発者がスマートコントラクトとDappsを構築するプロセスの一般的なタスクを管理および自動化するのに役立ち、このワークフローにさらに多くの機能を簡単に導入できます。つまり、スマートコントラクトを非常にコアでコンパイル、実行、テストできるということです。

これは、Solidityデバッグに焦点を当てており、トランザクションが失敗したときに明示的なスタックトレースとエラーメッセージを表示します。Hardhatには、開発用に設計されたローカルイーサリアムネットワークであるHardhat Networkと、コア機能と対話するためのCLIが組み込まれています。

Hardhat CLIの例:

$ npx hardhat
888    888                      888 888               888
888    888                      888 888               888
888    888                      888 888               888
8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888
888    888     "88b 888P"  d88" 888 888 "88b     "88b 888
888    888 .d888888 888    888  888 888  888 .d888888 888
888    888 888  888 888    Y88b 888 888  888 888  888 Y88b.
888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888


Welcome to Hardhat v2.0.8


? What do you want to do? …
❯ Create a sample project
  Create an empty hardhat.config.js
  Quit

利用可能なヘルメットコマンド:

$ npx hardhat
Hardhat version 2.0.8


Usage: hardhat [GLOBAL OPTIONS] <TASK> [TASK OPTIONS]


GLOBAL OPTIONS:


  --config              A Hardhat config file.
  --emoji               Use emoji in messages.
  --help                Shows this message, or a task's help if its name is provided
  --max-memory          The maximum amount of memory that Hardhat can use.
  --network             The network to connect to.
  --show-stack-traces   Show stack traces.
  --tsconfig            Reserved hardhat argument -- Has no effect.
  --verbose             Enables Hardhat verbose logging
  --version             Shows hardhat's version.




AVAILABLE TASKS:


  accounts      Prints the list of accounts
  check         Check whatever you need
  clean         Clears the cache and deletes all artifacts
  compile       Compiles the entire project, building all artifacts
  console       Opens a hardhat console
  flatten       Flattens and prints contracts and their dependencies
  help          Prints this message
  node          Starts a JSON-RPC server on top of Hardhat Network
  run           Runs a user-defined script after compiling the project
  test          Runs mocha tests


To get help for a specific task run: npx hardhat help [task]

トリュフアイコントリュフとは何ですか?

Truffleは、Consensysによって作成され、Ethereum Virtual Machine(EVM)を使用するブロックチェーンの開発環境、テストフレームワーク、およびアセットパイプラインです。Truffleを使用すると、直接契約通信用のインタラクティブコンソール、パブリックおよびプライベートネットワークに展開するネットワーク管理、契約のコンパイル、リンク、バイナリ管理などのDappの開発に役立つ多くの重要な特性を利用できます。

Truffleエコシステムのもう1つの部分は、テストソリディティ契約用のローカルEthereumブロックチェーンであるGanacheです。GanacheCLI(最も完全なバージョン)を使用する方法と、Ganache UI(特に最も使いやすいバージョン)を使用する2つの異なる方法でGanache使用できます。初心者向け)は、どのバージョンを好むかをテストして確認するのはあなた次第です。

ガナッシュUI

GanacheUIが実行されています。

遅かれ早かれ、人々があなたのDappsと相互作用し始めることができるように、UIを開発する必要があります。そのため、GanacheはDrizzleにフロントエンドライブラリのコレクションを用意しています。Drizzleのコアはreduxを使用しているため、reduxで利用可能なすべてのツールを使用して、契約データとトランザクションデータの同期をreduxに任せることができます。

Remixとは何ですか?

Remixは、オープンソースのWebおよびデスクトップアプリです。Remixは、スマートコントラクトの作成、テスト、デプロイに使用され、ブロックチェーン開発を学習および指導するための遊び場として使用できます。Remix IDE(この記事でremixを見るたびに、特に明記しない限りRemix IDEについて話します)は、プラグインアーキテクチャを使用する開発ツールのプラットフォームであるRemixプロジェクトの一部です。

Remixは、Remix Plugin Engine、Remix Libs、そしてもちろんRemixIDEを含む一連のサブプロジェクトで構成されています。これはjavascriptで記述されており、ブラウザとデスクトップバージョンをサポートしています。

IDEをリミックスする

Solidityコードを使用したRemixIDE。

ヘルメットアイコンドキュメンテーション

Hardhatのドキュメントは非常に明確で整理されており、CLIの基本から、タスク、プラグイン、タイプスクリプトのサポートなどのHardhatのコアな側面まで、ローカルブロックチェーンの実行を開始する方法まで、さまざまなガイドを見つけることができます。さまざまなフレームワークと統合を処理します。

ドキュメントのもう1つの非常に役立つセクションは、チュートリアルページです。これは、Hardhatを使用して簡単なスマートコントラクトを最初から作成するためのステップガイドであり、フロントエンドでReactを使用してコントラクトコードを使用する方法です。これは、Hardhatの使用方法を理解するのに非常に役立ちます。ブロックチェーン開発に不慣れな場合でも、すべてをまとめる方法を知るための優れたリソースです。

ドキュメントの欠点は、少なくともこの記事を書いている時点では、メインのドキュメントや内部コミュニティの外に多くのチュートリアルやビデオがないことです。良いことは、より多くの企業や開発者が、単純な機能と複雑な機能の使用方法に関するリソースや記事を作成していることです。さらに、最も一般的な問題や問題を解決する方法に関するフィードバックを追加することは、ライブラリやフレームワークの人気を高めるために非常に重要です。

トリュフアイコンドキュメンテーション

Truffleのドキュメントは明確であり、プロジェクトの作成方法の基本を学び、TruffledevelopまたはGanacheで移行し、Truffleをメタマスクに接続して、コントラクトとの対話を開始できます。

Truffleには、Truffle開発の一般的なタスクをガイドするガイドセクションがあります。これらのガイドは、単一プロジェクトのステップバイステップガイドではなく、それほど更新されていません。良い面は、Truffleがブロックチェーン開発用の新しいツールではないことです。そこにはさらに多くの記事やチュートリアルがあり、その周りに構築された寿命と開発エコシステムのために多くのリソースを見つけることができます。

ドキュメンテーション

Remixのドキュメントは、ブロックチェーンソフトウェアの開発経験がなくても、簡単に学習できるように作成されています。Remixの各ツールを識別するための矢印とテキストが付いた複数の画像が表示されるので、非常にすばやく慣れて、必要に応じてRemixをカスタマイズし始めることができます。ドキュメントは、UIの一部を示すだけでなく、Hardhatなどのさまざまな統合でリミックスを使用する方法、単体テストを行う方法、およびリミックスをマスターするための他の重要な側面を示します。

リミックスコンパイラの説明

コンパイラタブを説明するRemixドキュメントの例。

他の良い部分は、ドキュメントを頻繁に更新することです。これは、ブロックチェーンツールに関するドキュメントが一般的に更新されないため、非常に良いことです。これは、エラーが発生した場合でも、問題を開くことができるこの非常に変化する環境にとって重要な側面です。自分で編集してドキュメントリポジトリにプルリクエストを行ったGithubまたは修正。

リミックスドキュメントgithub編集

エラーが表示された場合、またはコンテンツを追加したい場合は、Remixのドキュメントを編集できます。

ヘルメットアイコンコミュニティ

コミュニティは非常に活発で親切です。公式のDiscordサーバーでコアメンバーと経験豊富な開発者を見つけることができます。そこでは、ヘルメットに関連するさまざまなトピックの多くのチャネルと多くのメンバーの友好的な支援を見つけることができます。

コミュニティの欠点は、Discordサーバーでより具体的なヘルプが見つかるだけであり、StackOverflowのような場所では、Hardhatに関連する、または解決された多くの質問がないという事実です。これは比較的新しいためですが、良い部分はこれが変更されることです。時間と使用法で。

トリュフアイコンコミュニティ

Truffleのコミュニティは、他の開発者コミュニティに遅れをとっていません。メインのTruffle Webサイトのコミュニティセクションですべてのコミュニティチャネルを見つけることができます。ConsensysのDiscordサーバーで、Truffleに関するチャネルがあることを質問することをお勧めします。したがって、あなたはあなたが持っているすべての質問をすることができ、あなたはできるだけ早く答えを得るでしょう。

StackOverflowStackexchangeのような場所では、コミュニティが大きいため、メインのコミュニティチャネルの外で立ち往生しているときに答えを見つけることができるため、これらの場所や他の種類のブログやフォーラムで答えを見つけることは一般的です。

リミックスアイコンコミュニティ

Remixのコミュニティは非常に協力的です。Gitterのメインチャネルで立ち往生している場合は、質問の答えを見つけて、コミュニティのメンバーに助けを求めることができます。

カスタムプラグインの開発を手伝いたい場合、またはあなたやあなたが働いている会社のためにプラグインを開発することに疑問がある場合は、Remixツールでの作業についての詳細が必要な場合は、寄稿者のチャンネルにアクセスしてください。

コミュニティには、メインコミュニティ以外の場所で回答を見つけるための時間があります。行き詰まった場合、プライマリソースはStackOverflowになり、その後にStackexchangeが続きます。

ヘルメットアイコンライブラリとプラグイン

Hardhatには、プラグインを中心とした完全なエコシステムがあります。プラグインはHardhatのバックボーンであり、あらゆる種類のプロジェクトで使用できる再利用可能な構成の一部です。Hardhatが作成した公式プラグインを使用したり、Hardhatコミュニティの他のメンバーが作成したプラグインを使用したり、独自のプラグインを作成したりできます。

舞台裏のプラグインは、Hardhat Runtime Environment(HRE)を拡張し、新しいタスクを定義したり、既存のタスクをオーバーライドしたりしています。たとえば、Solidityコードを読み取るプラグインを作成し、Reactですぐに使用できるフックを作成できます。

これを追加する基本的なプラグインを作成できますhardhat.config.js

// Will make hi available everywhere where the environment is accessible
extendEnvironment((hre) => {
  hre.hi = "Hello, Hardhat!";
});


task("envhello", (args, hre) => {
  console.log(hre.hi);
});


module.exports = {};
});

出力:

$ npx hardhat envhello
Hello, Hardhat!

トリュフアイコンライブラリとプラグイン

トリュフの生態系はの周りにあります。トリュフボックスは、プロジェクトの開発をスピードアップするのに役立つ定型文であるため、重要な部分に集中できます。ボックスには、Solidity契約、ライブラリ、およびすぐに使用できるフロントエンドの組み合わせがあり、コミュニティによって作成された公式ボックスを見つけることができます。または、独自のボックスを作成することもできます。

各ボックスは基本的にtruffle-box.json構成ファイルを中心に展開します。このファイルは、開梱の時点で実行するコマンドを指定して、すぐに使用できるようにします。ゼロから始める場合は、共通の値を持つ構成ファイルを含む青写真ボックスがあります。

// Example of truffle-box.json
{
  "ignore": ["README.md", ".gitignore"],
  "commands": {
    "Compile contracts": "truffle compile",
    "Migrate contracts": "truffle migrate",
    "Test contracts": "truffle test"
  },
  "hooks": {
    "post-unpack": ""
  }
}

特定のものが必要な場合、ボックスの欠点は柔軟ではありません。ボックスの一部だけでなく、ボックス全体を使用する必要があります。Truffleをオーバーライドまたは拡張して、契約ごとにUML文法を生成し、さまざまなプロジェクトで使用するなど、特定の機能を追加する場合、これは簡単な機能ではありません。追加。

リミックスアイコンライブラリとプラグイン

Remixにはプラグインマネージャーがあり、Remixチーム(Solidityコンパイラー、 Solidityユニットテスト)およびコミュニティの他のメンバー( Optimismコンパイラーcelo )によって作成されたプラグインにアクセスできます。アイコンプラグをクリックすると、使用可能なすべてのプラグインのリストが表示されます。プロジェクトのカスタム機能を作成する場合は、自分で作成したローカルプラグインに接続できます。

リミックスプラグインのリスト

利用可能なすべてのプラグインのリストを含むRemixのプラグインマネージャー。

Remixのプラグインの欠点は、プラグインの多様性がないことですが、これは、ブロックチェーンエコシステムが成長し、より多くの開発者がコーディングに参加し、各フレームワークにより多くのプラグインを提供するときに修正されます。

ヘルメットアイコンテスト

Hardhatとのスマートコントラクトをテストするには、javascriptまたはtypescriptを使用する必要があります。コントラクトをテストするための最も一般的なオプションは、スマートコントラクトと対話するためのライブラリEthers.jsと、スマートコントラクトをテストするためのWaffleです(Waffleを使用したテストはMochaとChaiで作成されます

Ethers.jsとWaffleを使用したテストの例:

const { expect } = require("chai");
const { ethers } = require("hardhat");


describe("Greeter", function () {
  it("Should return the new greeting once it's changed", async function () {
    const Greeter = await ethers.getContractFactory("Greeter");
    const greeter = await Greeter.deploy("Hello, world!");
    await greeter.deployed();


    expect(await greeter.greet()).to.equal("Hello, world!");


    const setGreetingTx = await greeter.setGreeting("Hola, mundo!");


    await setGreetingTx.wait();


    expect(await greeter.greet()).to.equal("Hola, mundo!");
  });
});

出力:

$ npx hardhat test


  Contract: Greeter
    ✓ Should return the new greeting once it's changed (762ms)


  1 passing (762ms)

TruffleとWeb3.jsを使用してスマートコントラクトをテストすることもできます。これにより、 @ truffle/contractパッケージとの互換性が得られます。Truffle4とTruffle5は、 @ nomiclabs/hardhat-truffle4@nomiclabs/hardhat-truffle5を使用してサポートされています。

Web3.jsとTruffleを使用したテストの例:

const Greeter = artifacts.require("Greeter");


// Truffle test
contract("Greeter", (accounts) => {
  it("Should return the new greeting once it's changed", async function () {
    const greeter = await Greeter.new("Hello, world!");
    assert.equal(await greeter.greet(), "Hello, world!");


    await greeter.setGreeting("Hola, mundo!");


    assert.equal(await greeter.greet(), "Hola, mundo!");
  });
});


describe("Greeter contract", function () {
  let accounts;


  before(async function () {
    accounts = await web3.eth.getAccounts();
  });


  describe("Deployment", function () {
    it("Should deploy with the right greeting", async function () {
      const greeter = await Greeter.new("Hello, world!");
      assert.equal(await greeter.greet(), "Hello, world!");


      const greeter2 = await Greeter.new("Hola, mundo!");
      assert.equal(await greeter2.greet(), "Hola, mundo!");
    });
  });
});

出力:

$ npx hardhat test


Contract: Greeter
    ✓ Should return the new greeting once it's changed (265ms)


  Greeter contract
    Deployment
      ✓ Should deploy with the right greeting (114ms)




  2 passing (398ms)

トリュフアイコンテスト

Truffleには、箱から出してすぐにテストできるようにする一連のテストライブラリが付属しています。スマートコントラクトをテストする最初の方法は、javascriptとtypescriptを使用することです。Truffleには、JavaScriptテストを作成するためのMocha、Chai、およびWeb3.jsが付属しています。

const MetaCoin = artifacts.require("MetaCoin");


contract("2nd MetaCoin test", async (accounts) => {
  it("should put 10000 MetaCoin in the first account", async () => {
    const instance = await MetaCoin.deployed();
    const balance = await instance.getBalance.call(accounts[0]);
    assert.equal(balance.valueOf(), 10000);
  });


  it("should call a function that depends on a linked library", async () => {
    const meta = await MetaCoin.deployed();
    const outCoinBalance = await meta.getBalance.call(accounts[0]);
    const metaCoinBalance = outCoinBalance.toNumber();
    const outCoinBalanceEth = await meta.getBalanceInEth.call(accounts[0]);
    const metaCoinEthBalance = outCoinBalanceEth.toNumber();
    assert.equal(metaCoinEthBalance, 2 * metaCoinBalance);
  });


  it("should send coin correctly", async () => {
    const account_one = accounts[0];
    const account_two = accounts[1];
    let balance;


    const amount = 10;


    const instance = await MetaCoin.deployed();
    const meta = instance;


    balance = await meta.getBalance.call(account_one);
    const account_one_starting_balance = balance.toNumber();


    balance = await meta.getBalance.call(account_two);
    const account_two_starting_balance = balance.toNumber();
    await meta.sendCoin(account_two, amount, { from: account_one });


    balance = await meta.getBalance.call(account_one);
    const account_one_ending_balance = balance.toNumber();


    balance = await meta.getBalance.call(account_two);
    const account_two_ending_balance = balance.toNumber();


    assert.equal(
      account_one_ending_balance,
      account_one_starting_balance - amount,
      "Amount wasn't correctly taken from the sender"
    );
    assert.equal(
      account_two_ending_balance,
      account_two_starting_balance + amount,
      "Amount wasn't correctly sent to the receiver"
    );
  });
});

出力:

Contract: MetaCoin
    √ should put 10000 MetaCoin in the first account (83ms)
    √ should call a function that depends on a linked library (43ms)
    √ should send coin correctly (122ms)




  3 passing (293ms)

テストを行うもう1つの方法は、より高度なシナリオでコントラクトをテストするためのSolidityです。TruffleのSolidityテストフレームワークは、次のような問題を念頭に置いて作成されました。

▪︎Solidityテストはいかなる契約からも拡張されるべきではありません。これにより、作成する契約を完全に制御できます。

▪✧Solidityテストは、どのアサーションライブラリにも見られないようにする必要があります。Truffleにはデフォルトのアサーションライブラリが付属していますが、プロジェクトの要件に合わせてこのライブラリを変更できます。

▪︎任意のイーサリアムクライアントに対してSolidityテストを実行できるはずです。

堅牢性テストの例:

pragma solidity >=0.4.25 <0.6.0;


import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MetaCoin.sol";


contract TestMetaCoin {
  function testInitialBalanceUsingDeployedContract() {
    MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin());


    uint expected = 10000;


    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
  }


  function testInitialBalanceWithNewMetaCoin() {
    MetaCoin meta = new MetaCoin();


    uint expected = 10000;


    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
  }
}

出力:

$ truffle test


Compiling your contracts...
===========================
> Compiling ./test/TestMetaCoin.sol


  TestMetaCoin
    ✓ testInitialBalanceWithNewMetaCoin (65ms)


  Contract: MetaCoin
    ✓ should put 10000 MetaCoin in the first account (38ms)


  1 passing (7s)

テスト

Remixを使用したテストは、堅牢性のみを使用して行われ、特にブロックチェーン開発について学び始めたときに、スマートコントラクトにテストを実装する最も簡単な方法です。Solidityユニットテストプラグインはすでにアクティブになっており、Remix内でテストがどのように機能するかの例を示すコントラクトテストの例が表示されます。

Remixを使用した堅牢性テストの例:

// SPDX-License-Identifier: GPL-3.0


pragma solidity >=0.7.0 <0.9.0;
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "../contracts/3_Ballot.sol";


contract BallotTest {


    bytes32[] proposalNames;


    Ballot ballotToTest;
    function beforeAll () public {
        proposalNames.push(bytes32("candidate1"));
        ballotToTest = new Ballot(proposalNames);
    }


    function checkWinningProposal () public {
        ballotToTest.vote(0);
        Assert.equal(ballotToTest.winningProposal(), uint(0), "proposal at index 0 should be the winning proposal");
        Assert.equal(ballotToTest.winnerName(), bytes32("candidate1"), "candidate1 should be the winner name");
    }


    function checkWinninProposalWithReturnValue () public view returns (bool) {
        return ballotToTest.winningProposal() == 0;
    }
}

テストが合格か不合格かを確認するには、チェックアイコンをクリックし、[実行]をクリックしてテストを実行します。テストに合格した場合は緑色のテキストが表示され、テストが不合格の場合は赤色のラベルが表示されます。それらが失敗した理由を調べることができます。失敗したテストをクリックすると、失敗した理由のアサーションの詳細が表示され、テストが失敗したコード行が表示されます。

堅牢性リミックステストの例

Solidityユニットテストプラグインを使用してテストをリミックスします。

SolidityのコンパイラバージョンやEVMバージョンのように、数回クリックするだけでテストをカスタマイズして、さまざまなシナリオでスマートコントラクトをテストできます。

[カスタマイズ]タブをリミックスします

[カスタマイズ]タブをリミックスします。

ヘルメットアイコンどの企業がヘルメットを使用していますか?

ゼッペリンを開く

OpenZeppelinは、分散型アプリケーションを構築、自動化、運用するためのセキュリティ製品を提供します。OpenZeppelinは、Coinbase、EthereumFoundationなどの主要な暗号組織で最も使用されているDeFiおよびNFTプロジェクトから信頼されている最高の暗号サイバーセキュリティテクノロジーおよびサービス会社です...

楽観

Optimismは、イーサリアムのすべてのDappをサポートできるイーサリアムのレイヤー2スケーリングソリューションです。Optimismは、すべての計算とデータをイーサリアムネットワークで実行する代わりに、すべてのトランザクションデータをオンチェーンにし、計算をオフチェーンで実行して、1秒あたりのイーサリアムのトランザクションを増やし、トランザクション料金を減らします。

Aave

Aaveは、ユーザーが預金者または借り手として参加できる分散型の非保管流動性市場プロトコルです。預金者は市場に流動性を提供して受動的な収入を得る一方、借り手は担保過剰(永続的)または担保不足(1ブロックの流動性)で借りることができます。

トリュフアイコンどの会社がトリュフを使用していますか?

Bitgo

BitGoは、機関投資家向けデジタル資産の保管、取引、および財務のリーダーです。BitGoを使用すると、クライアントは、接続された、準拠した、安全なソリューションスイートを使用して、デジタル資産の複雑な状況をナビゲートできます。

1インチ

1inchのプロトコルは、多くのDEXをスクレイプして最も安いプラットフォームを見つけ、手数料と資産自体の価格を考慮します。このDEXアグリゲーターは、実行する最も安い取引を自動的に特定し、あらゆるトレーダーにとって価値のあるツールになります。暗号資産を購入するために単一のDeFiプロトコルに依存する代わりに

JPMorgan Chase&Co

JPMorgan Chase&Co。は、ニューヨーク市に本社を置く米国の多国籍投資銀行および金融サービス持株会社です。さまざまな投資銀行および金融サービスの主要プロバイダーです。2021年の時点で、それは世界で化石燃料産業への最大の貸し手です。

リミックスアイコンRemixを使用している企業は何ですか?

公海

OpenSeaは、NFTを購入、販売、および取引するための分散型非代替トークン(NFT)マーケットプレイスです。OpenSeaは、デジタル商品の最大の市場としての地位を確立し、無駄のないコラボレーションと刺激的な新技術への投資意欲によって構築されました。

イーサリアム組織

Ethereum.orgは、誰もが貢献できるイーサリアムコミュニティ向けの公開オープンソースリソースであり、新しいユーザーがイーサリアムとその主要な概念に慣れるために設計された教育リソースです。

月光

Moonbeamは、既存のイーサリアム開発者ツールチェーンおよびネットワークとの互換性を提供するよう努める開発者指向のブロックチェーンです。これは、完全なEVM実装、Web3互換API、およびMoonbeamを既存のEthereumネットワークに接続するブリッジを提供することによって実現されます。

ヘルメットアイコントリュフアイコンリミックスアイコン人気

幸いなことに、最も使用されているブロックチェーンフレームワークを知るには、前回のSolidity DeveloperSurvey2020のデータを参照してください。この調査では、48か国から193件の回答が寄せられました。イーサリアム固有の開発環境に関する質問では、回答の35%でトリュフが最も人気があり、次にリミックスが29%、ヘルメットが23%でした。

この調査に参加している少数の人々であっても、これらのフレームワークがプロやアマチュアのブロックチェーン開発者にどのように配布されているかを知ることができます。

ブロックチェーンの最も人気のあるフレームワーク

Solidity DeveloperSurvey2020の調査結果。

ヘルメットアイコントリュフアイコンリミックスアイコン結論

この記事のすべての情報を使用すると、最も人気のあるブロックチェーン開発ツールを提供するオプションについてより良いアイデアが得られるかもしれません。また、次のプロジェクトを開始するオプションを知っているかもしれません。

私のアドバイスは、ローカルに依存関係をインストールする必要さえないので、Remixから始めることができ、コーディングにそれほど問題なく始めることができ、メインネットでさえネットをテストするための堅牢性、テスト、およびデプロイメントの基本を学ぶことができるということです。

次に、その非ピニオンの性質のためにHardhatを使用できます。必要なものをインストールして、Hardhatランタイム環境を拡張できます。優れたドキュメントと成長するコミュニティは、多くの企業と私がHardhatをメインのブロックチェーン開発ツールとして使用する理由の1つです。 。

結局のところ、あなたがする必要があるのは、ツールから始めて、それを使って物を作り始めることだけです。そうすれば、あなたが持っているすべての知識を任意のツールに変換することができます。最も重要なことは、使用しているツールについてあまり心配することなく、必要なプロジェクトをリードする知識と経験です。 

リンク:https ://theblockchainguy.dev/hardhat-vs-truffle-vs-remix  

#hardhat #truffle #remix 

Hardhat、Truffle、Remixの比較
山本  洋介

山本 洋介

1647223620

Remix 1.0リリース, 特徴的なNested Routingについて解説!

Remix 1.0リリース, 特徴的なNested Routingについて解説! | Chrome96 | TypeScript 4.5 | Twitter AMPサポート廃止 【エンジニアニュース】

▶︎目次
0:00 Remix1.0 リリース
7:17 Chrome96 リリース
8:53 TypeScript 4.5
13:49 Twitter AMPのサポート終了

#remix #chrome96 #typescript 

Remix 1.0リリース, 特徴的なNested Routingについて解説!
최 호민

최 호민

1644831492

Gatsby vs. NextJS vs. Remix 개츠비 vs 넥스트JS vs 리믹스

리액트 프레임워크. 10분 완벽 정리!

개츠비 vs 넥스트JS vs 리믹스
그래서 저의 선택은...?

-
1:00 프레임워크. 라이브러리 차이점
1:33 클라이언트 사이드 렌더링 문제점
2:45 Gatsby 소개 
7:08 Remix 소개 
11:47 NextJS 소개

#리액트 #프레임워크 #코딩 #gatsby #next #remix #react 
 

Gatsby vs. NextJS vs. Remix 개츠비 vs 넥스트JS vs 리믹스
Felix Kling

Felix Kling

1643272481

Introduction to Remix | React Framework

What Is Remix? - What Is Web Development

Welcome to Remix!

We are happy you're here!

Remix is a full stack web framework that lets you focus on the user interface and work back through web fundamentals to deliver a fast, slick, and resilient user experience that deploys to any Node.js server and even non-Node.js environments at the edge like Cloudflare Workers.

Want to know more? Read the Technical Explanation of Remix

This repository contains the Remix source code. This repo is a work in progress, so we appreciate your patience as we figure things out.

Documentation

For documentation about Remix, please visit our website.

Also, please join our community on Discord.

The documentation is automatically generated on each release from the files in the docs directory.

Contributing

If you're interested in contributing code and/or documentation, please read this first.

Code of Conduct

Please see our code of conduct for any questions about the kind of community we are trying to build here and what to do if you need help with someone who is not acting professionally.

Download Details: 
Author: remix-run
Source Code: https://github.com/remix-run/remix 
License: MIT

#react #remix #webdev 

Introduction to Remix | React Framework

Comparison Between Next.js and Remix?

Next.js vs Remix : Next.js Might Not Be The Best Framework?

In this video, let's talk about how Remix compares to Next.js, and why Remix is a worthy competitor for Next.js. 

Timestamps
0:00 Teaser
1:18 Overview of Blog post
2:11 Remix likes Vercel
2:40 Is Remix as fast as Next.js?
4:08 How is Remix Different from Next.js?
7:02 Dynamic Page cache miss
10:04 Data Mutation
11:25 Handling Interruptions
12:22 Remix without Javascript
13:37 Conclusion
15:05 Outro


Remix vs Next.js


Easily the biggest question we get asked is something like:

How is Remix different from Next.js?

It appears we have to answer this question! We'd like to address it directly and without drama. If you're a fan of Remix and want to start tweeting smug reactions to this article, we kindly ask that you drop the smugness before hitting the tweet button 🤗. A rising tide lifts all boats. We've been friends with folks at Vercel long before Vercel was founded. They are doing great work and we respect the work they do!

But make no mistake, we think Remix has a better set of tradeoffs than Next.js. (Otherwise we wouldn't have built it...)

We encourage you to read this entire article. There is a lot of nuance in this conversation that's left un-captured in the shiny graphs and animations. By the end, hopefully you'll consider Remix for your next project (no pun intended 😂).

tl;dr

  • Remix is as fast or faster than Next.js at serving static content
  • Remix is faster than Next.js at serving dynamic content
  • Remix enables fast user experiences even on slow networks
  • Remix automatically handles errors, interruptions, and race conditions, Next.js doesn't
  • Next.js encourages client side JavaScript for serving dynamic content, Remix doesn't
  • Next.js requires client side JavaScript for data mutations, Remix doesn't
  • Next.js build times increase linearly with your data, Remix build times are nearly instant and decoupled from data
  • Next.js requires you to change your application architecture and sacrifice performance when your data scales
  • We think Remix's abstractions lead to better application code

Background

We figured the fairest way to compare the frameworks would be to take a Next.js example app that the Vercel team wrote themselves. Since they wrote it, the decisions they made should reflect how they intend you to build your app. It should also show off the features the Vercel team is most proud of.

We ported the Commerce Example from the Next.js examples page. It has a handful of real world features we liked, and seems to be the one they put the most effort into.

  • Initial page load is critical for ECommerce
  • Dynamic data on the search page
  • Data mutations with the shopping cart
  • Ability to integrate with multiple providers that illustrates how the frameworks help you abstract

We actually built two versions:

  • Minimal Port - We simply copy/pasted/tweaked the Next.js code to run on Remix instead of Next.js. This is deployed to Vercel just like the Next.js Demo. This is a great comparison of frameworks because everything but the framework is the same.
  • Rewrite - The two frameworks don't actually have a lot of API overlap and Remix can run on different infrastructure than Next.js. To really exercise Remix's design, we rewrote the example into idiomatic Remix, and even built a quick image optimization route into the app so it's 100% Remix.

Note that this app doesn't get to exercise everything we think is cool about Remix (like nested routes!). Once we answer this question, we can move on to just talking about Remix, so stay tuned!

Additionally, we shared this post with Vercel before publishing. Turns out their example was running on an older version of Next.js, they updated it, so we took the time to rework this to compare to their latest example.

Seriously, We Like Vercel

We consider them friends and even partners as Vercel is an excellent deployment target for Remix. I've deployed Remix apps to pretty much every hosting service I've ever heard of. Vercel's developer experience is easily my favorite. The "Develop, Preview, Ship" mantra has real effects. Just this morning @gt_codes and I were trying to figure out a production bug and having every preview deployment available with a little screenshot of each one helped us find the bad commit in seconds. It's good stuff.

Please read this post with that context. Let's get pushing!

Self-Descriptions

I think you can tell a lot about something by how the people who built it describe it. (If you follow me on twitter you'll know I've been iterating laboriously over ours!)

Next.js describes itself as:

The React Framework for Production. Next.js gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed.

Next.js is built by Vercel. Looking at the GitHub repo for the Vercel platform it states:

Vercel is a platform for static sites and frontend frameworks, built to integrate with your headless content, commerce, or database.

We describe Remix as:

Remix is an edge native, full stack JavaScript framework for building modern, fast, and resilient user experiences. It unifies the client and server with web fundamentals so you can think less about code and more about your product.

We'll leave it to you to contrast those descriptions.

Home Page, Visually Complete

Is Remix as fast as Next.js?

This is usually the first question people ask. Next.js often uses the phrase "performance by default" and they've got it in spades! Let's see how fast each app can render a "Visually Complete" page.

We ran the sites through WebPageTest. It's a great tool that generates the comparison gifs in this post. In every comparison, we gave each framework five runs and took the best one from each.

Above each comparison is a caption that links to the results that generated the animation. You are free to validate everything yourself by simply clicking "rerun test" on WebPageTest.com.

This first one was run from Virginia with a cable modem connection to the internet.

 

Home Page, Virginia, Cable

 

Remix loads in 0.7s, Next in 0.8s

Before we say anything, let's acknowledge that all three versions are so dang fast it's not even worth comparing who is faster. It's a bit unfair to Next.js too, because the little animation of the cookie banner factors into "visually complete" and the Remix site doesn't have it. Let's look at it in slow motion:

 

Home Page, Virginia, Cable, Slow-Mo

 

Remix loads in 0.7s, Next in 0.8s

Now we can see that Next.js is actually done 0.8s. Again, they are all fast. I also ran them all through the same test with a 3G network connection and it was the same story: all fast, all looked about the same.

✅ Remix is as fast as Next.js

Why The Apps Are Fast

Why Next.js is fast: The homepage uses Static Site Generation (SSG) with getStaticProps. At build time, Next.js pulls data from Shopify, renders a page to an HTML file and puts it in the public directory. When the site is deployed, the static file is now served at the edge (out of Vercel's CDN) instead of hitting an origin server at a single location. When a request comes in, the CDN simply serves the file. Data loading and rendering have already been done ahead of time so the visitor doesn't pay the download + render cost. Also, the CDN is distributed globally, close to users (this is "the edge"), so requests for statically generated documents don't have to travel all the way to a single origin server.

Why the Remix port is fast: Remix doesn't support SSG so we used the HTTP stale-while-revalidate caching directive (SWR, not be consfused with Vercel's swr client fetching package). The end result is the same: a static document at the edge (even on the same CDN, Vercel's). The difference is how the documents get there.

Instead of fetching all of the data and rendering the pages to static documents at build/deploy time, the cache is primed when you're getting traffic. Documents are served from the cache and revalidated in the background for the next visitor. Like SSG, no visitor pays the download + render cost when you're getting traffic. If you're wondering about cache misses, we'll discuss that a little later.

SWR is a great alternative to SSG. Another thing that makes deploying to Vercel great is that their CDN supports it.

You might wonder why the Remix port isn't as fast as Next.js. Since Remix doesn't have built-in image optimization (yet), we just pointed the images at the Next.js app 🤫. The browser has to open a connection to both domains and this delays the images from loading by 0.3s (you can verify this on the network waterfall). If the images were self-hosted, it would be right there with the other two around 0.7s.

Why the Remix rewrite is fast: Instead of caching documents at the edge with SSG or SWR, this version caches data at the edge in Redis. In fact, it actually runs the application at the edge too with Fly.io. Finally, it's got a quick image optimization Resource Route that writes to a persistent volume. It's basically its own CDN 😎.

This might have been difficult to build a few years ago, but the server landscape has changed significantly in the past few years and is only getting better.

Loading Dynamic Pages

How is Remix Different than Next.js?

This is the next question we get. There are a lot of differences in feature sets, but one major, architectural difference is that Remix doesn't rely on SSG for speed.

In practically every app, you will eventually hit a case that SSG can't support. For the application we're comparing here, it's the search page.

The constraint is that users can submit an infinite number of queries. With the universe's current constraints on space and time, you can't statically generate infinite pages. SSG is off the table.

 

Search Page, Cached, Virginia, Cable

 

Remix in 0.8s, Next.js 1.9

Because SSG doesn't scale to dynamic pages, Next.js switched to clientside data fetching from the user's browser. Taking a peak at the network waterfall will tell us why it's 2.3x slower than Remix.

Remix Search

Next.js Search

The Remix apps are completely done before the Next.js app even starts loading images. Perhaps the most important thing to get right in web performance is parallelizing the network waterfall. At Remix, we are fanatical about it.

Why Next.js is slower: Next.js introduced what we call a "network waterfall request chain". Because SSG can't be used here, the app is fetching the search results from the user's browser. It can't load images until it has fetched data, and it can't fetch data until it has loaded, parsed, and evaluated the JavaScript.

Fetching in the client also means more JavaScript over the network, and more time for parse/eval. Sometimes we forget about parse/eval, but you can see the JS execution on the 15th request took longer than the document did to download! Next.js is sending 1.5x more JavaScript than Remix with 566 kB vs. 371 kB unpacked. Over the network it's 50 kB more compressed (172 kB vs. 120 kB).

Doing more work in the browser starts to add up. Look at the bottom rows that show CPU utilization and the browser's main thread activity. The Next.js app is quite busy with a big red "long task" slowing things down.

Why Remix is still as fast as the homepage: Neither Remix example actually had to talk to the Shopify API in the request. While SSG can't cache the search page, the Remix versions can: with either SWR or Redis. When you have a single, dynamic way to generate pages, you can tweak your caching strategy without changing your application code. The result is SSG speed on commonly visited pages. The "/search" page will likely be primed, as well as the categories on the left nav and common queries like "tshirt".

Dynamic Page Cache Miss

Yeah, but what about a cache miss?

You're probably not going to believe me on this one, and I have no way to prove that our cache was empty, but here is a cache miss in Remix (cross my heart, swear to die, stick a needle in my eye).

 

Search Page, Empty Cache, Virginia, Cable

 

Remix loads in 3.9s, Next in 8s

Actually, I lied. That's a cache hit for the Remix Rewrite. The cache miss was faster (0.6s 🤭). I really didn't think you'd believe me, so I put the slower cache hit in the graphic 😅

Impossible!

Turns out the Shopify API is quite fast.

Since the Next.js app is fetching directly from the browser to the Shopify API, we can look at the network graph of the test and see that the request only took 224ms. It took longer for the browser to establish a connection with the API than to make the request! (They could speed that up with a <link rel="preconnect" /> in their initial HTML.)

If the user's browser could make the request to Shopify that quickly, the Remix server can certainly do it faster. The user's connection to the cloud is always going to be slower than your server's, probably best to keep the data fetching there.

Bottom line is, caching is nearly pointless when using the Shopify API. Cache hits or misses will be virtually indistinguishable from each other.

This is best illustrated by slowing down the user's network and seeing what happens. Let's do another cache miss, this time from Hong Kong on a 3G connection.

 

Search Page, Empty Cache, Hong Kong, 3G

 

Remix loads in 3.1s, Next in 6.6s

Next.js is now 3.5 seconds behind, even on a cache miss. What's up?

You said the Shopify API was fast!

Next.js can't load images until it loads data, it can't load data until it loads JavaScript, and it can't load JavaScript until the document loads. The user's network is a multiplier for every single step in that chain 😫.

In Remix, the only chain is waiting for the document to be able to load the images. The Remix design of always fetching on the server removes the user's network as a multiplier everywhere else.

Remix can start fetching from Shopify immediately when a request is received. It doesn't have to wait for the browser to download the document and then the JavaScript. It doesn't matter how slow the user's network is, the fetch to the Shopify API on the server doesn't change and is probably under 200ms.

Architectural Divergence

The user experience wasn't the only thing that took a hit when Next.js moved to fetching in the client. The app now has two different sets of abstractions for talking to Shopify: one set for SSG and another for the browser.

Architectural divergences like this bring up some major questions:

  • Do you have to authenticate in the browser?
  • Does the API support CORS?
  • Does the API SDK even work in the browser?
  • How do we share code between build and browser code?
  • Is it okay to expose the API token in the browser?
  • What permissions does our token that we just shipped to every visitor have?
  • Can this function use process.env?
  • Can this function read window.location.origin?
  • How do I make a network request that works in both places?
  • Can we cache these responses somewhere?
  • Should we make an isomorphic cache object that works in both places and pass it in to the different data fetching functions?

(omigosh I said isomorphic) (that's orthogonal to this post) (gah PROFUNCTOR OPTICS!)

Let's answer these questions for Remix, where you only have to abstract the Shopify API on the server:

  • Do you have to authenticate in the browser? (no)
  • Does the API support CORS? (doesn't matter)
  • Does the API SDK even work in the browser? (doesn't need to)
  • How do we share code between build and browser code? (you don't have to)
  • Is it okay to expose the API token in the browser? (don't need to)
  • What permissions does our token that we just shipped to every visitor have? (you didn't!)
  • Can this function use process.env? (yes)
  • Can this function read window.location.origin? (no)
  • How do I make a network request that works in both places? (however you want, it's not in the browser)
  • Can we cache these responses somewhere? (sure, HTTP, redis, lru-cache, persistent volume, sqlite...)
  • Should we make an isomorphic cache object that works in both places and pass it in to the different data fetching functions? (don't need to!)

The simpler these questions are to answer, the better your abstractions will be, resulting in simpler code to work with.

If the Next.js app moved away from client fetching, and used getServerSideProps, they would probably close the gap and have simpler answers to these questions. It's interesting to note that the Next.js docs push you away from server fetching and into SSG or client fetching often, though:

If you do not need to pre-render the data, then you should consider fetching data on the client side.

They also encourage client fetching for pages with user data, pushing you, again to more architectural divergence.

[Client fetching] works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is not relevant

As we've seen here, server rendering is about better performance, too, not just SEO.

The fundamental difference here is that Next.js has four "modes" for getting data on the page:

  • getInitialProps - called server and client side
  • getServerSideProps - called server side
  • getStaticProps - called at build time
  • client fetching - called in the browser

Remix only has one: loader. It's easier to abstract around one thing that only runs in one place than four things that run in three places.

The Cost of Architectural Divergence

Let's try to quantify the cost of this architectural divergence. Perhaps the most difficult development task of this app is abstracting the commerce back end. The app is designed in a way that you can plug anything into it: Shopify, BigCommerce, Spree, Saleor etc.

In the Next.js app, the Shopify integration lives in this folder. Running cloc on it today yields:

     101 text files.
      93 unique files.
       8 files ignored.

github.com/AlDanial/cloc v 1.92
---------------------------------------------------------------------
Language           files          blank        comment           code
---------------------------------------------------------------------
TypeScript            88            616           2256           5328
GraphQL                1           1610           5834           2258
Markdown               1             40              0             95
JSON                   2              0              0             39
JavaScript             1              1              0              7
---------------------------------------------------------------------
SUM:                  93           2267           8090           7727
---------------------------------------------------------------------

Almost 8,000 lines of code across nearly 100 files. I ran it for the other integrations and it's the same story. They're all approaching 100 files and hover around 10,000 lines of code. Nearly all of that code makes it to the browser, too.

Here is the Remix integration with Shopify.

  • 1 file
  • 608 lines of code
  • None of it goes to the browser

This, right here, is the cost of architectural divergence. The Next.js abstractions have to anticipate, and participate in the build and the browser. The Remix abstraction is only on the server.

You might wonder if the two Shopify providers have the same feature sets, and maybe we're being deceptive. There is some code in many of them for authentication and wishlists, but the Shopify provider didn't use either one (but did have to export modules for them). Using the two websites they appear to have the same feature set. Regardless, if we did miss something, it would be hard to imagine it would take 7,000 lines of code to get there when the visible features in the app only took 1/10th of that.

Even if Next.js moved to getServerSideProps for the search page, they'd still need almost all of that code for the data mutation features, but I'm getting ahead of myself now!

Edge Native

We talk a lot about "deploying to the edge". What does that mean? Here's another cache miss from Hong Kong, this time with a fast user network:

 

Search Page, Empty Cache, Hong Kong, Cable

 

Remix loads in 3.9s, Next in 8s

This time we're going to talk about the difference between the two Remix apps. We already know the Next.js version is slower because of the network waterfall chains.

Both Remix apps fetch on the server, so why is the Remix port so far behind the Remix Rewrite?

The answer is simple: the Remix Port is running in a Vercel function, and Vercel's functions don't run your code at the edge, they run in one region, defaulting to Washington DC. That's pretty far away from Hong Kong!

This means the user has to get all the way from Hong Kong to Washington, DC, before the server can start fetching the data from Shopify. When the server is done, it has to send the document all the way back.

The Remix Rewrite is running in Washington DC, too, but it's also running in Hong Kong! That means the user has a very quick hop to the Remix server where everything is going to be faster.

It's like riding your bike to the train to get into town, instead of riding your bike the whole way.

🚲-----------------------------------------🏢
🚲-----🚊====🏢

You can see this play out in the network waterfall (as usual):

Remix Rewrite @ Edge

Remix Port in US East

The infrastructure difference manifests in the first blue bar for the document. In the Remix Port, it's way bigger. That's the user riding their bike half way around the world in the Vercel function bike lane. In the Remix Rewrite, it got on the train and made it to the Shopify API and back much sooner.

This version runs on Fly.io that can run Node.js servers in dozens of regions around the world. Remix doesn't depend on Node.js though. It can run in any JavaScript environment. In fact, it already runs in Cloudflare Workers, which means you're running your code on their 250 servers distributed around the world. Can't get any closer to users than that!

This is why we say that Remix is "edge native". Next.js depends on Node.js so it's ability to deploy the edge is limited today.

We still have a lot of work to do in this area to make the developer experience better. We only officially support Node.js and Cloudflare right now, but we're actively working on Deno, and community members have Remix running on Fastly.

When you're using an "edge native" framework like Remix, you no longer have to decide which users get a faster experience. You can give every user a fast experience no matter where they are in the world.

The edge is what Remix was built for. As you can see, it's very promising. As we understand it, the Vercel team is working hard on deploying your apps to the edge, too. Remix is ready for it, we can't wait to try it out.

Clientside Transitions

Both frameworks enable instant transitions with link prefetching, but Next.js only does this for pages created from SSG. The search page is out, again. (maybe next time, sport)

However, Remix can prefetch any page because there was no architectural divergence for data loading. Prefetching an unknowable, user-driven search page URL is not any different than prefetching a knowable product URL.

In fact, Remix prefetching isn't limited to just links, it can prefetch any page, at any time, for any reason! Check this out, prefetching the search page as the user types:

Search Input Prefetching, Fast 3G

No spinners, no skeletons, instant user experiences, even on slow networks 🏎

This was super easy to do, too.

import { Form, PrefetchPageLinks } from "remix";

function Search() {
  let [query, setQuery] = useState("");
  return (
    <Form>
      <input type="text" name="q" onChange={(e) => setQuery(e.target.value)} />
      {query && <PrefetchPageLinks page={`/search?q=${query}`} />}
    </Form>
  );
}

Since Remix uses HTML's <link rel="prefetch"> (instead of an in memory cache like Next.js) the browser actually makes the requests, not Remix. Watching the video you can see how the requests are cancelled as the user interrupts the current fetch. Remix didn't have to ship a single character of code for that top-notch handling of asynchrony. #useThePlatform ... or, uh, #reuseThePlatform 😎?!

Data Mutations

This is where Remix and Next.js start to look completely different. Half of your app code is related to data mutations. It's time your web framework respects that.

How mutations work in Next.js: Next.js doesn't do anything for you here. <button onClick={itsAllUpToYou}>. Typically you'll manage the form's state to know what to post, add an API route to post to, track loading and errors states yourself, revalidate data and propagate changes throughout the UI, and finally deal with errors, interruptions, and race conditions (but let's be honest, nobody actually deals with that stuff).

How mutations work in Remix: Remix uses HTML forms. I know what you're thinking.

pffft ... I'm building a web app, this will never work.

You might think the API you're about to see looks incapable of handling the needs of a modern web app. Highly interactive web apps have been my entire career, Remix was designed with them in mind. Just because this looks like PHP from ye olden days doesn't mean it can't scale up to modern, sophisticated user experiences. We like to say that Remix scales up, but it scales down, too. So let's go back to ye olden days to help you understand Remix.

Since the dawn of the web, a mutation is modeled as a form and a server page to handle it. Ignoring Remix completely, it looks like this:

<form method="post" action="/add-to-cart">
  <input type="hidden" name="productId" value="123" />
  <button>Add to Cart</button>
</form>
// on the server at `/add-to-cart`
export async function action(request) {
  let formData = await request.formData();
  return addToCart(formData);
}

The browser navigates to "/add-to-cart" with a POST of the form's serialized data, adds pending UI, and renders a new page with all fresh data from your database when it's done.

Remix does the same thing as HTML forms, except optimized with capital-F <Form> and a function on your route named action (imagine your Next.js pages were their own API route). It posts with fetch instead of a document reload and then revalidates all the data on the page with the server to keep the UI in sync with the back end. This is the same thing you're used to doing in an SPA, except Remix manages it all for you.

There's no application code needed to communicate a mutation with the server other than the form and the serverside action. There are no application context providers or global state management tricks to propagate the change to the rest of the UI either. This is why the Remix bundles are nearly 30% smaller than the Next.js bundles, you don't need all that code to talk to your "API routes".

Oops, I lied again. That code actually works in Remix. If you use lowercase <form> the browser handles the post instead of Remix. Handy for situations where the JavaScript fails to load 😅 (more on that later)

You can scale up to fancy UI by asking Remix about the transition for busy spinners and progress or the data being posted to create optimistic UI. The model is HTML forms, the capability is anything your designers come up with. And you don't have to completely rearchitect your implementation to say "no problem, we can do that."

Smaller bundles and a simple mutation API aren't the only thing Remix does for you here, either.

Because Remix handles all of your interactions with the server (both data loading and data mutations), it has a unique ability in the web framework space to fix long-standing issues with web apps.

Unhandled Errors

What happens when the "add to cart" backend handler throws an error? Here we block requests to the routes that add items to the cart to see what happens.

Next.js Failed POST

Nothing happens. Error handling is difficult and annoying. Many developers just skip it as they did here. We think this is a terrible default user experience.

Let's see what happens in Remix.

Remix Failed POST

Remix handles every error around data and rendering in your app, even errors on the server.

All you have to do is define an error boundary at the root of your app. You can even get more granular and only take down the section of the page that had an error.

The only reason Remix can do this and Next.js can't is because Remix's data abstractions didn't stop with how to get data into your app, but also how to change it.

Interruptions

Users often click a button twice on accident and most apps don't deal with it very well. But sometimes you have a button that you fully expect the user to click really fast and want the UI to respond immediately.

In this app, the user can change the quantity of items in the cart. It's likely they'll click it very quickly to increment the number a few times.

Let's see how the Next.js app deals with interruptions

Next.js Interruption

It's a little difficult to see exactly what's happening, but if you scrub the video controls you can see it better. There's a weird thing from 5 to 6 to 5 in the middle. The final seconds are the most interesting though. You can see that the very last request sent lands (to go to 4) and then a couple frames later the very first request sent lands! The quantity fields jumps from 5, to 4, to 2, without any user interaction. Kind of hard UI to trust.

This code didn't manage race conditions, interruptions, or revalidation, so the UI is now possibly out of sync with the server (it depends if the 2 or the 4 was the last to hit the server side code). Managing interruptions and revalidating data after mutations would have prevented this.

I get it, dealing with race conditions and interruptions is hard! That's why most apps don't do it. The Vercel team is one of the most talented development teams in the industry and even they skipped it.

In fact, when we ported the React Server Components example built by the React Core team in our last blog post, they also had this same bug.

I said earlier that we are fanatical about the network tab. Let's see how Remix handles this.

Remix Interruption

You can see Remix cancels the request on interruptions and revalidates the data after the POST completes. This ensures that the UI across the entire page (not just this form) is in sync with whatever changes your form just made with the server.

You might think that maybe we just had more attention to detail in our app than the Next.js app. None of this behavior is in the application code. It's all built-in to Remix's data mutation APIs. (It's really just doing what the browser does with HTML forms...)

The seamless integration and transition between the client and server in Remix is unprecedented.

Remix ❤️ the Web

In our decades-long careers in web dev, we remember how simple it used to be. Put a button in a form, point it at a page that writes to the database, redirect, get the updated UI. It was so easy.

When designing Remix APIs, we always look to the platform first. Like the mutation workflow. We knew the HTML form API + a server side handler was right, so we built around that. It wasn't the goal, but a seriously amazing side effect is that the core features of an idiomatic Remix app work without JavaScript!

Remix Without JavaScript

While it's totally valid to use Remix this way, it's not our intent that you build websites without JavaScript. We've got a lot of ambition for building amazing user interfaces and you need JavaScript for that.

Instead of saying "Remix works without JavaScript" we prefer to say "Remix works before JavaScript". Maybe your user just went into a tunnel on the train as the page was loading the JavaScript. When they pop back out, the page will still generally work. We were really just going for the simplicity of HTML but we ended up with an incredibly resilient framework.

We look to the web platform for writing your server side code, too. Instead of inventing another new JavaScript request/response API, Remix uses the Web Fetch API. To work with URL search params, we use the built-in URLSearchParams. To work with form data, we use the built-in FormData.

export function loader({ request }) {
  // request is a standard web fetch request
  let url = new URL(request.url);

  // remix doesn't do non-standard search param parsing,
  // you use the built in URLSearchParams object
  let query = url.searchParams.get("q");
}

export function action({ request }) {
  // formData is part of the web fetch api
  let formData = await request.formData();
}

You will find that when you start learning Remix, you'll spend as much time on the MDN docs, if not more, than the Remix docs. We want Remix to help you build better websites even when you're not using it.

Get better at Remix, accidentally get better at the web.

It's a core value for us. While Remix apps are incredibly fast, we actually aren't hyper focused on performance, just great user and developer experiences. We look to the platform for answers to problems, make them easier to use, and the performance generally takes care of itself.

Optimizing for Change

Now that you know how both frameworks do things, let's see how the apps respond to change. I've always liked the phrase "optimize for change", and we talk about that a lot when we design Remix APIs.

Changing the Home Page

Let's consider you want to change the products on the home page, what does that look like? You have two choices in Next.js:

Rebuild and redeploy your app. Your build times will grow linearly with the number of products in your store (each build has to pull data from Shopify for every product). Simply changing a typo in your footer requires you to download every product from Shopify to deploy that change. As your store grows to thousands of products, this will become a problem.

Use Incremental Static Regeneration. Vercel recognizes the issue with build times in SSG, so they created ISR. When a page is requested, the server sends the cached version and then rebuilds it with fresh data in the background. The next visitor get's the newly cached version.

If the page wasn't built when you deployed, Next.js will server render the page and then cache it on the CDN. This is exactly what HTTP stale-while-revalidate does, except ISR comes with a non-standard API and vendor lock-in.

In Remix, you simply update your products with Shopify and your products will be updated within your caching TTL. You could also set up a webhook in an afternoon to invalidate the home page query.

This infrastructure is more work than going with SSG, but as we've seen in this article, it scales to any size product catalog, any kind of UI (the search page) and actually gets faster than SSG with more users (we can cache common search queries). You're also not coupled to a specific host, and barely coupled to a framework since Remix uses mostly standard web APIs for application logic.

Additionally, we think loading data in only one way, on the server, leads to cleaner abstractions.

What about cache misses?

This is a great question. Server and HTTP caching only work when your site is getting traffic. Turns out, your business only works when your site is getting traffic too 😳. You don't need two page views a day to be one second faster, you need a mailing list.

  • Empty cache hits on product pages in Remix are no slower than the search page in the Next.js site (where it can't use SSG). When was the last time you shopped online without searching? As that cache fills up with common queries, it gets even faster.
  • Common landing pages will be primed pretty much always, then Remix's prefetching makes the next transitions instant. Remix can prefetch any page, dynamic or otherwise, Next.js doesn't.
  • At a certain scale with SSG, you'll need to switch to ISR. Now you have the same cache miss problem on pages that weren't part of your last deployment

If cache miss requests are a significant portion of your visits, getting 100% cache hits won't fix your business: you don't have a technical problem, you have a marketing problem.

Personalization

Let's look at another change. Imagine the product team comes to you and says the home page is changing to display similar products to what the user has purchased in the past, instead of a set list of products.

Like the search page, SSG is out the door, and your performance by default with it. SSG really has a limited set of use cases.

Virtually every website has users. As your site grows, you're going to start showing the user more and more personalized information. Each time, that becomes a client side fetch. At some point, the majority of your page is client fetched and your performance is gone.

For Remix, this is just a different database query on the back end.

Consider the top of the ecommerce food chain: Amazon.com. That entire page is personalized. We already know the end from the beginning. Invest in architecture that will get you there, not stuff you'll need to drop when the product team tweaks the home page.

Bottom Line

It's easy to miss the power in Remix's deceptively simple <Form> + action + loader APIs and the design to keep as much on the server as possible. It changes the game. These APIs are the source of Remix's faster page loads, faster transitions, better UX around mutations (interruptions, race conditions, errors), and simpler code for the developer.

Remix apps get their speed from backend infrastructure and prefetching. Next.js gets its speed from SSG. Since SSG has limited use cases, especially as features and data scale, you will lose that speed.

SSG and the Jamstack were great workarounds for slow backend services. The latest generation of platforms and databases is fast and only getting faster. Even the Shopify API backing these apps can send a response to a query in 200ms from pretty much anywhere in the world, I tested it from every continent except Antarctica! (Going to need @chancethedev to try it out for me when he's there this month.)

It would honestly be totally acceptable to skip all caching strategies this article discussed and hit the Shopify API in each request on the server. Instead of a 1.2s load it would be 1.4. Instead of 0.8s it would be 1. Bupkis. If you've got a slow backend API, invest your time making your back end fast. If you don't have any control over it, deploy your own server and cache there where you can speed up any page for all users.

Investing in your back end will yield the same performance results as SSG, but it scales to any kind of page. It will require more initial work than SSG, but we think it's worth it for your users and your code in the long run.

Data loading is only half of the story, too. In Remix, your data abstractions can also encapsulate data mutations. All the code stays on the server, leading to better application code and smaller bundles in the browser.

With Next.js you have to ship your own data mutation code to the browser to interact with the API routes and propagate updates to the rest of the UI. As we saw in this article, even top teams mess this up around errors, interruptions, and race conditions.

Aren't you ignoring getServerSideProps?

Some folks say you can do all the things Remix does with getServerSideProps. This question comes from us not having a chance to explain Remix very well yet!

As mentioned before, this would definitely speed up the search page. However, you still have the data mutations to deal with. You'll need a combination of getServerSideProps, API routes, and your own browser code that communicates with them for mutations (including error handling, interruptions, race conditions, redirects, and revalidation). What we're really saying here is "you could build your own Remix". Indeed, you could. We already did 😇.

Phew!

Now that we've answered the big question everybody keeps asking us, our future posts will really start showing off what Remix can do!

#nextjs #remix #programming #react 

Comparison Between Next.js and Remix?
Crypto  Fan

Crypto Fan

1642651172

Create a token on Binance Smart Chain with Solidity for Beginners

In this video we will create a BEP20 token on the Binance Smart Chain.

It's a great way to write your first smart contract with Solidity, the programming language for Blockchain.

We will use Remix, an online code editor for Solidity. You don't need to install anything on your computer. Everything will be in your browser.

Solidity is an object-oriented, high-level programming language used to create smart contracts that automate transactions on the blockchain. After being proposed in 2014, the language was developed by contributors to the Ethereum project. The language is primarily used to create smart contracts on the Ethereum blockchain and create smart contracts on other blockchains.

Remix, more commonly known as Remix IDE, is an open-source Ethereum IDE you can use to write, compile and debug Solidity code. As such, Remix can be a hugely important tool in Web3 and dApps development. In short, if you’re looking for an answer to “what is Remix”, you’ve come to the right place! In the sections that follow, you will learn all you need to know about the basics of Remix. This information will help you decide whether or not it’s the proper tool you should take advantage of. On top of that, we’ll tell you about an amazing platform that enables you to skip time-consuming backend coding and still deploy excellent dApps.


Subscribe: https://www.youtube.com/c/EatTheBlocks/featured 

#solidity #remix #cryptocurrency #blockchain 

Create a token on Binance Smart Chain with Solidity for Beginners
Crypto  Fan

Crypto Fan

1642473078

How to Deploy Smart Contracts using Remix IDE

In this video, We will show you how to deploy smart contracts using Remix IDE (web app for Solidity development). As example, I created a simple contract that can receive and store ether. Owner of the contract can withdraw accumulated funds to any valid public address.

Smart contracts are computer programs that are hosted and executed on a blockchain network. Each smart contract consists of code specifying predetermined conditions that, when met, trigger outcomes. By running on a decentralized blockchain instead of a centralized server, smart contracts allow multiple parties to come to a shared result in an accurate, timely, and tamper-proof manner. 

Remix, more commonly known as Remix IDE, is an open-source Ethereum IDE you can use to write, compile and debug Solidity code. As such, Remix can be a hugely important tool in Web3 and dApps development. In short, if you’re looking for an answer to “what is Remix”, you’ve come to the right place! In the sections that follow, you will learn all you need to know about the basics of Remix. This information will help you decide whether or not it’s the proper tool you should take advantage of. On top of that, we’ll tell you about an amazing platform that enables you to skip time-consuming backend coding and still deploy excellent dApps.

Remix IDE: 
https://remix.ethereum.org/ 

Code from video:
https://gist.github.com/Chmarusso/d8d5349084b57c6f02c32ea30dbed79c 

Solidity official docs: 
https://docs.soliditylang.org/ 

Subscribe: https://www.youtube.com/c/ArturChmaro/featured 
 

#solidity  #ethereum  #smartcontract #remix 

How to Deploy Smart Contracts using Remix IDE
React Tutorial

React Tutorial

1642407601

Build a Simple MDX-based Blog using Remix and Tailwind CSS

Build Your Own Blog with Remix and Tailwind CSS, and deploy to Vercel!

In this quick tutorial we'll build a simple MDX-based (markdown) blog using Remix (a.k.a. "remix run" a new React framework) and Tailwind Typography. I'll also show how easy it is to deploy this to Vercel!

00:00 - Intro
01:07 - Installation and setup
02:56 - First MDX Route
03:47 - Markdown attributes
06:17 - Add Syntax Highlighting
11:15 - Add Tailwind and Typography plugin
15:49 - Create list of articles
19:11 - Deploying to Vercel
23:01 - Outro

#remix #react #tailwindcss #tailwind #webdev #markdown #vercel

Build a Simple MDX-based Blog using Remix and Tailwind CSS
React Tutorial

React Tutorial

1641869991

Making a Feature Flag Management System using Upstash Redis and Remix

Remix & Upstash Redis - Making a Feature Flag Management System

In this video we see how to use Upstash Redis together with Remix, focusing on data loaders and form actions. We'll also see how to submit multiple forms to the same action.

For more details check out the corresponding article https://blog.upstash.com/redis-with-remix 

Source Code - https://github.com/leighhalliday/remix-upstash-redis 

#react #remix #redis #database 

Making a Feature Flag Management System using Upstash Redis and Remix
Toby Rogers

Toby Rogers

1641523338

Remix JS Crash Course

Remix JS Crash Course

In this video, we will cover remix, the new JS framework.

Jokes App:
https://remix.run/docs/en/v1/tutorials/jokes 

Timeline:
0:00 - Introduction
3:50 - Creating a Remix App
15:56 - Route Handling
20:50 - Nested Routes
32:36 - Styling
48:42 - Creating a Database
1:01:00 - Fetching Data
1:10:09 - Fetching Data with Params
1:16:25 - Mutations

#remix #react #webdev 

Remix JS Crash Course