¿Cuál es la mejor manera de obtener JSON ABI después de implementar un contrato con Truffle a Ganache o Kovan?

Remix hace que sea muy fácil obtener JSON ABI.

¿Alguien tiene alguna recomendación sobre la mejor manera de obtener JSON ABI después de implementar con éxito un contrato usando Truffle sin tener que aprovechar Remix?

Respuestas (5)

cuando corres

$ truffle compile

truffle crea y guarda un archivo json por contrato en formato /yourProjectPath/build/contracts. En este archivo json encontrará el abi, el código de bytes, los temas (si tiene alguno eventen su contrato inteligente), las definiciones de funciones, etc. sólo para obtener una comprensión amplia).

personalmente uso python para mis proyectos. Así es como cargo automáticamente mi abi en mis scripts para realizar transacciones con mis contratos (usando web3py )

import json

PATH_TRUFFLE_WK = '/home/myUserName/Projects/myEthereumProjet/'
truffleFile = json.load(open(PATH_TRUFFLE_WK + '/build/contracts/myContractName.json'))

abi = truffleFile['abi']
bytecode = truffleFile['bytecode']

Puedes hacer lo mismo con tu lenguaje de programación favorito o simplemente copiar y pegar tu abi a mano.

@salanfe: Tu respuesta es correcta.

Sin embargo , hay algunos problemas con el compilador de trufas. Tuve problemas especialmente con funciones que no tenían parámetros de entrada...

Debido a este problema, sugiero usar solc en su lugar:

solcjs --abi path/to/your/contract.sol

Espero eso ayude.

Escribí una herramienta simple que hace exactamente lo que sugirió @salanfe. Es útil cuando tiene varias definiciones de contrato:

# Install it from npm
$ npm install -g truffle-export-abi

# Run it in your truffle project
$ truffle-export-abi
ABI extracted and output file wrote to: build/ABI.json

Repositorio de Github: https://github.com/maxme/truffle-export-abi

Considere usar solc -compiler directamente.

Más conveniente para usar la imagen de la ventana acoplable Solc :

docker run \
  -v {smart_contract_location_path}:/src:ro \
  -v {result_abi_location_path}:/build \
  ethereum/solc:0.8.3 \
  --allow-paths /src/node_modules \
  --overwrite \
  -o /build \
  --abi \
  /src/contracts/test.sol

Observaciones:

  • aquí se usó la versión codificada del compilador - 0.8.3; considere usar la última versión estable - ethereum/solc:stable
  • El compilador proporciona los siguientes formatos de salida:
  --ast-compact-json   AST of all source files in a compact JSON format.
  --asm                EVM assembly of the contracts.
  --asm-json           EVM assembly of the contracts in JSON format.
  --opcodes            Opcodes of the contracts.
  --bin                Binary of the contracts in hex.
  --bin-runtime        Binary of the runtime part of the contracts in hex.
  --abi                ABI specification of the contracts.
  --ir                 Intermediate Representation (IR) of all contracts
                       (EXPERIMENTAL).
  --ir-optimized       Optimized intermediate Representation (IR) of all
                       contracts (EXPERIMENTAL).
  --ewasm              Ewasm text representation of all contracts
                       (EXPERIMENTAL).
  --hashes             Function signature hashes of the contracts.
  --userdoc            Natspec user documentation of all contracts.
  --devdoc             Natspec developer documentation of all contracts.
  --metadata           Combined Metadata JSON whose Swarm hash is stored
                       on-chain.
  --storage-layout     Slots, offsets and types of the contract's state
                       variables.

Para evitar errores de importación como "Archivo fuera de los directorios permitidos" o "Archivo no encontrado", defina la ruta 'estricta' al archivo:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;

import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";

contract Hello is Ownable {
..
}

Para obtener ayuda, ejecute este comando:

docker run ethereum/solc:0.8.3 --help

..
  --base-path path     Use the given path as the root of the source tree
                       instead of the root of the filesystem.
  --allow-paths path(s)
                       Allow a given path for imports. A list of paths can be
                       supplied by separating them with a comma.
  --ignore-missing     Ignore missing files.
..
Esta debería ser la respuesta aceptada. ¿Por qué complicar las cosas con truffle (otras dependencias/bibliotecas) en lugar de usar el compilador solc directamente (dentro del contenedor docker oficial)?

Para JS

> truffle compile

Luego en el js

import ERC20Contract from '../build/contracts/ERC20';
const ERC20Token = new web3.eth.Contract(ERC20Contract.abi, contractAddress)