Skip to content

Instantly share code, notes, and snippets.

@smlu
Last active March 11, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smlu/5faabee3ff6d3c01013e0d02db35790b to your computer and use it in GitHub Desktop.
Save smlu/5faabee3ff6d3c01013e0d02db35790b to your computer and use it in GitHub Desktop.
Converts JSON format of EOSIO contract abi to binary.
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <eosio/abi.hpp>
#include <eosio/from_json.hpp>
#include <eosio/to_bin.hpp>
namespace fs = std::filesystem;
using namespace std::string_view_literals;
inline std::string check_abi_version(const std::string& s) {
if (s.substr(0, 13) != "eosio::abi/1.") {
return "unsupported abi version";
}
return "";
}
std::string to_hex(const std::vector<char>& data)
{
using namespace std::string_view_literals;
static constexpr auto table = "0123456789ABCDEF"sv;
std::string hexstr;
hexstr.reserve( data.size() * 2 );
for ( int b : data ) {
hexstr.push_back( table.at( (b & 0xFF) >> 4) );
hexstr.push_back( table.at( (b & 0xFF) & 0x0f));
}
return hexstr;
}
int main(int argc, char** argv)
{
if (argc < 2) {
std::cerr << "Converts JSON format of EOSIO contract abi to binary\n"
<< " Usage: eosabi2bin [Options] <path_to_file>.abi\n\n"
<< " Options:\n"
<< " -hex Prints hex string output to console insted of writing to file\n\n";
return 1;
}
bool hex_out = argc > 2 && argv[1] == "-hex"sv;
fs::path abi_path(argv[hex_out ? 2 : 1]);
if (!fs::exists(abi_path) || !fs::is_regular_file(abi_path)) {
std::cerr << "Invalid ABI file path: " << abi_path << std::endl;
return 1;
}
std::ifstream abi_file(abi_path);
std::string abi_json_str(
(std::istreambuf_iterator<char>(abi_file)),
std::istreambuf_iterator<char>()
);
eosio::json_token_stream stream(abi_json_str.data());
eosio::abi_def def{};
eosio::from_json(def, stream);
if (auto error = check_abi_version(def.version); !error.empty()) {
std::cerr << error << std::endl;
return 1;
}
std::vector<char> abi_bin;
eosio::vector_stream vecstream(abi_bin);
eosio::to_bin(def, vecstream);
if (hex_out) {
std::cout << "binary abi:\n" << to_hex(abi_bin) << std::endl;
}
else {
const auto bin_abi_path = abi_path.replace_extension(".abi.bin");
std::ofstream bin_abi_file(bin_abi_path, std::ios::binary | std::ios::out);
bin_abi_file.write(abi_bin.data(), abi_bin.size());
}
return 0;
}
@smlu
Copy link
Author

smlu commented Mar 11, 2021

Requires abieos to compile.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment