Best of Crypto

Best of Crypto


Root Chain Contracts for The OmiseGO Plasma Framework

OmiseGO Plasma Framework Contracts

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:

  • transaction types, influenced by Plasma Group's Generalized Plasma Architecture
  • exit games, which can support any MVP-compatible exit game
  • token vaults, such as ETH and ERC-20

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.

Child chain and Watchers

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.

Learn more

You can learn more about OmiseGO and get started developing with our plasma framework at

Getting started

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:

  1. DEPLOYER The account that actually deploys the contracts
  2. AUTHORITY 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.
  3. 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

Building and running the python tests

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

Run Load Tests

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

How to release a new plasma contracts version

  • Update the
  • Bumps the version in package.json (the patch part)
  • Creates a commit with specified message
  • Tags that commit with the new version
npm version patch -m "Fixed a bug in X"

Download details:

Author: omgnetwork
Source code:
License: Apache-2.0 license

#omg #blockchain #web3 #ethereum #truffle #ganache #solidity #javascript

Root Chain Contracts for The OmiseGO Plasma Framework

Building Initial Coin Offering(ICO) Smart Contract In Ethereum

ICO Smart Contract

Initial Coin Offering(ICO) smart contract in Ethereum.


  • Building your own Initial Coin Offering
  • Adding features like crowdsale & whitelist to the ICO contract

Built With

  • Truffle
  • Solidity-v0.4.23


_Below are instructions to get started

  1. Clone the repo
  git clone

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!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Download details:

Author: ac12644
Source code:
License: MIT license

#solidity #smartcontract #blockchain #web3 #ethereum #dapp #truffle #ico

Building Initial Coin Offering(ICO) Smart Contract In Ethereum

Solidity Code Examples on Truffle and Ganache TestNet


  • Make sure Node.js & npm package manager is installed and accessible from the command line along with truffle.
    • Node.js
    • Truffle


The running examples and vulnerable contracts are in contract-samples folder. See Other folders contains token or full project examples that can be run for better understanding.

Running Examples

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
        ✓ Should return 10 addresses (43ms)

    1 passing (184ms)

Other Commands

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

Running Script

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'.


Useful Links

Download details:

Author:  lahiri-phdworks
Source code:

#solidity #smartcontract #blockchain #web3 #ethereum #dapp #truffle #ganache 

Solidity Code Examples on Truffle and Ganache TestNet

KryptoAuth: Web DApp for Secure Authentication Built with Java Solidiy

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.


  • Project's javadoc can be found in docs/javaDoc directory and at the following link: Javadoc Link.
  • Documentation can be found in docs/deliverables directory and at the following link: Documentation

Technical informations

Installation guide can be found in docs/deliverables directory and at the following link: User manual

Built With

  • Spring Boot - Framework used to perform code development.
  • Solidity - Object-oriented, high-level language for implementing smart contracts.
  • Web3j - Highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with clients on the Ethereum network.
  • Web3js - A collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or WebSocket.
  • Ganache - Blockchain based on Ethereum.
  • Metamask - A crypto wallet & gateway to blockchain apps.
  • Truffle - Development environment for Smart Contracts.
  • OpenZeppelin - The standard for secure blockchain applications.

Download details:

Author: Alberto-00
Source code:

#spring #springboot #java #solidity #web33 #web3js #ganache #metamask #truffle #openzeppelin #blockchain

KryptoAuth: Web DApp for Secure Authentication Built with Java Solidiy
Hans  Marvin

Hans Marvin


How to Create Your First Smart Contract in Solidity & Truffle

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:

#smartcontract #solidity #blockchain #truffle 

How to Create Your First Smart Contract in Solidity & Truffle

How to Build a Todo App with Solidity, Nextjs & Truffle

Build a Todo App with Solidity, Next.js & Truffle

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

How to Build a Todo App with Solidity, Nextjs & Truffle
Best of Crypto

Best of Crypto


An Example Smart Contract Utilizing Chainlink Using Truffle Box

Chainlink Truffle Box


  • NPM


  1. Install truffle
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.

Local Blockchain

: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

Helper Scripts

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
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
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'.

Truffle v5.0.25 (core: 5.0.25)
Node v10.16.3


  • Add tests for ChainlinkVRF
  • Add tests for Chainlink Price Feeds
  • Refactor tests to use this instead of defining contracts with let
  • Use the Chainlink-published mocks for MockV3Aggregator and VRFCoordinatorMock

Download details:
Author: smartcontractkit
Source code:
License: MIT license

#smartcontract #blockchain #oracle #chainlink #truffle 

An Example Smart Contract Utilizing Chainlink Using Truffle Box

How to Get Staking Reward in form Of Dapp Tokens Using Solidity, Web3

About the Application

