1661240460
Root chain contracts for The OmiseGO Plasma Framework, a layer 2 scaling solution for Ethereum.
These contracts comprise the root chain component of an extensible plasma framework that can support many Minimal Viable Plasma (MVP) (Buterin) style plasma constructions. The framework features the ability to extend:
The framework includes a basic payment transaction type for UTXO transfers, with 4 inputs and 4 outputs. These transactions are secured under More Viable Plasma (MoreVP) (Fichter, Jones) exits.
The framework includes two token vaults, supporting ETH, ERC-20, and non-compliant ERC-20 tokens.
The child chain component of our plasma construction runs under Proof of Authority, with a single operator. The construction is secured by a distributed network of watchers. Detailed description of our child chain design is in Tesuji document.
The OmiseGO implementation of the child chain and watcher can be found in our elixir-omg GitHub repository.
You can learn more about OmiseGO and get started developing with our plasma framework at developer.omisego.co.
The easiest way to compile and deploy the contracts is with Truffle. Requires node.js >= 8.
All the code is in the plasma_framework
directory, so go there first.
cd plasma_framework
Next install the dependencies.
npm install
You can then compile the contracts.
npx truffle compile
Or run the tests
npm run test
The migration scripts can be configured in plasma_framework/config.js
. Various properties of the contracts can be set here, such as the minimum exit period. See the file itself for more details. By default the development
environment is used, but this can be set to production
via the DEPLOYMENT_ENV
environment variable.
You may also override the default exit period in development
with an environment variable MIN_EXIT_PERIOD
.
Deploying the contracts requires three accounts:
DEPLOYER
The account that actually deploys the contractsAUTHORITY
The account that used by the Child chain to submit blocks. It must not have made any transaction prior to calling the scripts i.e. its nonce must be 0.MAINTAINER
The account that can register new vaults, exit games, etc.Normally you will deploy the contracts using an Ethereum client that you run yourself, such as Geth or Parity. Those Ethereum client would have default accounts on the node itself. For local testing, you can leverage those accounts and deploy with --network local
flag. The first three accounts inside the Ethereum client would be the DEPLOYER
, MAINTAINER
, and AUTHORITY
account with the order.
You can also use a remote provider such as Infura that does not have control of the private key and accounts with --network remote
flag. In this case you'll need to know the private keys for the DEPLOYER
, AUTHORITY
and MAINTAINER
accounts. See truffle-config.js
for an example.
Run truffle, passing in the network e.g.
npx truffle migrate --network local
# or to deploy via a remote provider
npx truffle migrate --network remote
You can also run within the docker with the provided Dockerfile.
# run the following commands under the repo directory instead of under plasma_framework/
# build the docker image
docker build -t omisego/plasma-contract .
# deploy the contract
docker run --rm omisego/plasma-contracts npx truffle migrate --network remote
For more detail of the deploying scripts and the env vars to set, see deploying.md
We suggest running the following commands with an active python virtual environment ex. venv
. All the code is in the plasma_framework/python_tests
directory, so go there first.
Installing dependencies needed for compilation:
make init
Installing dependencies needed to run tests:
make dev
Building and running tests:
make test
Running slow (overnight) tests:
make runslow | tee raport.txt
We have code for load tests but is skipped by default. Currently it needs manual setup to run it locally. You should go to the test/loadTests/
folder to find the test you would like to enable. Remove the .skip
part on the test, and change it to .only
.
The load test would need a ETH network with super high block gas limit and high initial ETH fund for test accounts. You can do the following with ganache:
ganache-cli -e 10000000000000 -l 0xfffffffffff
Run the following command to run the test afterward:
npx truffle test --network loadTest
npm version patch -m "Fixed a bug in X"
Download details:
Author: omgnetwork
Source code: https://github.com/omgnetwork/plasma-contracts
License: Apache-2.0 license
#omg #blockchain #web3 #ethereum #truffle #ganache #solidity #javascript
1660959240
Initial Coin Offering(ICO) smart contract in Ethereum.
_Below are instructions to get started
git clone https://github.com/ac12644/ICO-Token.git
2. Install packages
npm install
3. Compile
truffle compile
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!
git checkout -b feature/AmazingFeature
)git commit -m 'Add some AmazingFeature'
)git push origin feature/AmazingFeature
)Author: ac12644
Source code: https://github.com/ac12644/ICO-Smart-Contract
License: MIT license
#solidity #smartcontract #blockchain #web3 #ethereum #dapp #truffle #ico
1660929660
Node.js
& npm
package manager is installed and accessible from the command line along with truffle
.The running examples and vulnerable contracts are in contract-samples
folder. See README.md Other folders contains token
or full
project examples that can be run for better understanding.
Make sure you have Ganache
test blockchain running locally in your machine. Run *.AppImage
with chmod a+x
from the download site.
$ cd ballot-example
$ truffle compile
...
Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
> Compiling ./contracts/Address.sol
> Compiling ./contracts/Ballot.sol
> Compiling ./contracts/Migrations.sol
$ truffle migrate
...
Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
> Everything is up to date, there is nothing to compile.
Network up to date.
$ truffle deploy
...
# For testing
$ truffle test
...
Using network 'development'.
Compiling your contracts...
===========================
✔ Fetching solc version list from solc-bin. Attempt #1
> Compiling ./test/4_Ballot_test.sol
✔ Fetching solc version list from solc-bin. Attempt #1
> Artifacts written to /tmp/test--288401-NgXp0VWd8kTu
> Compiled successfully using:
- solc: 0.7.6+commit.7338295f.Emscripten.clang
Contract: Address
[
'0x53756d6974000000000000000000000000000000000000000000000000000000',
'0x5261766900000000000000000000000000000000000000000000000000000000',
'0x52616a616e000000000000000000000000000000000000000000000000000000',
'0x5261676875000000000000000000000000000000000000000000000000000000',
'0x45746865724b696e670000000000000000000000000000000000000000000000',
'0x5368656b68617200000000000000000000000000000000000000000000000000',
'0x436f6e74726163746f7200000000000000000000000000000000000000000000',
'0x50756c75626b0000000000000000000000000000000000000000000000000000',
'0x426974636f696e4b696e67000000000000000000000000000000000000000000',
'0x44616f4865636b65720000000000000000000000000000000000000000000000'
]
✓ Should return 10 addresses (43ms)
1 passing (184ms)
Smart contract functions to run on the MetaCoin-example
folder.
$ truffle exec src/getAddress.js --network development --compile
$ truffle console
...
$ truffle(development)> let instance = await MetaCoin.deployed()
...
$ truffle(development)> let accounts = await web3.eth.getAccounts()
$ truffle(development)> instance.sendCoin(accounts[1], 10, {from: accounts[0]})
...
...
$ truffle(development)> .exit
Logging and running each command from truffle console can be tedious. We can use a script (written in JavaScript) to execute on development network. See (truffle-run.js)
$ truffle exec ./example_run.js --network development
...
Using network 'development'.
0xdAd324Ac3f539785b8E02329fFd34e7657a16064
99713108700000000000
...
Author: lahiri-phdworks
Source code: https://github.com/lahiri-phdworks/Solidity-Examples
#solidity #smartcontract #blockchain #web3 #ethereum #dapp #truffle #ganache
1659994200
A project for my Bachelor's Degree in Computer Science at University of Salerno.
Project description and introduction
In this section we introduce context informations for the project.
🎓 The Web DApp KryptoAuth is made with the aim of offering greater security during the authentication operation by exploiting the Ethereum Blockchain technology. The system allows any user to register and wait for a administrator gives him the permissions of "User" or "Admin" to carry out the operation of Login.
docs/javaDoc
directory and at the following link: Javadoc Link.docs/deliverables
directory and at the following link: DocumentationTechnical informations
Installation guide can be found in docs/deliverables
directory and at the following link: User manual
Author: Alberto-00
Source code: https://github.com/Alberto-00/Blockchain-Authentication
#spring #springboot #java #solidity #web33 #web3js #ganache #metamask #truffle #openzeppelin #blockchain
1659426768
Ethereum Blockchain allows us to write the code that gets executed on Ethereum Virtual Machine with Smart Contracts. That means all of the business logic of our application resides on the smart contract. It will read and write the data, transferring value and execute any business logic that we program on the blockchain.
In this tutorial, We will learn how to write the Smart Contract in Solidity Programming Langauge and deploy it to the local ethereum blockchain. If you are new to Blockchain world, then please check out my previous tutorial Ethereum Blockchain Tutorial From Scratch
See more at: https://appdividend.com/2018/04/09/how-to-create-your-first-smart-contract-in-solidity/
#smartcontract #solidity #blockchain #truffle
1658910770
In this tutorial, you'll learn how to build a Todo app with Solidity, Nextjs & Truffle. Kickstart your Blockchain Development career or take it to the next level with this course. This course is perfect for Beginners as well as Intermediate Developers.
#blockchain #solidity #web3 #nextjs #truffle
1658554620
npm install truffle -g
2. Setup repo
mkdir MyChainlinkProject
cd MyChainlinkProject/
3. Unbox
truffle unbox smartcontractkit/box
4. Install dependencies by running:
npm install
# OR...
yarn install
npm test
:warning: When pushing your code to Github, make sure that your MNEMONIC and RPC_URL are stored in a .env file and it is also in your .gitignore
For deploying to the kovan network, Truffle will use truffle-hdwallet-provider
for your mnemonic and an RPC URL. Set your environment variables $RPC_URL
and $MNEMONIC
before running:
npm run migrate:kovan
You can also run:
truffle migrate --network kovan --reset
If you want to use truffle commands.
:warning: Without a Chainlink node deployed locally, requests from smart contracts will not be responded to. We recommend you deploy to the Kovan network
If needed, edit the truffle-config.js
config file to set the desired network to a different port. It assumes any network is running the RPC port on 8545.
npm run migrate:dev
There are 3 helper scripts provided with this box in the scripts directory:
fund-contract.js
request-data.js
read-contract.js
In addition, for working with Chainlink Price Feeds and ChainlinkVRF there are folders respectively.
They can be used by calling them from npx truffle exec
, for example:
npx truffle exec scripts/fund-contract.js --network kovan
The CLI will output something similar to the following:
Using network 'kovan'.
Funding contract: 0x972DB80842Fdaf6015d80954949dBE0A1700705E
0xd81fcf7bfaf8660149041c823e843f0b2409137a1809a0319d26db9ceaeef650
Truffle v5.0.25 (core: 5.0.25)
Node v10.16.3
In the request-data.js
script, example parameters are provided for you. You can change the oracle address, Job ID, and parameters based on the information available on our documentation.
npx truffle exec scripts/request-data.js --network kovan
This creates a request and will return the transaction ID, for example:
Using network 'kovan'.
Creating request on contract: 0x972DB80842Fdaf6015d80954949dBE0A1700705E
0x828f256109f22087b0804a4d1a5c25e8ce9e5ac4bbc777b5715f5f9e5b181a4b
Truffle v5.0.25 (core: 5.0.25)
Node v10.16.3
After creating a request on a kovan network, you will want to wait 3 blocks for the Chainlink node to respond. Then call the read-contract.js
script to read the contract's state.
npx truffle exec scripts/read-contract.js --network kovan
Once the oracle has responded, you will receive a value similar to the one below:
Using network 'kovan'.
21568
Truffle v5.0.25 (core: 5.0.25)
Node v10.16.3
Download details:
Author: smartcontractkit
Source code: https://github.com/smartcontractkit/truffle-starter-kit
License: MIT license
#smartcontract #blockchain #oracle #chainlink #truffle
1658042760
Truffle Compile
to compile the smartcontracttruffle migrate --reset
to migrate your code to blockchainnpm start
the React will run on localhost:3000
truffle exec scripts/issue-token.js
to distribute the the reward to the investorsDownload Details:
Author: 0xdevnet
Source Code: https://github.com/0xdevnet/staking-and-reward
License:
#blockchain #solidity #smartcontract #web3 #metamask #truffle #metamask
1657950060
Blockchain Token Staking dApp built with React, Solidity, on Ethereum Ganache, Ropsten, Rinkeby testnet networks
*
*
*
*
*
*
*
*
*
Working Demo: https://ibnz-staking.netlify.app/
git clone https://github.com/ibnzUK/Token-Staking-dApp
)npm install
)npm run start
)truffle test
/scripts
foldertruffle exec scripts/changeAPY.js 0.137
this script takes 1 argument (daily APY), in this provided example, admin sets 0.137
daily APY truffle exec scripts/redistribute.js
or provide argument custom
if you want to redistribute custom rewards TestToken deployment
✓ token deployed and has a name (246ms)
TokenStaking deployment
✓ staking contract deployed and has a name (160ms)
✓ checking default APY value (179ms)
✓ checking custom APY value (128ms)
✓ staking contract has 500k TestTokens tokens inside (176ms)
TokenStaking stakeTokens function
✓ users balance is correct before staking (126ms)
✓ checking total staked before any stakes (126ms)
✓ approving tokens, staking tokens, checking balance (1259ms)
✓ checking contract balance after staking (156ms)
✓ checking user balance inside contract (131ms)
✓ checking total staked (136ms)
✓ testing if user is staking at the moment (148ms)
✓ testing if user has staked (145ms)
TokenStaking redistributeRewards function
✓ checking who can do redistribution (1059ms)
✓ checking TokenStaking balance (105ms)
✓ checking user balance (130ms)
TokenStaking unstakeTokens function
✓ unstaking and checking users balance after unstake (468ms)
✓ checking total staked (132ms)
TokenStaking [custom] staking/unstaking functions
✓ checking total custom staked before any stakes (132ms)
✓ checking users balance before staking (165ms)
✓ approving tokens, staking tokens, checking balance (1131ms)
✓ checking custom total staked (125ms)
✓ testing if user is staking at custom staking at the moment (147ms)
✓ testing if user has staked at custom staking (107ms)
✓ unstaking from custom staking and checking users balance (535ms)
Claim Tst
✓ trying to obtain 1000 test token (395ms)
Change custom APY value
✓ checking who can change APY (1115ms)
✓ checking new custom APY value (146ms)
Testing custom APY reward redistribution
✓ staking at customStaking (1299ms)
✓ redistributing rewards, checking who can redistribute (733ms)
✓ checking user balance after custom APY rewards (111ms)
For private Ethereum test network make sure Ganache is running on HTTP://127.0.0.1:7545
truffle-config.js
with your infura key and mnemonic key. You can reate files in top dirrectory under names .infuraKey
and .secret
and paste your keys in there.gitignore
your keystruffle compile
truffle migrate --reset
or for Ethereum test network (Rinkeby) run: truffle migrate --network rinkeby --reset
or change rinkeby
to ropsten
.ethKey
and for (Rinkeby) run: truffle run verify TestToken --network rinkeby
or change rinkeby
to ropsten
TokenStaking Smart Contract Address on Test NetWarning, known security issue, use at own risk
Front end functions to Claim for 1000 Tst
token and Redistribute rewards or Custom redistribution
are only for testing purpose and showcase of application. Do not include or use them in your final project.
Download Details:
Author: ibnzUK
Source Code: https://github.com/ibnzUK/Token-Staking-dApp
License:
1656117240
Conflux-Truffle
Conflux-Truffle is a development environment, testing framework and asset pipeline for Conflux, aiming to make life as an Conflux developer easier. With Conflux-Truffle, you get:
$ npm install -g conflux-truffle
For a default set of contracts and tests, run the following within an empty project directory:
$ cfxtruffle init
From there, you can run cfxtruffle compile
, cfxtruffle migrate
and cfxtruffle test
to compile your contracts, deploy those contracts to the network, and run their associated unit tests.
Conflux-Truffle comes bundled with a local development blockchain server that launches automatically when you invoke the commands above. If you'd like to configure a more advanced development environment we recommend you install the conflux-rust docker separately by running docker pull confluxchain/conflux-rust
at the command line.
Please see the change logs from here
Download Details:
Author: Conflux-Chain
Source Code: https://github.com/Conflux-Chain/conflux-truffle
License: MIT license
#Conflux #blockchain #smartcontract #truffle #javascript #solidity
1653034020
Trabajar con cualquier tecnología nueva puede ser una experiencia tanto emocionante como aterradora. Por un lado, puede que te entusiasme construir con un nuevo conjunto de herramientas. Pero saber elegir las adecuadas entre todas las herramientas disponibles también puede resultar abrumador.
Ya sea que recién esté comenzando a aprender Web3 o que sea un desarrollador experimentado, comprenderá bien esta abrumadora experiencia. Los desarrolladores deben tener conocimiento de los conceptos específicos de Web3, como cadenas de bloques y contratos inteligentes, y de una pila de herramientas completamente nueva para desarrollar estos conceptos. Sin embargo, los desarrolladores pueden desarrollar tecnologías Web3 de manera relativamente rápida y eficiente con los pasos correctos y las herramientas adecuadas.
Este artículo brindará una breve descripción general de los pasos necesarios para crear un contrato inteligente Web3. Al mismo tiempo, veremos cómo puede navegar esos pasos con éxito escribiendo, implementando y probando contratos inteligentes con una herramienta que ya conoce, Visual Studio Code (VS Code), y la extensión Truffle for VS Code .
Elegir las herramientas adecuadas
Después de aprender los fundamentos de blockchain y Ethereum, probablemente se inspiró para comenzar a aplicar su conocimiento para construir sus propios proyectos Web3. En el camino, es posible que haya recopilado una larga lista de herramientas de varios proyectos y tutoriales. En lugar de perdernos en esa lista, concentrémonos en explorar los pasos necesarios para iniciar un nuevo proyecto de contrato inteligente mediante el uso de una de esas herramientas, la extensión Truffle for VS Code, y explorar cómo puede ayudar a la creación, depuración e implementación de su contrato inteligente. , seguridad y otras áreas de desarrollo.
Creación de proyectos
Primero, echemos un vistazo a la creación de su proyecto inicial.
La trufa para la extensión del código VS
Un proyecto exitoso a menudo comienza con una buena configuración y estructura de archivos. Dado que pueden surgir muchos problemas por no configurar correctamente su proyecto, es crucial asegurarse de que la estructura de su archivo sea consistente e intuitiva en su nombre.
Una buena ventaja de usar la extensión Truffle para VS Code es que puede crear rápidamente un nuevo proyecto con la estructura correcta desde el principio, ya sea creando una nueva carpeta con una estructura de archivos con plantilla y archivos de inicio o simplemente creando un proyecto a partir de un Caja de trufas .
Comencemos un nuevo proyecto para ver cómo se ve una estructura de archivos adecuada. Primero, deberá instalar la extensión Truffle for VS Code. Para obtener instrucciones de instalación detalladas y obtener aún más información sobre sus capacidades, consulte esta publicación .
Una vez instalada la extensión, presione las teclas SHIFT + CTRL
/ CMD + P
para abrir la paleta de comandos. A continuación, escriba el comando Truffle New Solidity Project
y seleccione la opción "Crear proyecto básico". Después de elegir la ruta del proyecto, se creará un nuevo proyecto con la estructura de archivos adecuada.
Estructura de archivos adecuada
Como puede ver, el proyecto de plantilla tiene una carpeta que contiene contratos inteligentes, otra para migraciones a entornos de cadena de bloques, una tercera para scripts y otra carpeta para pruebas. El proyecto también incluye un archivo .gitignore
para almacenar información que no desea enviar a un repositorio, un acuerdo de licencia de código abierto y un truffle-config.js
archivo.
Esta estructura de archivos mantiene todo limpio y organizado, por lo que importar de un archivo a otro o ejecutar comandos de Truffle es sencillo y menos propenso a errores.
Depuración de su contrato
Desafortunadamente, no vivimos en un mundo perfecto donde nuestro código no tenga errores. Y al crear su contrato inteligente, encontrará mensajes de error que quizás no haya visto antes. La depuración de estas transacciones puede ser complicada si siempre necesita hacer referencia a un explorador de blockchain como Etherscan para obtener información.
Una solución es utilizar la función de depuración de transacciones a través de la extensión Truffle for VS Code. Para trabajar con el depurador, abra la paleta de comandos nuevamente y escriba Truffle Debug Transaction. Desde allí, puede ver los mensajes de transacción y trabajar con ellos paso a paso. Esto es importante para los desarrolladores, ya que los errores en una determinada transacción a menudo hacen que falle el próximo intento de transacción (como que los fondos no estén disponibles en una billetera específica).
Elija una transacción para depurar después de escribir el comando: Transacción de debut de trufa
Después de seleccionar una transacción, el depurador estará disponible. Aquí puede realizar funciones de depuración típicas, como entrar/salir/sobre, ver la pila de llamadas, ver ventanas, etc.
Las herramientas de depuración están disponibles después de elegir una transacción
Implementación de su contrato
Una vez que tenga un contrato inteligente en funcionamiento, es hora de implementarlo. Hay tres vías para acercarse aquí. La mejor práctica es implementar primero en una instancia de blockchain local para realizar pruebas, como Ganache . Luego, querrá implementarlo en una red de prueba para verificar que funciona correctamente en un entorno en vivo. Luego, solo después de que se completen todas las pruebas, puede iniciar su proyecto en la red principal. Todas estas pruebas lo ayudarán a evitar errores costosos y, a veces, irreversibles en sus contratos inteligentes.
Dentro de la extensión Truffle, puede implementar en los tres tipos de redes sin necesidad de salir de VS Code. Puede hacerlo haciendo clic con el botón derecho en el archivo .SOL que desea implementar y seleccionando "Implementar contratos".
Cree o implemente fácilmente contratos inteligentes después de hacer clic con el botón derecho en un archivo .sol
Blockchain local: usar el servicio Ganache es una forma sencilla de crear una cadena de bloques local con múltiples direcciones de billetera y probar Eth que puede usar para interactuar con su contrato inteligente. Puede crear una nueva red de Ganache en el panel Truffle — Networks en VS Code desde la extensión. Después de crear una red, puede iniciar/detener y reiniciar el servidor según sea necesario.
Cree o conéctese fácilmente a una red existente
Redes de prueba : las redes de prueba están diseñadas para funcionar de manera similar a la red principal de Ethereum, pero no tienen los costos financieros ni los riesgos de implementarse directamente en la red principal. El uso de una red de prueba es una excelente manera de comprender mejor cómo funcionará su contrato una vez implementado en la red principal.
Hay varias redes de prueba de Ethereum para elegir, y todas se pueden conectar mediante un servicio de proveedor de nodos, como Infura . Después de configurar su cuenta Infura dentro de la extensión, tiene acceso a sus proyectos Infura existentes o puede crear otros nuevos fácilmente.
Opciones para que las redes se desplieguen
Red principal : si las redes de prueba son como servidores de prueba para su código de contrato inteligente, implementar en la red principal es como llevar el código a producción. La importancia de probar su código de contrato inteligente no se puede enfatizar lo suficiente. Si hay errores o lagunas, los atacantes pueden explotarlos y lo harán. Estos errores pueden ser costosos tanto para las organizaciones como para los usuarios.
Veamos cómo podemos asegurar nuestro contrato utilizando las herramientas adecuadas y las mejores prácticas antes de implementarlo en la red principal.
Asegurando su contrato
La seguridad siempre debe ser una prioridad importante al desarrollar contratos inteligentes. Los piratas informáticos pierden millones de dólares en lo que parece ser una base regular. Como desarrollador de Web3, debe estar continuamente actualizado sobre las mejores prácticas de seguridad más recientes .
Ejecutar sus contratos inteligentes a través de herramientas como Diligence Fuzzing o su alternativa de código abierto, Scribble , puede ayudarlo a detectar muchas vulnerabilidades de seguridad comunes. Sin embargo, si su proyecto tiene como objetivo manejar los fondos de millones de usuarios, es una buena práctica auditar sus contratos inteligentes de manera profesional.
Aún así, los desarrolladores deben estar al tanto de las vulnerabilidades comunes mientras construyen sus proyectos. Un vector de ataque frecuente en Web3 es cuando los piratas informáticos usan bots para escanear contratos implementados en busca de posibles vulnerabilidades e información secreta, como claves privadas de billetera que quedan en el código de las pruebas. Usar una herramienta como Truffle Dashboard es una forma de evitar perder fondos y activos por errores de desarrollo.
Conecte su billetera MetaMask directamente al panel de Truffle
Truffle Dashboard elimina la necesidad de que los desarrolladores almacenen claves privadas dentro de un archivo de configuración en el proyecto Solidity. Los desarrolladores pueden realizar un proceso de configuración único para conectar su billetera Metamask a un tablero alojado localmente en el navegador. Una vez hecho esto, es suficiente usar la palabra clave del tablero en lugar de copiar y pegar claves en un archivo de configuración. También es compatible con otros marcos de desarrollo, como Hardhat.
Para usar Truffle Dashboard, instala la última versión de Truffle e ingresa el comando truffle dashboard
en tu terminal. Ahora, cualquier acción que hubiera requerido sus claves privadas puede enrutarse a través del tablero. Por ejemplo, para implementar su contrato, asegúrese de especificar el puerto adecuado en su truffle-config.js
archivo, luego haga clic con el botón derecho en su contrato para implementarlo y seleccione dashboard: 24012
. El valor predeterminado es 24012
.
Asegúrese de que el puerto correcto esté seleccionado en el archivo truffle-config.js
Seleccione la opción del tablero al implementar el contrato
¡Todas las transacciones se enrutan a través del panel de Truffle, por lo que ya no necesita compartir sus claves privadas!
Las herramientas adecuadas, el camino correcto a seguir
Construir un proyecto Web3 no tiene por qué ser complicado. Con las herramientas adecuadas, el camino a seguir se vuelve claro. Hay muchas maneras de mejorar su flujo de trabajo, pero tener a su disposición Truffle for VS Code Extension lo ayudará a trabajar de manera eficiente desde un entorno con el que quizás ya esté familiarizado. Este espacio se mueve bastante rápido y se crean nuevas herramientas todo el tiempo. Esperamos que este artículo le haya dado una idea de una manera fácil de optimizar el proceso de desarrollo mientras navega por la pila de herramientas de Web3.
1653033720
新しいテクノロジーを使用することは、刺激的で恐ろしい経験になる可能性があります。一方では、新しいツールセットを使用して構築することにワクワクするかもしれません。しかし、利用可能なすべてのツールの中から適切なツールを選択する方法を知ることも、圧倒される可能性があります。
Web3を学び始めたばかりでも、経験豊富なビルダーでも、この困難な経験をよく理解できます。開発者は、ブロックチェーンやスマートコントラクトなどのWeb3固有の概念と、これらの概念を開発するためのまったく新しいツールスタックについての知識を持っている必要があります。ただし、開発者は、適切な手順と適切なツールを使用して、Web3テクノロジを比較的迅速かつ効率的に構築できます。
この記事では、Web3スマートコントラクトを作成するために必要な手順の概要を説明します。同時に、既に知っているツールであるVisual Studio Code(VS Code)とTruffle for VS Code拡張機能を使用してスマートコントラクトを作成、展開、テストすることで、これらの手順をうまくナビゲートする方法についても見ていきます。
適切なツールの選択
ブロックチェーンとイーサリアムの基礎を学んだ後、あなたはおそらくあなた自身のWeb3プロジェクトを構築するためにあなたの知識を適用し始めるようにインスピレーションを得ました。途中で、さまざまなプロジェクトやチュートリアルからツールの長いリストを収集した可能性があります。そのリストに迷うのではなく、これらのツールの1つであるTruffle for VS Code拡張機能を使用して、新しいスマートコントラクトプロジェクトを開始するために必要な手順を調べ、スマートコントラクトの作成、デバッグ、展開にどのように役立つかを調べてみましょう。 、セキュリティ、およびその他の開発分野。
プロジェクトの作成
まず、最初のプロジェクトの作成を見てみましょう。
VSCodeExtensionのトリュフ
多くの場合、プロジェクトの成功は、適切なセットアップとファイル構造から始まります。プロジェクトを適切に設定しないと多くの問題が発生する可能性があるため、ファイル構造に一貫性があり、名前を直感的に理解できるようにすることが重要です。
Truffle for VS Code拡張機能を使用する利点は、テンプレート化されたファイル構造とスターターファイルを使用して新しいフォルダーを作成するか、または単にプロジェクトを作成することにより、最初から正しい構造で新しいプロジェクトをすばやく構築できることです。トリュフボックス。
新しいプロジェクトを開始して、適切なファイル構造がどのように見えるかを確認しましょう。まず、Truffle forVSCode拡張機能をインストールする必要があります。インストール手順の詳細とその機能の詳細については、この投稿を確認してください。
拡張機能がインストールされたら、キーSHIFT + CTRL
/を押しCMD + P
てコマンドパレットを開きます。次に、コマンドを入力してTruffle New Solidity Project
、[基本プロジェクトの作成]オプションを選択します。プロジェクトパスを選択すると、適切なファイル構造で新しいプロジェクトが作成されます。
適切なファイル構造
ご覧のとおり、テンプレートプロジェクトには、スマートコントラクトを含むフォルダー、ブロックチェーン環境への移行用のフォルダー、スクリプト用のフォルダー、テスト用のフォルダーがあります。このプロジェクトには.gitignore
、リポジトリにプッシュしたくない情報を保存するための、オープンソースライセンス契約、およびtruffle-config.js
ファイルも含まれています。
このファイル構造により、すべてがきちんと整理された状態に保たれるため、あるファイルから別のファイルにインポートしたり、Truffleコマンドを実行したりするのは簡単で、エラーが発生しにくくなります。
契約のデバッグ
残念ながら、コードにエラーがない完璧な世界には住んでいません。また、スマートコントラクトを構築するときに、これまでに見たことのないエラーメッセージが表示されます。情報を得るためにEtherscanのようなブロックチェーンエクスプローラーを常に参照する必要がある場合、これらのトランザクションのデバッグは難しい場合があります。
1つの解決策は、TruffleforVSCode拡張機能を介してデバッグトランザクション機能を使用することです。デバッガーを操作するには、コマンドパレットを再度開き、TruffleDebugTransactionと入力します。そこから、トランザクションメッセージを表示し、それらを段階的に処理できます。特定のトランザクションでエラーが発生すると、次のトランザクションの試行が失敗することがよくあるため、これは開発者にとって重要です(特定のウォレットで資金が利用できないなど)。
次のコマンドを入力した後、デバッグするトランザクションを選択します。Truffle debut transaction
トランザクションを選択すると、デバッガーが使用可能になります。ここでは、ステップイン/アウト/オーバー、コールスタックの表示、ウィンドウの監視などの一般的なデバッグ機能を実行できます。
トランザクションを選択すると、デバッグツールが利用可能になります
契約の展開
スマートコントラクトが機能するようになったら、デプロイするときが来ました。ここにアプローチする方法は3つあります。ベストプラクティスは、最初にGanacheなどのテスト用のローカルブロックチェーンインスタンスにデプロイすることです。その後、テストネットにデプロイして、ライブ環境で正しく機能していることを確認します。次に、すべてのテストが完了した後でのみ、プロジェクトをメインネットに起動できます。このすべてのテストは、スマートコントラクトのコストがかかり、場合によっては元に戻せないエラーを回避するのに役立ちます。
Truffle拡張機能内では、VS Codeを離れることなく、3つのタイプのネットワークすべてにデプロイできます。これを行うには、デプロイする.SOLファイルを右クリックし、[コントラクトのデプロイ]を選択します。
.solファイルを右クリックした後、スマートコントラクトを簡単に構築または展開できます
ローカルブロックチェーン:Ganache Serviceを使用すると、複数のウォレットアドレスを使用してローカルブロックチェーンを作成し、スマートコントラクトとのやり取りに使用できるEthをテストする簡単な方法です。拡張機能から、VSCodeのTruffle—Networksペインの下に新しいGanacheネットワークを作成できます。ネットワークを作成した後、必要に応じてサーバーを起動/停止および再起動できます。
既存のネットワークを簡単に作成または接続
テストネット:テストネットはイーサリアムのメインネットと同じように機能するように設計されていますが、メインネットに直接展開するための経済的コストやリスクはありません。テストネットを使用することは、メインネットにデプロイされたときにコントラクトがどのように機能するかをよりよく理解するための優れた方法です。
選択できるイーサリアムテストネットはいくつかあり、それらはすべて、Infuraなどのノードプロバイダーサービスを使用して接続できます。拡張機能内でInfuraアカウントを設定すると、既存のInfuraプロジェクトにアクセスしたり、新しいプロジェクトを簡単に作成したりできます。
展開するネットワークのオプション
メインネット:テストネットがスマートコントラクトコードのステージングサーバーのようなものである場合、メインネットへのデプロイはコードを本番環境にプッシュするようなものです。スマートコントラクトコードをテストすることの重要性を十分に強調することはできません。エラーや抜け穴がある場合、攻撃者によって悪用される可能性があります。これらの間違いは、組織とユーザーの両方にとって同様にコストがかかる可能性があります。
メインネットに展開する前に、適切なツールとベストプラクティスを使用して契約を保護する方法を見てみましょう。
契約の確保
スマートコントラクトを開発するときは、セキュリティを常に最優先する必要があります。定期的に何百万ドルもハッカーに失われています。Web3開発者は、最新のセキュリティのベストプラクティスを常に最新の状態に保つ必要があります。
Diligence Fuzzingやそのオープンソースの代替手段であるScribbleなどのツールを使用してスマートコントラクトを実行すると、多くの一般的なセキュリティの脆弱性を見つけるのに役立ちます。ただし、プロジェクトが数百万人のユーザーの資金を処理することを目的としている場合は、スマートコントラクトを専門的に監査することをお勧めします。
それでも、開発者はプロジェクトを構築する際に一般的な脆弱性に注意する必要があります。Web3で頻繁に発生する攻撃ベクトルの1つは、ハッカーがボットを使用して、デプロイされたコントラクトをスキャンし、潜在的な脆弱性や、テストでコードに残されたウォレットの秘密鍵などの秘密情報を探す場合です。Truffle Dashboardのようなツールを使用することは、開発ミスによる資金と資産の損失を回避する1つの方法です。
MetaMaskウォレットをTruffleダッシュボードに直接接続します
Truffleダッシュボードにより、開発者はSolidityプロジェクトの構成ファイル内に秘密鍵を保存する必要がなくなります。開発者は、メタマスクウォレットをブラウザでローカルにホストされているダッシュボードに接続するための1回限りのセットアッププロセスを実行できます。これが完了したら、キーをコピーして構成ファイルに貼り付ける代わりに、dashboardキーワードを使用するだけで十分です。Hardhatなどの他の開発フレームワークとも互換性があります。
Truffleダッシュボードを使用するには、最新バージョンのTruffleをインストールし、端末にコマンドを入力truffle dashboard
します。これで、秘密鍵が必要になるアクションは、代わりにダッシュボードを介してルーティングできます。たとえば、コントラクトをデプロイするには、truffle-config.js
ファイルで適切なポートが指定されていることを確認してから、コントラクトを右クリックしてデプロイし、を選択しますdashboard: 24012
。デフォルトはです24012
。
truffle-config.jsファイルで正しいポートが選択されていることを確認してください
コントラクトをデプロイするときにダッシュボードオプションを選択します
すべてのトランザクションはTruffleダッシュボードを介してルーティングされるため、秘密鍵を共有する必要はありません。
適切なツール、適切な前進
Web3プロジェクトの構築は複雑である必要はありません。適切なツールを使用すれば、前進する道が明確になります。ワークフローを改善する方法はたくさんありますが、Truffle for VS Code Extensionを自由に使用できると、既に慣れ親しんでいる環境から効率的に作業するのに役立ちます。この空間はかなり速く動き、常に新しいツールが作成されます。したがって、この記事が、Web3ツールスタックをナビゲートしながら開発プロセスを合理化する簡単な方法のアイデアを提供してくれることを願っています。
1652156053
As a developer you always required to choose a framework or an environment which gives you best options to develop software and blockchain is no different . we have few options like Truffle , hardhat , Brownie , Embark etc . for now we are going to focus on Truffle and Hardhat only .
Truffle and Hardhat both are Javascript based environment , it means you need to have node installed on your computer because you are going to use npm a lot during development of Dapp or any kind of blockchain based application .
Documentation
The hardhat has very clear and organised documentation . you can find different guides to how to start hardhat CLI and use hardhat core functionality very effectively . everything has been laid out neat and clean for developers to jump start your blockchain development journey.
the best part of the hardhat documentation is that , they have provided tutorials for various tasks and functionality available in hardhat which provides best practices for developers and not to beet around the bush . so if you are a new programmer and want to dive into blockchain development , hardhat becomes your first option to start with .
Truffle also has clean and organised documentation . To kick off your development journey with Truffle , Ganache , Smart contract compilation , testing and so on . apart from that they have also provided examples of how to connect truffle with metamask .
truffle is an old player in the market and thus it has advantage of having more reference around the web on youtube and other blogs as well . so if you are stuck with some concepts or want to know opinions about other people , you will find more resources than hardhat which becomes down side for hardhat.
Community
it has active community of blockchain and core developers of the framework . you can contact them via their discord server . but just don’t ask any random question or error solution , you have not explored much or there is already existing answer for it . ask only question which has not been addressed by someone else before , cherry on the cake , try to solve solve problem for the developer and you will get more idea about community .
But apart from official community we do have options like Stackoverflow and Stackexchange community which becomes helpful when you have some common errors in development .
The community of truffle is very supportive and large . you can find the group of communities here and can ask questions on their official Discord server .
truffle has few advantages when it comes to community due to first mover advantage . truffle has more resources around the web than hardhat but as hardhat becoming more and more popular , it will have more communities and more resources so don’t freak out .
Libraries & Plugins
hardhat has wide range of libraries and plugins and we can say that plugins are backbone of hardhat as well . you can enhance the functionality of hardhat with desired plugins . you can also make your own plugin here .
truffle does also have something similar called box . Box is a kind of plugin or library , you can create your own box but the thing is that you have to have use entire Box . you can not just use a part of box . which becomes a kind of tedious and more complex thing than hardhat .
Testing
hardhat comes up with much more flexible testing environment than truffle . because you can interact with smart contracts in testing which is also possible with truffle but hardhat makes it more easy .
let’s have a look at very simple code for testing Greeter.sol
need to have one file for writing test which is done with ethers.js , mocha and waffle . mostly it is test/sample-test.js
everything has been wrote with javascript . fire up the command for testing and you will see test results very soon .
Truffle also has testing environment built upon libraries like mocha , chai , and web3.js .
but the down side is that you can not interact with contract directly , you also need to start Ganache CLI or Gahance UI which provides free accounts and local blockchain to test any contract but hardhat has configured everything is single package .
again , here is the result for the truffle .
Framework used by companies
OpenZeppelin provides security products to build, automate, and operate decentralized applications. OpenZeppelin is the premier crypto cybersecurity technology and services company, trusted by the most used DeFi and NFT projects for leading crypto organizations including Coinbase, Ethereum Foundation, etc…
Optimism is a Layer 2 scaling solution for Ethereum that can support all of Ethereum’s Dapps. Instead of running all computation and data on the Ethereum network, Optimism puts all transaction data on-chain and runs computation off-chain, increasing Ethereum’s transactions per second and decreasing transaction fees.
Aave is a decentralised non-custodial liquidity market protocol where users can participate as depositors or borrowers. Depositors provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an overcollateralised (perpetually) or undercollateralised (one-block liquidity) fashion.
BitGo is the leader in institutional digital asset custody, trading, and finance. BitGo enables clients to navigate the complex landscape of digital assets with a connected, compliant, and secure suite of solutions.
1inch’s protocol scrapes many DEXs to find the cheapest platform, accounting for fees and the price of the asset itself.This DEX aggregator automatically pinpoints the cheapest trade to execute, making it a valuable tool for any trader. Instead of relying on a single DeFi protocol to buy a crypto asset
JPMorgan Chase & Co. is an American multinational investment bank and financial services holding company headquartered in New York City. it is a major provider of various investment banking and financial services. As of 2021 it is the largest lender to the fossil fuel industry in the world.
Conclusion
i have laid out all 5 parameters to let you decided which suits best for you , i personally like to use Hardhat because it seems easy for me but you are free to make your own choice . Happy Coding
#hardhat #truffle #blockchain
1650966540
This truffle plugin allows you to automatically verify your smart contracts' source code on Etherscan, straight from the Truffle CLI.
I wrote a tutorial on my website that goes through the entire process of installing and using this plugin: Automatically verify Truffle smart contracts on Etherscan.
Note: This version of the plugin uses multi-file verification. If you want to use source code flattening instead for any reason, please use the legacy version (v0.4.x) of the plugin.
npm install -D truffle-plugin-verify
yarn add -D truffle-plugin-verify
2. Add the plugin to your truffle-config.js
file
module.exports = {
/* ... rest of truffle-config */
plugins: ['truffle-plugin-verify']
}
3. Generate an API Key on your Etherscan account (see the Etherscan website)
4. Add your Etherscan API key to your truffle config (make sure to use something like dotenv
so you don't commit the api key)
module.exports = {
/* ... rest of truffle-config */
api_keys: {
etherscan: 'MY_API_KEY'
}
}
Before running verification, make sure that you have successfully deployed your contracts to a public network with Truffle. The contract deployment must have completely finished without errors, including the final step of "saving migration to chain," so that the artifact files are updated with the required information. If this final step fails, try lowering your global gas limit in your truffle-config.js
file, as saving migrations to chain uses your global gas limit and gas price, which could be problematic if you do not have sufficient ETH in your wallet to cover this maximum hypothetical cost.
After deployment, run the following command with one or more contracts that you wish to verify:
truffle run verify SomeContractName AnotherContractName --network networkName [--debug]
The network parameter should correspond to a network defined in the Truffle config file, with the correct network id set. The Ethereum mainnet and all main public testnets are supported.
For example, if we defined rinkeby
as network in Truffle, and we wish to verify the SimpleStorage
contract:
truffle run verify SimpleStorage --network rinkeby
This can take some time, and will eventually either return Pass - Verified
or Fail - Unable to verify
for each contract. Since the information we get from the Etherscan API is quite limited, it is currently impossible to retrieve any more information on verification failure. There should be no reason though why the verification should fail if the usage is followed correctly.
If you do receive a Fail - Unable to verify
and you are sure that you followed the instructions correctly, please open an issue and I will look into it. Optionally, a --debug
flag can also be passed into the CLI to output additional debug messages. It is helpful if you run this once before opening an issue and provide the output in your bug report.
In 2022, Truffle launched an awesome new feature called the Truffle Dashboard that allows you to deploy your contracts using your Metamask wallet. truffle-plugin-verify works with the Truffle Dashboard out of the box, but for it to work correctly you need to make sure that you are running the truffle dashboard, connected to the same network as you used for deployment while you're running truffle run verify ...
This plugin supports EIP1967 proxies out of the box. If you try to verify a proxy contract (e.g. contracts deployed with OpenZeppelin's deployProxy
), it will correctly verify the implementation contract and call Etherscan's "proxy verification" so that the proxy contract gets marked as a proxy on Etherscan (enabling Read/Write as Proxy). Note that EIP1967 Beacon contracts are not yet supported, and other types of non-standard proxies are also not supported.
You can optionally provide an explicit address of the contract(s) that you wish to verify. This may be useful when you have deployed multiple instances of the same contract. The address is appended with @<address>
as follows:
truffle run verify SimpleStorage@0x61C9157A9EfCaf6022243fA65Ef4666ECc9FD3D7 --network rinkeby
In some cases the Etherscan website may not be directly accessible. In this case it is possible to configure proxy settings so that the Etherscan requests will be made through this proxy. To use this feature, please add the relevant proxy settings to your truffle-config under proxy.verify
.
module.exports = {
/* ... rest of truffle-config */
verify: {
proxy: {
host: '127.0.0.1',
port: '1080'
}
}
}
You can additionally provide an explicit constructor arguments for the contract using the --forceConstructorArgs
option. This is useful if the contract was created by another contract rather an EOA, because truffle-plugin-verify cannot automatically retrieve constructor arguments in these cases. Note that the value needs to be prefixed with string:
(e.g. --forceConstructorArgs string:0000
).
truffle run verify MetaCoin --forceConstructorArgs string:0000000000000000000000000cb966d6a7702a4eff64009502653e302b3ec365 --network goerli
You can pass an optional --debug
flag into the plugin to display debug messages during the verification process. This is generally not necessary, but can be used to provide additional information when the plugin appears to malfunction.
truffle run verify SimpleStorage --network rinkeby
These instructions were written for verification on Etherscan for Ethereum mainnet and testnets, but it also works for verification on other platforms for other chains. To verify your contracts on these chains make sure that your truffle-config.js
file contains a network config for your preferred network. Also make sure that you request an API key from the platform that you're using and add it to your truffle-config.js
file. If you want to verify your contracts on multiple chains, please provide separate API keys.
module.exports = {
/* ... rest of truffle-config */
api_keys: {
etherscan: 'MY_API_KEY',
optimistic_etherscan: 'MY_API_KEY',
arbiscan: 'MY_API_KEY',
bscscan: 'MY_API_KEY',
snowtrace: 'MY_API_KEY',
polygonscan: 'MY_API_KEY',
ftmscan: 'MY_API_KEY',
hecoinfo: 'MY_API_KEY',
moonscan: 'MY_API_KEY',
bttcscan: 'MY_API_KEY',
aurorascan: 'MY_API_KEY',
cronoscan: 'MY_API_KEY'
}
}
This plugin has a naming conflict with the truffle-security plugin, so when using both truffle-security and truffle-plugin-verify in the same project, truffle run etherscan
can be used instead of truffle run verify
for truffle-plugin-verify.
Download Details:
Author: rkalis
Source Code: https://github.com/rkalis/truffle-plugin-verify
License: MIT License
#blockchain #solidity #ethereum #smartcontract #truffle #javascript
1650621540
This package adds additional assertions that can be used to test Ethereum smart contracts inside Truffle tests.
truffle-assertions can be installed through npm:
npm install truffle-assertions
To use this package, import it at the top of the Truffle test file, and use the functions that are documented below.
const truffleAssert = require('truffle-assertions');
I wrote two tutorials on using this library for checking events and asserting reverts inside smart contract tests:
I also gave a two talks that explain a few different use cases of the library:
The eventEmitted
assertion checks that an event with type eventType
has been emitted by the transaction with result result
. A filter function can be passed along to further specify requirements for the event arguments:
truffleAssert.eventEmitted(result, 'TestEvent', (ev) => {
return ev.param1 === 10 && ev.param2 === ev.param3;
});
Alternatively, a filter object can be passed in place of a function. If an object is passed, this object will be matched against the event's arguments. This object does not need to include all the event's arguments; only the included ones will be used in the comparison.
truffleAssert.eventEmitted(result, 'TestEvent', { param1: 10, param2: 20 });
When the filter
parameter is omitted or set to null, the assertion checks just for event type:
truffleAssert.eventEmitted(result, 'TestEvent');
Optionally, a custom message can be passed to the assertion, which will be displayed alongside the default one:
truffleAssert.eventEmitted(result, 'TestEvent', (ev) => {
return ev.param1 === 10 && ev.param2 === ev.param3;
}, 'TestEvent should be emitted with correct parameters');
The default messages are
`Event of type ${eventType} was not emitted`
`Event filter for ${eventType} returned no results`
Depending on the reason for the assertion failure. The default message also includes a list of events that were emitted in the passed transaction.
The eventNotEmitted
assertion checks that an event with type eventType
has not been emitted by the transaction with result result
. A filter function can be passed along to further specify requirements for the event arguments:
truffleAssert.eventNotEmitted(result, 'TestEvent', (ev) => {
return ev.param1 === 10 && ev.param2 === ev.param3;
});
Alternatively, a filter object can be passed in place of a function. If an object is passed, this object will be matched against the event's arguments. This object does not need to include all the event's arguments; only the included ones will be used in the comparison.
truffleAssert.eventNotEmitted(result, 'TestEvent', { param1: 10, param2: 20 });
When the filter
parameter is omitted or set to null, the assertion checks just for event type:
truffleAssert.eventNotEmitted(result, 'TestEvent');
Optionally, a custom message can be passed to the assertion, which will be displayed alongside the default one:
truffleAssert.eventNotEmitted(result, 'TestEvent', null, 'TestEvent should not be emitted');
The default messages are
`Event of type ${eventType} was emitted`
`Event filter for ${eventType} returned results`
Depending on the reason for the assertion failure. The default message also includes a list of events that were emitted in the passed transaction.
Pretty prints the full list of events with their parameters, that were emitted in transaction with result result
truffleAssert.prettyPrintEmittedEvents(result);
Events emitted in tx 0x7da28cf2bd52016ee91f10ec711edd8aa2716aac3ed453b0def0af59991d5120:
----------------------------------------------------------------------------------------
TestEvent(testAddress = 0xe04893f0a1bdb132d66b4e7279492fcfe602f0eb, testInt: 10)
----------------------------------------------------------------------------------------
There can be times where we only have access to a transaction hash, and not to a transaction result object, such as with the deployment of a new contract instance using Contract.new();
. In these cases we still want to be able to assert that certain events are or aren't emitted.
truffle-assertions
offers the possibility to create a transaction result object from a contract instance and a transaction hash, which can then be used in the other functions that the library offers.
Note: This function assumes that web3 is injected into the tests, which truffle does automatically. If you're not using truffle, you should import web3 manually at the top of your test file.
let contractInstance = await Contract.new();
let result = await truffleAssert.createTransactionResult(contractInstance, contractInstance.transactionHash);
truffleAssert.eventEmitted(result, 'TestEvent');
Asserts that the passed async contract function does not fail.
await truffleAssert.passes(
contractInstance.methodThatShouldPass()
);
Optionally, a custom message can be passed to the assertion, which will be displayed alongside the default one:
await truffleAssert.passes(
contractInstance.methodThatShouldPass(),
'This method should not run out of gas'
);
The default message is
`Failed with ${error}`
Asserts that the passed async contract function fails with a certain ErrorType and reason.
The different error types are defined as follows:
ErrorType = {
REVERT: "revert",
INVALID_OPCODE: "invalid opcode",
OUT_OF_GAS: "out of gas",
INVALID_JUMP: "invalid JUMP"
}
await truffleAssert.fails(
contractInstance.methodThatShouldFail(),
truffleAssert.ErrorType.OUT_OF_GAS
);
A reason can be passed to the assertion, which functions as an extra filter on the revert reason (note that this is only relevant in the case of revert, not for the other ErrorTypes). This functionality requires at least Truffle v0.5.
await truffleAssert.fails(
contractInstance.methodThatShouldFail(),
truffleAssert.ErrorType.REVERT,
"only owner"
);
If the errorType parameter is omitted or set to null, the function just checks for failure, regardless of cause.
await truffleAssert.fails(contractInstance.methodThatShouldFail());
Optionally, a custom message can be passed to the assertion, which will be displayed alongside the default one:
await truffleAssert.fails(
contractInstance.methodThatShouldFail(),
truffleAssert.ErrorType.OUT_OF_GAS,
null,
'This method should run out of gas'
);
The default messages are
'Did not fail'
`Expected to fail with ${errorType}, but failed with: ${error}`
This is an alias for truffleAssert.fails(asyncFn, truffleAssert.ErrorType.REVERT[, reason][, message])
.
await truffleAssert.reverts(
contractInstance.methodThatShouldRevert(),
"only owner"
);
Download Details:
Author: rkalis
Source Code: https://github.com/rkalis/truffle-assertions
License: MIT License