From 1d232fbbe3a8ee98bd9a3865b3cd82ce531d3bf3 Mon Sep 17 00:00:00 2001 From: Daniel Seidler Date: Fri, 9 May 2025 14:31:45 -0300 Subject: [PATCH 1/4] fix: translate and generic readme --- README.md | 59 +++------------------------------------------------ readmes/v1.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 56 deletions(-) create mode 100644 readmes/v1.md diff --git a/README.md b/README.md index dd25905..c7903e7 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,4 @@ -# Welcome -Welcome to this tutorial for learning how to make your own NEAR contract using rust. +# Sobre el proyecto +En este proyecto vamos a aprender a hacer contratos de NEAR con rust. Para esto, se aconseja seguir las instrucciones que se dan en los distintos archivos dentro de la carpeta `readmes/`. Están nombrados por versión, donde en cada caso se enseña algo nuevo. -For this tutorial we will be using rustc 1.80.1 (3f5fd8dd4 2024-08-06) - -This tutorial will asume you know some things and have installed some others. - -## Installing necessary packages -### Rust -For installing rust, follow the instructions in this [link](https://www.rust-lang.org/tools/install) - -This will install the most recent version of rust. Currently, NEAR is having some issues with the most recent version of rust. For this, we recommend you to downgrade to the version for this tutorial the following way - -``` -rustup install 1.80.1 -rustup default 1.80.1 -``` - -You can check it running `rustc --version` - -### Other packages -You can follow the instructions in the [NEAR documentation](https://docs.near.org/smart-contracts/quickstart). Just in case the contents change, we will paste the most relevant commands - -``` -# Contracts will be compiled to wasm, so we need to add the wasm target -rustup target add wasm32-unknown-unknown - -# Install NEAR CLI-RS to deploy and interact with the contract -curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh - -# Install cargo near to help building the contract -curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh -``` - -## Initialize your contract -With the following command we will have a basic NEAR contract ready for deployment with basic tests as well. This command will generate a `hello-near` folder. -``` -cargo near new hello-near -``` - -After this, we can check on `src/lib.rs` our contract with a set_greeting and get_greeting function and their corresponding tests. - -## Test your contract -### Using rust -Besides the mentioned tests, we have one more test on `tests/test_basics.rs`. If we want to run our rust tests, we can do it by simply running: -``` -cargo test -``` - -After running this command, the code will be compiled into a `target/` folder on the root of the project. Note this folder is included on the `.gitignore` file, so it is not necessary nor convinient to be shared in github, since we can generate it very easily. - -There are 2 types of tests on rust: -- Infile tests: tests that are written in a file and are supposed to test the functions defined on that file; -- Integration tests: written typically on a `tests` folder on the root of the project and should tests integrally the whole contract. - -## What else is relevant? -We also have the `Cargo.toml` file which is like the `package.json` file for node. We can include some configuration and our dependencies. We can search for dependencies in `https://crates.io/`. \ No newline at end of file +Para cada readme hay un branch con el nombre correspondiente. En cada branch, se hacen los cambios que se describen en el readme, agregando archivos y cambiando o agregando código. Se aconseja empezar con el instructivo en el branch v1 y seguir a partir de ahí. \ No newline at end of file diff --git a/readmes/v1.md b/readmes/v1.md new file mode 100644 index 0000000..6ca628e --- /dev/null +++ b/readmes/v1.md @@ -0,0 +1,56 @@ +# Bienvenidos +Bienvenidos a este tutorial para aprender a hacer tu propio contrato de NEAR utilizando rust. + +Para este tutorial, vamos a utilizar la versión 1.80.1 de rustc + +En este tutorial, se va a asumir cierto nivel de conocimiento y que se tienen ciertas cosas instaladas, como node y un manejo básico del mismo. + +## Instalando los paquetes necesarios +### Rust +Para instalar rust, sigan las instrucciones en el [sitio oficial de rust](https://www.rust-lang.org/tools/install) + +Esto va a instalar la versión más reciente de rust. En este momento, NEAR está teniendo ciertos problemas con la versión más reciente de rust. Por esto, les recomendamos que bajen la versión de rust para este tutorial de la siguiente forma: + +``` +rustup install 1.80.1 +rustup default 1.80.1 +``` + +Pueden verificarlo corriendo `rustc --version` + +### Otros paquetes +Pueden seguir las siguientes instrucciones en la [documentación de NEAR](https://docs.near.org/smart-contracts/quickstart). En caso que el contenido de la página cambie, se pegan los comandos más relevantes abajo. + +``` +# Contracts will be compiled to wasm, so we need to add the wasm target +rustup target add wasm32-unknown-unknown + +# Install NEAR CLI-RS to deploy and interact with the contract +curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh + +# Install cargo near to help building the contract +curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh +``` + +## Inicializar el código del contrato +Con el siguiente comando vamos a tener un contrato básico de NEAR listo para ser deployado con unos tests básicos. Esto también nos va a generar una carpeta `hello-near`. +``` +cargo near new hello-near +``` + +Luego de esto, podemos verificar en `src/lib.rs` nuestro contrato con las funciones set_greeting y get_greeting y sus tests correspondientes. + +## Testear tu contrato +Además de los tests unitarios mencionados, tenemos un test más en `tests/test_basics.rs`. Si queremos correr los tests, podemos hacerlo simplemente corriendo: +``` +cargo test +``` + +Luego de correr este comando, el código será compilado en la carpeta `target/` en la raiz del proyecto. Noten que esta carpeta ya está incluida en el archivo `.gitignore`, por lo que no es necesario ni conveniente subir esta carpeta a github, ya que se puede generar con mucha facilidad. + +Hay 2 tipos de tests en rust: +- Tests en el archivo: los tests son escritos en el mismo archivo que tienen las funciones que deben ser testeadas +- Tests de integración: generalmente escritos en la carpeta `tests/` que se encuentra en la raiz del proyecto y deberían testear todo el contrato. + +## ¿Qué más es importante? +También tenemos el archivo `Cargo.toml` que es como el `package.json` en node. Podemos incluir cierta configuración y nuestras dependencias. Podemos buscar dependencias en `https://crates.io/`. \ No newline at end of file From 34e00ac23b20cf9e1ed668566d60ad9d522cedc2 Mon Sep 17 00:00:00 2001 From: Daniel Seidler Date: Fri, 9 May 2025 14:48:23 -0300 Subject: [PATCH 2/4] fix: translate v2 --- README.md | 12 ------------ {previousReadmes => readmes}/v1.md | 0 readmes/v2.md | 14 ++++++++++++++ 3 files changed, 14 insertions(+), 12 deletions(-) delete mode 100644 README.md rename {previousReadmes => readmes}/v1.md (100%) create mode 100644 readmes/v2.md diff --git a/README.md b/README.md deleted file mode 100644 index df023e7..0000000 --- a/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Recommendation -The following is not necessary and you should be able to work properly without following this, but we recommend to avoid implementing the `Default` trait since in most cases we will not have a Default contract, but we will have some initialization params. So for this case, check how we change the Default trait for a simple implementation using the `init` macro and define the `new` function on the `src/lib.rs` file. - -We will also change the contract name for a more logic one. - -In case you'd rather still use the Default, we recommend for the purpose of this tutorial to still do it and try doing the same with just the `Default` trait, since all the following code will have this change done. - -We will also add to our Cargo.toml file into our dependencies the following line `borsh = "1.5.1"`. Borsh means `Binary Object Representation Serializer for Hashing` and will help us serialize and deserialize objects in order to improve storing data on the blockchain and recovering it. We want to do this for faster execution time and save storage cost. - -We will also need to adapt our tests for this new structure, but the code contract will remain the same way. - -After making all the fixes, we will need to build our project again by running `cargo build` and checking we have no error. \ No newline at end of file diff --git a/previousReadmes/v1.md b/readmes/v1.md similarity index 100% rename from previousReadmes/v1.md rename to readmes/v1.md diff --git a/readmes/v2.md b/readmes/v2.md new file mode 100644 index 0000000..d955c9b --- /dev/null +++ b/readmes/v2.md @@ -0,0 +1,14 @@ +# Recomendación +Lo siguiente no es necesario per se y se debería poder trabajar apropiadamente sin seguir esto, pero recomendamos evitar implementar el trait `Default`, ya que en general, no vamos a querer tener un contrato con valores por defecto, sino que vamos a elegir nuestros parámetros a la hora de inicializarlo. + +Así que para este caso, les recomendamos que cambien el trait Default por una simple implementación utilizando el macro `init` y definir la función `new` en el archivo `src/lib.rs`. + +También vamos a cambiar el nombre del contrato por uno más lógico. + +En caso de que prefieran seguir utilizando el trait Default, les aconsejamos que lo hagan luego de seguir el tutorial, con todo lo que aprendan, ya que el tutorial va a seguir asumiendo que esto no está y no vamos a poder garantizar que todo funcione exactamente igual, aunque es posible que si lo haga. + +También vamos a añadir en nuestro archivo Cargo.toml, en nuestras dependencias, la siguiente linea `borsh = "1.5.1"`. Borsh significa `Binary Object Representation Serializer for Hashing` y nos va a ayudar a serializar y deserializar objetos para mejorar el guardado y recuperación de información en la blockchain, de forma más rápida y utilizando el menor espacio de guardado posible. + +También necesitaremos adaptar nuestros tests a esta nueva estructura, pero el código del contrato, quedará igual. + +Luego de hacer estos arreglos, podremos buildear nuestro proyecto nuevamente corriendo `cargo build` y chequear que no haya error. \ No newline at end of file From b9f9cd79466e1f7d0018f573ce650094a5ea6e12 Mon Sep 17 00:00:00 2001 From: Daniel Seidler Date: Fri, 9 May 2025 14:50:13 -0300 Subject: [PATCH 3/4] fix: manual merge --- README.md | 4 ++++ readmes/v1.md | 43 +++++++++++++++++++++---------------------- 2 files changed, 25 insertions(+), 22 deletions(-) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..c7903e7 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# Sobre el proyecto +En este proyecto vamos a aprender a hacer contratos de NEAR con rust. Para esto, se aconseja seguir las instrucciones que se dan en los distintos archivos dentro de la carpeta `readmes/`. Están nombrados por versión, donde en cada caso se enseña algo nuevo. + +Para cada readme hay un branch con el nombre correspondiente. En cada branch, se hacen los cambios que se describen en el readme, agregando archivos y cambiando o agregando código. Se aconseja empezar con el instructivo en el branch v1 y seguir a partir de ahí. \ No newline at end of file diff --git a/readmes/v1.md b/readmes/v1.md index dd25905..6ca628e 100644 --- a/readmes/v1.md +++ b/readmes/v1.md @@ -1,25 +1,25 @@ -# Welcome -Welcome to this tutorial for learning how to make your own NEAR contract using rust. +# Bienvenidos +Bienvenidos a este tutorial para aprender a hacer tu propio contrato de NEAR utilizando rust. -For this tutorial we will be using rustc 1.80.1 (3f5fd8dd4 2024-08-06) +Para este tutorial, vamos a utilizar la versión 1.80.1 de rustc -This tutorial will asume you know some things and have installed some others. +En este tutorial, se va a asumir cierto nivel de conocimiento y que se tienen ciertas cosas instaladas, como node y un manejo básico del mismo. -## Installing necessary packages +## Instalando los paquetes necesarios ### Rust -For installing rust, follow the instructions in this [link](https://www.rust-lang.org/tools/install) +Para instalar rust, sigan las instrucciones en el [sitio oficial de rust](https://www.rust-lang.org/tools/install) -This will install the most recent version of rust. Currently, NEAR is having some issues with the most recent version of rust. For this, we recommend you to downgrade to the version for this tutorial the following way +Esto va a instalar la versión más reciente de rust. En este momento, NEAR está teniendo ciertos problemas con la versión más reciente de rust. Por esto, les recomendamos que bajen la versión de rust para este tutorial de la siguiente forma: ``` rustup install 1.80.1 rustup default 1.80.1 ``` -You can check it running `rustc --version` +Pueden verificarlo corriendo `rustc --version` -### Other packages -You can follow the instructions in the [NEAR documentation](https://docs.near.org/smart-contracts/quickstart). Just in case the contents change, we will paste the most relevant commands +### Otros paquetes +Pueden seguir las siguientes instrucciones en la [documentación de NEAR](https://docs.near.org/smart-contracts/quickstart). En caso que el contenido de la página cambie, se pegan los comandos más relevantes abajo. ``` # Contracts will be compiled to wasm, so we need to add the wasm target @@ -32,26 +32,25 @@ curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releas curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh ``` -## Initialize your contract -With the following command we will have a basic NEAR contract ready for deployment with basic tests as well. This command will generate a `hello-near` folder. +## Inicializar el código del contrato +Con el siguiente comando vamos a tener un contrato básico de NEAR listo para ser deployado con unos tests básicos. Esto también nos va a generar una carpeta `hello-near`. ``` cargo near new hello-near ``` -After this, we can check on `src/lib.rs` our contract with a set_greeting and get_greeting function and their corresponding tests. +Luego de esto, podemos verificar en `src/lib.rs` nuestro contrato con las funciones set_greeting y get_greeting y sus tests correspondientes. -## Test your contract -### Using rust -Besides the mentioned tests, we have one more test on `tests/test_basics.rs`. If we want to run our rust tests, we can do it by simply running: +## Testear tu contrato +Además de los tests unitarios mencionados, tenemos un test más en `tests/test_basics.rs`. Si queremos correr los tests, podemos hacerlo simplemente corriendo: ``` cargo test ``` -After running this command, the code will be compiled into a `target/` folder on the root of the project. Note this folder is included on the `.gitignore` file, so it is not necessary nor convinient to be shared in github, since we can generate it very easily. +Luego de correr este comando, el código será compilado en la carpeta `target/` en la raiz del proyecto. Noten que esta carpeta ya está incluida en el archivo `.gitignore`, por lo que no es necesario ni conveniente subir esta carpeta a github, ya que se puede generar con mucha facilidad. -There are 2 types of tests on rust: -- Infile tests: tests that are written in a file and are supposed to test the functions defined on that file; -- Integration tests: written typically on a `tests` folder on the root of the project and should tests integrally the whole contract. +Hay 2 tipos de tests en rust: +- Tests en el archivo: los tests son escritos en el mismo archivo que tienen las funciones que deben ser testeadas +- Tests de integración: generalmente escritos en la carpeta `tests/` que se encuentra en la raiz del proyecto y deberían testear todo el contrato. -## What else is relevant? -We also have the `Cargo.toml` file which is like the `package.json` file for node. We can include some configuration and our dependencies. We can search for dependencies in `https://crates.io/`. \ No newline at end of file +## ¿Qué más es importante? +También tenemos el archivo `Cargo.toml` que es como el `package.json` en node. Podemos incluir cierta configuración y nuestras dependencias. Podemos buscar dependencias en `https://crates.io/`. \ No newline at end of file From cbd8fadb0883fe9f7879e4ebafc2cb5f1137aa2b Mon Sep 17 00:00:00 2001 From: Daniel Seidler Date: Wed, 14 May 2025 12:02:03 -0300 Subject: [PATCH 4/4] refactor: near contract_state --- src/lib.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 98ecf80..904ec22 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,9 @@ // Find all our documentation at https://docs.near.org -use near_sdk::borsh::{BorshDeserialize, BorshSerialize}; -use near_sdk::{log, near_bindgen, PanicOnDefault}; +use near_sdk::{log, near, near_bindgen, PanicOnDefault}; // Define the contract structure -#[near_bindgen] -#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] +#[near(contract_state)] +#[derive(PanicOnDefault)] pub struct NearTutorialContract { greeting: String, }