There are 3 Smart Contract in this project, where 2 sol file is for ERC20 tokens, where one of the token is mock Dai or mDai, which is acting as the colateral for this project. The user will have to Deposit the mDai token to TokenFram SmartContract and for depositing our mDai we will get staking reward in form of Dapp Tokens.

Technology Used

  • Solidity
  • Truffle
  • React
  • Web3
  • Ganache
  • Metamask

How to run the Project

  • Start the local Blockchain in Ganache.
  • Connect the Local Blockchain with Metamask and import the second account to meta mask
  • Run Truffle Commands
    • Truffle Compile to compile the smartcontract
    • truffle migrate --reset to migrate your code to blockchain
  • Now start the Front End by npm start the React will run on localhost:3000
  • You can start deposit your mDai from the imported account.
  • Now you can run truffle exec scripts/issue-token.js to distribute the the reward to the investors

Download Details:
Author: 0xdevnet
Source Code:

#blockchain #solidity #smartcontract #web3 #metamask #truffle #metamask 

How to Get Staking Reward in form Of Dapp Tokens Using Solidity, Web3

Building Blockchain Token Staking dApp using React, Solidity, Truffle

Token Staking dApp

Blockchain Token Staking dApp built with React, Solidity, on Ethereum Ganache, Ropsten, Rinkeby testnet networks


  •  Added ERC20 TestToken
  •  Added Token Staking basic contract
  •  Started testing


  •  Updated Token Staking contract
  •  Added ability to stake, unstake, redistribute
  •  Implemented testing
  •  Added redistribution script


  •  Injected web3 and Metamask
  •  Ability to detect if Metamask installed, logged, locked
  •  Added skeletons for totalStaked, myStake,
  •  Added skeletons for Tester to Redistribute rewards and claim test tokens


  •  Added ability to load contracts
  •  Fetching data from TokenStaking contract
  •  Fetching balances
  •  Stake, Unstake is now working
  •  Redistribute rewards for (Admin only) is now working


  •  Implemented totalStaked
  •  Implemented ability to claim test token(Tst) (FOR TESTING PURPOSE ONLY)
  •  Added amount type validity check
  •  Add ability for user to stake max


  •  Added ability to listen to triggers .on transactionHash
  •  Data automatically fetched after confirmation received
  •  Added HDWallet provider and Infura setup
  •  Deployed on ropsten and rinkeby


  •  Different staking pool implemented customStake/customUnstake
  •  Implemented ability for admin to change custom pool APY value via script


  •  Implemented custom reward Pool redistribution
  •  Contract Source Code Verified (Exact Match)


  •  Components split in to smaller
  •  Added frontend logic for custom pools
  •  Added UI Elements
  •  Loaders fixed


  •  Added checks and restrictions for when Metamask is not connected
  •  UI Optimised for mobiles
  •  Production build uploaded to for preview and test run


Working Demo:

Running instructions

  • Copy project to your directory ( git clone )
  • Install project packages (npm install)
  • Start project (npm run start)

For Testing

  • To run tests, navigate to /test/TokenStaking and run: truffle test

For Admin Use

  • There are prewritten scripts for Admin use either manually or on daily, weekly basic, ideally with predefined cronjob from the server.
  • All scripts are located in /scripts folder
  • To change APY % run: truffle exec scripts/changeAPY.js 0.137 this script takes 1 argument (daily APY), in this provided example, admin sets 0.137 daily APY Preview
  • To redistribute rewards from the console, run: truffle exec scripts/redistribute.js or provide argument custom if you want to redistribute custom rewards Preview

Mocha testing output

   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)

Deployoment to Ethereum network and Verification

For private Ethereum test network make sure Ganache is running on HTTP://

Warning, 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:

#blockchain #solidity #smartcontract #dapp #truffle #react 

Building Blockchain Token Staking dApp using React, Solidity, Truffle
Best of Crypto

Best of Crypto


Conflux Truffle: A tool for Developing Smart Contracts on Conflux


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:

  • Built-in smart contract compilation, linking, deployment and binary management.
  • Automated contract testing with Mocha and Chai.
  • Configurable build pipeline with support for custom build processes.
  • Scriptable deployment & migrations framework.
  • Network management for deploying to many public & private networks.
  • Interactive console for direct contract communication.
  • Instant rebuilding of assets during development.
  • External script runner that executes scripts within a Conflux-Truffle environment.


$ npm install -g conflux-truffle

Quick Usage

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.



Change Log

Please see the change logs from here

Download Details:
Author: Conflux-Chain
Source Code:
License: MIT license

#Conflux #blockchain #smartcontract #truffle #javascript #solidity

Conflux Truffle: A tool for Developing Smart Contracts on Conflux

Creación De Proyectos Web3 Con La Extensión Truffle for VS Code

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.

Vista de Truffle for VS Code Extension en el editor de VS Code

La trufa para la extensión del código VS

La extensión Truffle para VS Code

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 + Ppara abrir la paleta de comandos. A continuación, escriba el comando Truffle New Solidity Projecty 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.

La estructura de archivos de un proyecto que comenzó con Truffle for VS Code Extension

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 .gitignorepara almacenar información que no desea enviar a un repositorio, un acuerdo de licencia de código abierto y un truffle-config.jsarchivo.

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).

Transacciones para elegir después de escribir el comando: Truffle Debug Transaction

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 que están disponibles a través de Truffle para VS Code Extension

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".

La opción para crear o implementar un contrato inteligente aparece después de hacer clic con el botón derecho en un archivo .sol

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.

La extensión Truffle for VS Code permite a los usuarios crear o conectarse a una red directamente desde el editor

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.

La lista de redes en las que un usuario puede implementar a través de la extensión

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.

Una imagen de la interfaz de Truffle Dashboard.  Permite a un usuario conectar su billetera MetaMask.

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 dashboarden 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.jsarchivo, luego haga clic con el botón derecho en su contrato para implementarlo y seleccione dashboard: 24012. El valor predeterminado es 24012.

El puerto 24012 está resaltado en el archivo de configuración de red, truffle-config.js

Asegúrese de que el puerto correcto esté seleccionado en el archivo truffle-config.js

La opción del tablero está resaltada en la lista de redes para implementar

Seleccione la opción del tablero al implementar el contrato

Aparece una transacción de MetaMask y se enruta a través del panel de control de Truffle.  ¡No más compartir claves privadas!

¡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.


#vscode #truffle #web3 

Creación De Proyectos Web3 Con La Extensión Truffle for VS Code
伊藤  直子

伊藤 直子


Truffle for VSCodeExtensionを使用したWeb3プロジェクトの作成



この記事では、Web3スマートコントラクトを作成するために必要な手順の概要を説明します。同時に、既に知っているツールであるVisual Studio Code(VS Code)とTruffle for VS Code拡張機能を使用してスマートコントラクトを作成、展開、テストすることで、これらの手順をうまくナビゲートする方法についても見ていきます。


ブロックチェーンとイーサリアムの基礎を学んだ後、あなたはおそらくあなた自身のWeb3プロジェクトを構築するためにあなたの知識を適用し始めるようにインスピレーションを得ました。途中で、さまざまなプロジェクトやチュートリアルからツールの長いリストを収集した可能性があります。そのリストに迷うのではなく、これらのツールの1つであるTruffle for VS Code拡張機能を使用して、新しいスマートコントラクトプロジェクトを開始するために必要な手順を調べ、スマートコントラクトの作成、デバッグ、展開にどのように役立つかを調べてみましょう。 、セキュリティ、およびその他の開発分野。







Truffle for VS Code拡張機能を使用する利点は、テンプレート化されたファイル構造とスターターファイルを使用して新しいフォルダーを作成するか、または単にプロジェクトを作成することにより、最初から正しい構造で新しいプロジェクトをすばやく構築できることです。トリュフボックス

新しいプロジェクトを開始して、適切なファイル構造がどのように見えるかを確認しましょう。まず、Truffle forVSCode拡張機能をインストールする必要があります。インストール手順の詳細とその機能の詳細については、この投稿を確認してください

拡張機能がインストールされたら、キーSHIFT + CTRL/を押しCMD + Pてコマンドパレットを開きます。次に、コマンドを入力してTruffle New Solidity Project、[基本プロジェクトの作成]オプションを選択します。プロジェクトパスを選択すると、適切なファイル構造で新しいプロジェクトが作成されます。

Truffle for VSCodeExtensionで開始されたプロジェクトのファイル構造







コマンドを入力した後に選択するトランザクション:Truffle Debug Transaction

次のコマンドを入力した後、デバッグするトランザクションを選択します。Truffle debut transaction


Truffle for VSCodeExtensionから利用できるデバッグツール




Truffle拡張機能内では、VS Codeを離れることなく、3つのタイプのネットワークすべてにデプロイできます。これを行うには、デプロイする.SOLファイルを右クリックし、[コントラクトのデプロイ]を選択します。



ローカルブロックチェーン:Ganache Serviceを使用すると、複数のウォレットアドレスを使用してローカルブロックチェーンを作成し、スマートコントラクトとのやり取りに使用できるEthをテストする簡単な方法です。拡張機能から、VSCodeのTruffle—Networksペインの下に新しいGanacheネットワークを作成できます。ネットワークを作成した後、必要に応じてサーバーを起動/停止および再起動できます。

Truffle for VS Code拡張機能を使用すると、ユーザーはエディターから直接ネットワークを作成または接続できます。










Diligence Fuzzingやそのオープンソースの代替手段であるScribbleなどのツールを使用してスマートコントラクトを実行すると、多くの一般的なセキュリティの脆弱性を見つけるのに役立ちます。ただし、プロジェクトが数百万人のユーザーの資金を処理することを目的としている場合は、スマートコントラクトを専門的に監査することをお勧めします。

それでも、開発者はプロジェクトを構築する際に一般的な脆弱性に注意する必要があります。Web3で頻繁に発生する攻撃ベクトルの1つは、ハッカーがボットを使用して、デプロイされたコントラクトをスキャンし、潜在的な脆弱性や、テストでコードに残されたウォレットの秘密鍵などの秘密情報を探す場合です。Truffle Dashboardのようなツールを使用することは、開発ミスによる資金と資産の損失を回避する1つの方法です。

Truffleダッシュボードインターフェイスの画像。 これにより、ユーザーはMetaMaskウォレットを接続できます。



Truffleダッシュボードを使用するには、最新バージョンのTruffleをインストールし、端末にコマンドを入力truffle dashboardします。これで、秘密鍵が必要になるアクションは、代わりにダッシュボードを介してルーティングできます。たとえば、コントラクトをデプロイするには、truffle-config.jsファイルで適切なポートが指定されていることを確認してから、コントラクトを右クリックしてデプロイし、を選択しますdashboard: 24012。デフォルトはです24012





MetaMaskトランザクションがポップアップし、Truffleダッシュボードを介してルーティングされます。 秘密鍵を共有する必要はもうありません!



Web3プロジェクトの構築は複雑である必要はありません。適切なツールを使用すれば、前進する道が明確になります。ワークフローを改善する方法はたくさんありますが、Truffle for VS Code Extensionを自由に使用できると、既に慣れ親しんでいる環境から効率的に作業するのに役立ちます。この空間はかなり速く動き、常に新しいツールが作成されます。したがって、この記事が、Web3ツールスタックをナビゲートしながら開発プロセスを合理化する簡単な方法のアイデアを提供してくれることを願っています。

 ソース:https ://

 #vscode #truffle #web3 

Truffle for VSCodeExtensionを使用したWeb3プロジェクトの作成
Blockchain Dev

Blockchain Dev


Hardhat Vs Truffle: Which One is Best?

Hardhat vs Truffle: Which One is Best?


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 .



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.



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 .



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.

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.


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 

Hardhat Vs Truffle: Which One is Best?

Truffle Plugin for Verify Your Smart Contracts on Etherscan


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.

Installation / preparation

  1. Install the plugin with npm or yarn
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.

Usage with the Truffle Dashboard

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 ...

Proxy Contracts

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.

Address override (Optional)

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

Run with a proxy (Optional)

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: '',
     port: '1080'

Constructor arguments override (Optional)

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

Usage with other chains

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'

All supported platforms & networks


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:
License: MIT License

#blockchain  #solidity  #ethereum  #smartcontract #truffle #javascript 

Truffle Plugin for Verify Your Smart Contracts on Etherscan

Truffle Assertions: Utilities for Testing ETH SmartContracts & Truffle


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:

Exported functions

truffleAssert.eventEmitted(result, eventType[, filter][, message])

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.

truffleAssert.eventNotEmitted(result, eventType[, filter][, message])

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

Events emitted in tx 0x7da28cf2bd52016ee91f10ec711edd8aa2716aac3ed453b0def0af59991d5120:
TestEvent(testAddress = 0xe04893f0a1bdb132d66b4e7279492fcfe602f0eb, testInt: 10)

truffleAssert.createTransactionResult(contract, transactionHash)

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;. 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;
let result = await truffleAssert.createTransactionResult(contractInstance, contractInstance.transactionHash);

truffleAssert.eventEmitted(result, 'TestEvent');

truffleAssert.passes(asyncFn[, message])

Asserts that the passed async contract function does not fail.

await truffleAssert.passes(

Optionally, a custom message can be passed to the assertion, which will be displayed alongside the default one:

await truffleAssert.passes(
    'This method should not run out of gas'

The default message is

`Failed with ${error}`

truffleAssert.fails(asyncFn[, errorType][, reason][, message])

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(

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(
    "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(
    'This method should run out of gas'

The default messages are

'Did not fail'
`Expected to fail with ${errorType}, but failed with: ${error}`

truffleAssert.reverts(asyncFn[, reason][, message])

This is an alias for truffleAssert.fails(asyncFn, truffleAssert.ErrorType.REVERT[, reason][, message]).

await truffleAssert.reverts(
    "only owner"

Related projects

  • truffle-events — 3rd party add-on to this project with 'deep events' support. You can test emitted events in other contracts, provided they are in the same transaction i.e. event A (contract A) and event B (contract B) are produced in the same transaction.

Download Details:
Author: rkalis
Source Code:
License: MIT License

#solidity  #ethereum  #smartcontract  #blockchain #truffle 

Truffle Assertions: Utilities for Testing ETH SmartContracts & Truffle