#!/usr/bin/env node

exports.id = 459;
exports.ids = [459];
exports.modules = {

/***/ 34514:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 34514;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 622219:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 622219;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 507745:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 507745;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 645982:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 645982;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 119354:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const web3Utils = __webpack_require__(118269);

module.exports = function(chai, _utils) {
  var assert = chai.assert;
  chai.Assertion.addProperty("address", function() {
    this.assert(
      this._obj.length === 42,
      "expected #{this} to be a 42 character address (0x...)",
      "expected #{this} to not be a 42 character address (0x...)"
    );

    // Convert address to a number. Make sure it's not zero.
    // Controversial: Technically there is that edge case where
    // all zeroes could be a valid address. But: This catches all
    // those cases where Ethereum returns 0x0000... if something fails.
    const number = web3Utils.toBN(this._obj);
    this.assert(
      number.equals(0) === false,
      "expected address #{this} to not be zero",
      "you shouldn't ever see this."
    );
  });
  assert.isAddress = function(val, exp, msg) {
    return new chai.Assertion(val, msg).to.be.address;
  };
};


/***/ }),

/***/ 160627:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const fse = __webpack_require__(655674);
const del = __webpack_require__(195752);
const WorkflowCompile = __webpack_require__(577135);
const BuildError = __webpack_require__(142863);
const {spawn} = __webpack_require__(63129);
const spawnargs = __webpack_require__(372255);
const _ = __webpack_require__(496486);
const expect = __webpack_require__(139883);

function CommandBuilder(command) {
  this.command = command;
}

CommandBuilder.prototype.build = function (options, callback) {
  console.log("Running `" + this.command + "`...");

  const args = spawnargs(this.command);
  const ps = args.shift();

  const cmd = spawn(ps, args, {
    detached: false,
    cwd: options.working_directory,
    env: _.merge(process.env, {
      WORKING_DIRECTORY: options.working_directory,
      BUILD_DESTINATION_DIRECTORY: options.destination_directory,
      BUILD_CONTRACTS_DIRECTORY: options.contracts_build_directory
    })
  });

  cmd.stdout.on("data", function (data) {
    console.log(data.toString());
  });

  cmd.stderr.on("data", function (data) {
    console.error(data);
  });

  cmd.on("close", function (code) {
    let error = null;
    if (code !== 0) {
      error = "Command exited with code " + code;
    }
    callback(error);
  });
};

const Build = {
  clean: async function (options) {
    const destination = options.build_directory;
    const contracts_build_directory = options.contracts_build_directory;

    // Clean first.
    await del([destination + "/*", "!" + contracts_build_directory]);
    fse.ensureDirSync(destination);
  },

  build: async function (options) {
    expect.options(options, [
      "build_directory",
      "working_directory",
      "contracts_build_directory",
      "networks"
    ]);

    const logger = options.logger || console;
    let builder = options.build;

    // Duplicate build directory for legacy purposes
    options.destination_directory = options.build_directory;

    if (builder === null || typeof builder === "undefined") {
      logger.log(
        "No build configuration found. Preparing to compile contracts."
      );
    } else if (typeof builder === "string") {
      builder = new CommandBuilder(builder);
    } else if (typeof builder === "function") {
      // If they've only provided a build function, use that.
      builder = { build: builder };
    } else if (builder.build == null) {
      throw new BuildError(
        "Build configuration can no longer be specified as an object. Please see our documentation for an updated list of supported build configurations."
      );
    }

    // Use our own clean method unless the builder supplies one.
    let clean = this.clean;
    if (builder && builder.hasOwnProperty("clean")) {
      clean = builder.clean;
    }

    await clean(options);

    // If necessary. This prevents errors due to the .sol.js files not existing.
    await WorkflowCompile.compileAndSave(options);
    if (builder) {
      builder.build(options, function (err) {
        if (typeof err === "string") {
          throw new BuildError(err);
        }
      });
    }
  }
};

module.exports = Build;


/***/ }),

/***/ 789664:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const copy = __webpack_require__(712415);
const path = __webpack_require__(385622);
const fs = __webpack_require__(935747);
const { promisify } = __webpack_require__(431669);

const templates = {
  test: {
    filename: path.join(__dirname, "templates", "example.js"),
    variable: "example"
  },
  contract: {
    filename: path.join(__dirname, "templates", "Example.sol"),
    name: "Example",
    license: "MIT",
    variable: "example"
  },
  migration: {
    filename: path.join(__dirname, "templates", "migration.js")
  }
};

const replaceContents = (filePath, find, replacement) => {
  const data = fs.readFileSync(filePath, { encoding: "utf8" });
  if (typeof find === "string") {
    find = new RegExp(find, "g");
  }
  const result = data.replace(find, replacement);
  fs.writeFileSync(filePath, result, { encoding: "utf8" });
};

const toUnderscoreFromCamel = (string) => {
  string = string.replace(/([A-Z])/g, function ($1) {
    return "_" + $1.toLowerCase();
  });

  if (string[0] === "_") {
    string = string.substring(1);
  }

  return string;
};

// getLicense return the license property value from Truffle config first and
// in case that the file doesn't exist it will fallback to package.json
const getLicense = (options) => {
  try {
    if ((license = __webpack_require__(120553).detect(options).license)) {
      return license;
    }
  } catch (err) {
    console.log(err);
  }

  try {
    return __webpack_require__(876775)(path.join(process.cwd(), "package.json")).license;
  } catch {}
}

const Create = {
  contract: async function (directory, name, options) {
    const from = templates.contract.filename;
    const to = path.join(directory, name + ".sol");

    if (!options.force && fs.existsSync(to)) {
      throw new Error("Can not create " + name + ".sol: file exists");
    }

    await promisify(copy.file.bind(copy))(from, to);

    replaceContents(to, templates.contract.name, name);
    if ((license = getLicense(options))) {
      replaceContents(to, templates.contract.license, license);
    }
  },

  test: async function (directory, name, options) {
    let underscored = toUnderscoreFromCamel(name);
    underscored = underscored.replace(/\./g, "_");
    const from = templates.test.filename;
    const to = path.join(directory, underscored + ".js");

    if (!options.force && fs.existsSync(to)) {
      throw new Error("Can not create " + underscored + ".js: file exists");
    }

    await promisify(copy.file.bind(copy))(from, to);
    replaceContents(to, templates.contract.name, name);
    replaceContents(to, templates.contract.variable, underscored);
  },

  migration: async function (directory, name, options) {
    let underscored = toUnderscoreFromCamel(name || "");
    underscored = underscored.replace(/\./g, "_");
    const from = templates.migration.filename;
    let filename = (new Date().getTime() / 1000) | 0; // Only do seconds.

    if (name != null && name !== "") {
      filename += "_" + underscored;
    }

    filename += ".js";
    const to = path.join(directory, filename);

    if (!options.force && fs.existsSync(to)) {
      throw new Error("Can not create " + filename + ": file exists");
    }
    return await promisify(copy.file.bind(copy))(from, to);
  }
};

module.exports = Create;


/***/ }),

/***/ 712415:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var cpr = __webpack_require__(917643);
var fs = __webpack_require__(935747);
var _ = __webpack_require__(496486);

var cpr_options = {
  deleteFirst: false,
  overwrite: false,
  confirm: true
};

// This module will copy a file or directory, and by default
// won't override individual files. If a file exists, it will
// simply move onto the next file.

var copy = function(from, to, extra_options, callback) {
  if (typeof extra_options === "function") {
    callback = extra_options;
    extra_options = {};
  }

  var options = _.merge(_.clone(cpr_options), extra_options);

  cpr(from, to, options, function(err, files) {
    var new_files = [];

    // Remove placeholders. Placeholders allow us to copy "empty" directories,
    // but lets NPM and git not ignore them.
    files = files || [];
    for (var file of files) {
      if (file.match(/.*PLACEHOLDER.*/) != null) {
        fs.unlinkSync(file);
        continue;
      }
      new_files.push(file);
    }

    callback(err, new_files);
  });
};

copy.file = function(from, to, callback) {
  var readStream = fs.createReadStream(from, "utf8");
  var writeStream = fs.createWriteStream(to, "utf8");

  readStream.on("error", function(err) {
    callback(err);
    callback = function() {};
  });

  writeStream.on("error", function(err) {
    callback(err);
    callback = function() {};
  });

  writeStream.on("finish", function() {
    callback();
  });

  readStream.pipe(writeStream);
};

module.exports = copy;


/***/ }),

/***/ 900458:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debugModule = __webpack_require__(354686);
const debug = debugModule("lib:debug:cli");

const ora = __webpack_require__(963395);
const fs = __webpack_require__(655674);
const path = __webpack_require__(385622);

const Debugger = __webpack_require__(538621);
const DebugUtils = __webpack_require__(93293);
const Codec = __webpack_require__(20102);

const { DebugInterpreter } = __webpack_require__(779311);
const { DebugCompiler } = __webpack_require__(455887);
const { DebugExternalHandler } = __webpack_require__(847546);

class CLIDebugger {
  constructor(config, { compilations, txHash } = {}) {
    this.config = config;
    this.compilations = compilations;
    this.txHash = txHash;
  }

  async run() {
    this.config.logger.log("Starting Truffle Debugger...");

    const session = await this.connect();

    // initialize prompt/breakpoints/ui logic
    const interpreter = await this.buildInterpreter(session);

    return interpreter;
  }

  async connect() {
    // get compilations (either by shimming compiled artifacts,
    // or by doing a recompile)
    const compilations = this.compilations || (await this.getCompilations());

    // invoke @truffle/debugger
    const session = await this.startDebugger(compilations);

    return session;
  }

  async fetchExternalSources(bugger) {
    const fetchSpinner = ora(
      "Getting and compiling external sources..."
    ).start();
    const {
      badAddresses,
      badFetchers,
      badCompilationAddresses
    } = await new DebugExternalHandler(
      bugger,
      this.config
    ).fetch(); //note: mutates bugger!
    if (badAddresses.length === 0 && badFetchers.length === 0) {
      fetchSpinner.succeed();
    } else {
      let warningStrings = [];
      if (badFetchers.length > 0) {
        warningStrings.push(
          `Errors occurred connecting to ${badFetchers.join(", ")}.`
        );
      }
      if (badAddresses.length > 0) {
        warningStrings.push(
          `Errors occurred while getting sources for addresses ${badAddresses.join(
            ", "
          )}.`
        );
      }
      if (badCompilationAddresses.length > 0) {
        warningStrings.push(
          `Errors occurred while compiling sources for addresses ${badCompilations.join(
            ", "
          )}.`
        );
      }
      fetchSpinner.warn(warningStrings.join("  "));
    }
  }

  async getCompilations() {
    let artifacts;
    artifacts = await this.gatherArtifacts();
    if ((artifacts && !this.config.compileAll) || this.config.compileNone) {
      let shimmedCompilations = Codec.Compilations.Utils.shimArtifacts(
        artifacts
      );
      //if they were compiled simultaneously, yay, we can use it!
      //(or if we *force* it to...)
      if (
        this.config.compileNone ||
        shimmedCompilations.every(DebugUtils.isUsableCompilation)
      ) {
        debug("shimmed compilations usable")
        return shimmedCompilations;
      }
      debug("shimmed compilations unusable")
    }
    //if not, or if build directory doesn't exist, we have to recompile
    return await this.compileSources();
  }

  async compileSources() {
    const compileSpinner = ora("Compiling your contracts...").start();

    const compilationResult = await new DebugCompiler(this.config).compile({
      withTests: this.config.compileTests
    });
    debug("compilationResult: %O", compilationResult);

    compileSpinner.succeed();

    return Codec.Compilations.Utils.shimCompilations(compilationResult);
  }

  async startDebugger(compilations) {
    const startMessage = DebugUtils.formatStartMessage(
      this.txHash !== undefined
    );
    let bugger;
    if (!this.config.fetchExternal) {
      //ordinary case, not doing fetch-external
      let startSpinner;
      startSpinner = ora(startMessage).start();
      bugger = await Debugger.forProject({
        provider: this.config.provider,
        compilations
      });
      if (this.txHash !== undefined) {
        try {
          debug("loading %s", this.txHash);
          await bugger.load(this.txHash);
          startSpinner.succeed();
        } catch (_) {
          debug("loading error");
          startSpinner.fail();
          //just start up unloaded
        }
      } else {
        startSpinner.succeed();
      }
    } else {
      //fetch-external case
      //note that in this case we start in light mode
      //and only wake up to full mode later!
      //also, in this case, we can be sure that txHash is defined
      bugger = await Debugger.forTx(
        this.txHash,
        {
          provider: this.config.provider,
          compilations,
          lightMode: this.config.fetchExternal
        }
      ); //note: may throw!
      await this.fetchExternalSources(bugger); //note: mutates bugger!
      let startSpinner = ora(startMessage).start();
      await bugger.startFullMode();
      //I'm removing the failure check here because I don't think that can
      //actually happen
      startSpinner.succeed();
    }
    return bugger;
  }

  async buildInterpreter(session) {
    return new DebugInterpreter(this.config, session, this.txHash);
  }

  async gatherArtifacts() {
    // Gather all available contract artifacts
    // if build directory doesn't exist, return undefined to signal that
    // a recompile is necessary
    if (!fs.existsSync(this.config.contracts_build_directory)) {
      return undefined;
    }
    const files = fs.readdirSync(this.config.contracts_build_directory);

    let contracts = files
      .filter(filePath => {
        return path.extname(filePath) === ".json";
      })
      .map(filePath => {
        return path.basename(filePath, ".json");
      })
      .map(contractName => {
        return this.config.resolver.require(contractName);
      });

    await Promise.all(
      contracts.map(abstraction => abstraction.detectNetwork())
    );

    return contracts;
  }
}

module.exports = {
  CLIDebugger
};


/***/ }),

/***/ 455887:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { Compile } = __webpack_require__(611105);
const WorkflowCompile = __webpack_require__(577135);
const Resolver = __webpack_require__(648511);
const glob = __webpack_require__(312884);
const path = __webpack_require__(385622);

class DebugCompiler {
  constructor(config) {
    this.config = config;
  }

  async compile({ sources, withTests }) {
    let compileConfig = this.config.with({ quiet: true });

    if (withTests) {
      const testResolver = new Resolver(this.config, {
        includeTruffleSources: true
      });
      const testFiles = glob
        .sync(`${this.config.test_directory}/**/*.sol`)
        .map(filePath => path.resolve(filePath));
      compileConfig = compileConfig.with({
        resolver: testResolver,
        //note we only need to pass *additional* files
        files: testFiles
      });
    }

    const { compilations } = sources
      ? await Compile.sources({ sources, options: compileConfig }) //used by external.js
      : await WorkflowCompile.compile(compileConfig.with({ all: true }));
    //note: we don't allow for the possibility here of compiling with specified sources
    //that are *not* solidity.  only external.js specifies sources, and making that work
    //with Vyper is a hard problem atm (how do we get the right version??)

    return compilations;
  }
}

module.exports = {
  DebugCompiler
};


/***/ }),

/***/ 847546:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debugModule = __webpack_require__(354686);
const debug = debugModule("lib:debug:external");

const Codec = __webpack_require__(20102);
const Fetchers = __webpack_require__(887031).default;
const {InvalidNetworkError} = __webpack_require__(887031);

const {DebugCompiler} = __webpack_require__(455887);

class DebugExternalHandler {
  constructor(bugger, config) {
    this.config = config;
    this.bugger = bugger;
  }

  async fetch() {
    let badAddresses = []; //for reporting errors back
    let badFetchers = []; //similar
    let badCompilationAddresses = []; //similar
    let addressesToSkip = new Set(); //addresses we know we can't get source for
    //note: this should always be a subset of unknownAddresses! [see below]
    //get the network id
    const userFetcherNames = this.config.sourceFetchers;
    //sort/filter fetchers by user's order, if given; otherwise use default order
    let sortedFetchers = [];
    if (userFetcherNames) {
      for (let name of userFetcherNames) {
        let Fetcher = Fetchers.find(Fetcher => Fetcher.fetcherName === name);
        if (Fetcher) {
          sortedFetchers.push(Fetcher);
        } else {
          throw new Error(`Unknown external source service ${name}.`);
        }
      }
    } else {
      sortedFetchers = Fetchers;
    }
    const networkId = this.config.network_id; //note: this is a number
    //make fetcher instances. we'll filter out ones that don't support this
    //network (and note ones that yielded errors)
    debug("Fetchers: %o", Fetchers);
    const fetchers = (
      await Promise.all(
        Fetchers.map(async Fetcher => {
          try {
            return await Fetcher.forNetworkId(
              networkId,
              this.config[Fetcher.fetcherName]
            );
          } catch (error) {
            if (!(error instanceof InvalidNetworkError)) {
              //if it's *not* just an invalid network, log the error.
              badFetchers.push(Fetcher.fetcherName);
            }
            //either way, filter this fetcher out
            return null;
          }
        })
      )
    ).filter(fetcher => fetcher !== null);
    //now: the main loop!
    let address;
    while (
      (address = getAnUnknownAddress(this.bugger, addressesToSkip)) !==
      undefined
    ) {
      let found = false;
      let failure = false; //set in case something goes wrong while getting source
      let failureReason; 
      //(not set if there is no source)
      for (const fetcher of fetchers) {
        //now comes all the hard parts!
        //get our sources
        let result;
        try {
          debug("getting sources for %s via %s", address, fetcher.fetcherName);
          result = await fetcher.fetchSourcesForAddress(address);
        } catch (error) {
          debug("error in getting sources! %o", error);
          failure = true;
          failureReason = "fetch";
          continue;
        }
        if (result === null) {
          debug("no sources found");
          //null means they don't have that address
          continue;
        }
        //if we do have it, extract sources & options
        debug("got sources!");
        const {sources, options} = result;
        if (options.language !== "Solidity") {
          //if it's not Solidity, bail out now
          debug("not Solidity, bailing out!");
          addressesToSkip.add(address);
          //break out of the fetcher loop, since *no* fetcher will work here
          break;
        }
        //compile the sources
        const externalConfig = this.config.with({
          compilers: {
            solc: options
          }
        }).merge({
          //turn on docker if the original config has docker
          compilers: {
            solc: {
              docker: ((this.config.compilers || {}).solc || {}).docker
            }
          }
        });
        let compilations;
        try {
          compilations = await new DebugCompiler(externalConfig).compile(
            { sources }
          );
        } catch (error) {
          debug("compile error: %O", error);
          failure = true;
          failureReason = "compile";
          continue; //try again with a different fetcher, I guess?
        }
        //shim the result
        const shimmedCompilations = Codec.Compilations.Utils.shimCompilations(
          compilations,
          `externalFor(${address})Via(${fetcher.fetcherName})`
        );
        //add it!
        await this.bugger.addExternalCompilations(shimmedCompilations);
        failure = false; //mark as *not* failed in case a previous fetcher failed
        //check: did this actually help?
        debug("checking result");
        if (!getUnknownAddresses(this.bugger).includes(address)) {
          debug(
            "address %s successfully recognized via %s",
            address,
            fetcher.fetcherName
          );
          found = true;
          //break out of the fetcher loop -- we got what we want
          break;
        }
        debug("address %s still unrecognized", address);
      }
      if (found === false) {
        //if we couldn't find it, add it to the list of addresses to skip
        addressesToSkip.add(address);
        //if we couldn't find it *and* there was a network or compile problem,
        //add it to the failures list
        if (failure === true) {
          switch (failureReason) {
            case "fetch":
              badAddresses.push(address);
              break;
            case "compile":
              badCompilationAddresses.push(address);
              break;
          }
        }
      }
    }
    return {
      badAddresses,
      badFetchers,
      badCompilationAddresses
    }; //main result is that we've mutated bugger,
    //not the return value!
  }
}

function getUnknownAddresses(bugger) {
  debug("getting unknown addresses");
  const instances = bugger.view(
    bugger.selectors.session.info.affectedInstances
  );
  debug("got instances");
  return Object.entries(instances)
    .filter(([_, {contractName}]) => contractName === undefined)
    .map(([address, _]) => address);
}

function getAnUnknownAddress(bugger, addressesToSkip) {
  return getUnknownAddresses(bugger).find(
    address => !addressesToSkip.has(address)
  );
}

module.exports = {
  DebugExternalHandler
};


/***/ }),

/***/ 779311:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debugModule = __webpack_require__(354686);
const debug = debugModule("lib:debug:interpreter");

const path = __webpack_require__(385622);
const util = __webpack_require__(431669);
const ora = __webpack_require__(963395);

const DebugUtils = __webpack_require__(93293);
const selectors = __webpack_require__(538621).selectors;
const { session, solidity, trace, evm, controller } = selectors;

const analytics = __webpack_require__(795614);
const repl = __webpack_require__(868027);

const { DebugPrinter } = __webpack_require__(429099);

const LINES_BEFORE_LONG = 5;
const LINES_AFTER_LONG = 3;

function watchExpressionAnalytics(raw) {
  if (raw.includes("!<")) {
    //don't send analytics for watch expressions involving selectors
    return;
  }
  let expression = raw.trim();
  //legal Solidity identifiers (= legal JS identifiers)
  let identifierRegex = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
  let isVariable = expression.match(identifierRegex) !== null;
  analytics.send({
    command: "debug: watch expression",
    args: { isVariable }
  });
}

class DebugInterpreter {
  constructor(config, session, txHash) {
    this.session = session;
    this.network = config.network;
    this.fetchExternal = config.fetchExternal;
    this.printer = new DebugPrinter(config, session);
    this.txHash = txHash;
    this.lastCommand = "n";
    this.enabledExpressions = new Set();
    this.repl = null;
  }

  async setOrClearBreakpoint(args, setOrClear) {
    //setOrClear: true for set, false for clear
    const currentLocation = this.session.view(controller.current.location);
    const breakpoints = this.session.view(controller.breakpoints);

    const currentNode = currentLocation.astRef;
    const currentSourceId = currentLocation.source
      ? currentLocation.source.id
      : null;
    const currentLine =
      currentSourceId !== null && currentSourceId !== undefined
        ? //sourceRange is never null, so we go by whether currentSourceId is null/undefined
          currentLocation.sourceRange.lines.start.line
        : null;

    let breakpoint = {};

    if (args.length === 0) {
      //no arguments, want currrent node
      debug("node case");
      if (currentNode === null) {
        this.printer.print("Cannot determine current location.");
        return;
      }
      breakpoint.node = currentNode;
      breakpoint.line = currentLine;
      breakpoint.sourceId = currentSourceId;
    }

    //the special case of "B all"
    else if (args[0] === "all") {
      if (setOrClear) {
        // only "B all" is legal, not "b all"
        this.printer.print("Cannot add breakpoint everywhere.");
        return;
      }
      await this.session.removeAllBreakpoints();
      this.printer.print("Removed all breakpoints.");
      return;
    }

    //if the argument starts with a "+" or "-", we have a relative
    //line number
    else if (args[0][0] === "+" || args[0][0] === "-") {
      debug("relative case");
      if (currentLine === null) {
        this.printer.print("Cannot determine current location.");
        return;
      }
      let delta = parseInt(args[0], 10); //want an integer
      debug("delta %d", delta);

      if (isNaN(delta)) {
        this.printer.print("Offset must be an integer.");
        return;
      }

      breakpoint.sourceId = currentSourceId;
      breakpoint.line = currentLine + delta;
    }

    //if it contains a colon, it's in the form source:line
    else if (args[0].includes(":")) {
      debug("source case");
      let sourceArgs = args[0].split(":");
      let sourceArg = sourceArgs[0];
      let lineArg = sourceArgs[1];
      debug("sourceArgs %O", sourceArgs);

      //first let's get the line number as usual
      let line = parseInt(lineArg, 10); //want an integer
      if (isNaN(line)) {
        this.printer.print("Line number must be an integer.");
        return;
      }

      //search sources for given string
      let sources = Object.values(this.session.view(solidity.views.sources));
      //we will indeed need the sources here, not just IDs
      let matchingSources = sources.filter(source =>
        source.sourcePath.includes(sourceArg)
      );

      if (matchingSources.length === 0) {
        this.printer.print(`No source file found matching ${sourceArg}.`);
        return;
      } else if (matchingSources.length > 1) {
        this.printer.print(
          `Multiple source files found matching ${sourceArg}.  Which did you mean?`
        );
        matchingSources.forEach(source =>
          this.printer.print(source.sourcePath)
        );
        this.printer.print("");
        return;
      }

      //otherwise, we found it!
      breakpoint.sourceId = matchingSources[0].id;
      breakpoint.line = line - 1; //adjust for zero-indexing!
    }

    //otherwise, it's a simple line number
    else {
      debug("absolute case");
      if (currentSourceId === null || currentSourceId === undefined) {
        this.printer.print("Cannot determine current file.");
        return;
      }
      let line = parseInt(args[0], 10); //want an integer
      debug("line %d", line);

      if (isNaN(line)) {
        this.printer.print("Line number must be an integer.");
        return;
      }

      breakpoint.sourceId = currentSourceId;
      breakpoint.line = line - 1; //adjust for zero-indexing!
    }

    //OK, we've constructed the breakpoint!  But if we're adding, we'll
    //want to adjust to make sure we don't set it on an empty line or
    //anything like that
    if (setOrClear) {
      let resolver = this.session.view(controller.breakpoints.resolver);
      breakpoint = resolver(breakpoint);
      //of course, this might result in finding that there's nowhere to
      //add it after that point
      if (breakpoint === null) {
        this.printer.print(
          "Nowhere to add breakpoint at or beyond that location."
        );
        return;
      }
    }

    //having constructed and adjusted breakpoint, here's now a
    //user-readable message describing its location
    let sources = this.session.view(solidity.views.sources);
    let sourceNames = Object.assign(
      //note: only include user sources
      {},
      ...Object.entries(sources).map(([id, source]) => ({
        [id]: path.basename(source.sourcePath)
      }))
    );
    let locationMessage = DebugUtils.formatBreakpointLocation(
      breakpoint,
      true, //only relevant for node-based breakpoints
      currentSourceId,
      sourceNames
    );

    //one last check -- does this breakpoint already exist?
    let alreadyExists =
      breakpoints.filter(
        existingBreakpoint =>
          existingBreakpoint.sourceId === breakpoint.sourceId &&
          existingBreakpoint.line === breakpoint.line &&
          existingBreakpoint.node === breakpoint.node //may be undefined
      ).length > 0;

    //NOTE: in the "set breakpoint" case, the above check is somewhat
    //redundant, as we're going to check again when we actually make the
    //call to add or remove the breakpoint!  But we need to check here so
    //that we can display the appropriate message.  Hopefully we can find
    //some way to avoid this redundant check in the future.

    //if it already exists and is being set, or doesn't and is being
    //cleared, report back that we can't do that
    if (setOrClear === alreadyExists) {
      if (setOrClear) {
        this.printer.print(`Breakpoint at ${locationMessage} already exists.`);
        return;
      } else {
        this.printer.print(`No breakpoint at ${locationMessage} to remove.`);
        return;
      }
    }

    //finally, if we've reached this point, do it!
    //also report back to the user on what happened
    if (setOrClear) {
      await this.session.addBreakpoint(breakpoint);
      this.printer.print(`Breakpoint added at ${locationMessage}.`);
    } else {
      await this.session.removeBreakpoint(breakpoint);
      this.printer.print(`Breakpoint removed at ${locationMessage}.`);
    }
    return;
  }

  start(terminate) {
    // if terminate is not passed, return a Promise instead
    if (terminate === undefined) {
      return util.promisify(this.start.bind(this))();
    }

    if (this.session.view(session.status.loaded)) {
      debug("loaded");
      this.printer.printSessionLoaded();
    } else if (this.session.view(session.status.isError)) {
      debug("error!");
      this.printer.printSessionError();
    } else {
      debug("didn't attempt a load");
      this.printer.printHelp();
    }

    const prompt = this.session.view(session.status.loaded)
      ? DebugUtils.formatPrompt(this.network, this.txHash)
      : DebugUtils.formatPrompt(this.network);

    this.repl = repl.start({
      prompt: prompt,
      eval: util.callbackify(this.interpreter.bind(this)),
      ignoreUndefined: true,
      done: terminate
    });
  }

  async interpreter(cmd) {
    cmd = cmd.trim();
    let cmdArgs, splitArgs;
    debug("cmd %s", cmd);

    if (cmd === ".exit") {
      cmd = "q";
    }

    //split arguments for commands that want that; split on runs of spaces
    splitArgs = cmd.trim().split(/ +/).slice(1);
    debug("splitArgs %O", splitArgs);

    //warning: this bit *alters* cmd!
    if (cmd.length > 0) {
      cmdArgs = cmd.slice(1).trim();
      cmd = cmd[0];
    }

    if (cmd === "") {
      cmd = this.lastCommand;
      cmdArgs = "";
      splitArgs = [];
    }

    //quit if that's what we were given
    if (cmd === "q") {
      process.exit();
    }

    let alreadyFinished = this.session.view(trace.finishedOrUnloaded);
    let loadFailed = false;

    // If not finished, perform commands that require state changes
    // (other than quitting or resetting)
    if (!alreadyFinished) {
      let stepSpinner = ora("Stepping...").start();
      switch (cmd) {
        case "o":
          await this.session.stepOver();
          break;
        case "i":
          await this.session.stepInto();
          break;
        case "u":
          await this.session.stepOut();
          break;
        case "n":
          await this.session.stepNext();
          break;
        case ";":
          //two cases -- parameterized and unparameterized
          if (cmdArgs !== "") {
            let count = parseInt(cmdArgs, 10);
            debug("cmdArgs=%s", cmdArgs);
            if (isNaN(count)) {
              this.printer.print("Number of steps must be an integer.");
              break;
            }
            await this.session.advance(count);
          } else {
            await this.session.advance();
          }
          break;
        case "c":
          await this.session.continueUntilBreakpoint();
          break;
      }
      stepSpinner.stop();
    } //otherwise, inform the user we can't do that
    else {
      switch (cmd) {
        case "o":
        case "i":
        case "u":
        case "n":
        case "c":
        case ";":
          //are we "finished" because we've reached the end, or because
          //nothing is loaded?
          if (this.session.view(session.status.loaded)) {
            this.printer.print("Transaction has halted; cannot advance.");
            this.printer.print("");
          } else {
            this.printer.print("No transaction loaded.");
            this.printer.print("");
          }
      }
    }
    if (cmd === "r") {
      //reset if given the reset command
      //(but not if nothing is loaded)
      if (this.session.view(session.status.loaded)) {
        await this.session.reset();
      } else {
        this.printer.print("No transaction loaded.");
        this.printer.print("");
      }
    }
    if (cmd === "t") {
      if (!this.fetchExternal) {
        if (!this.session.view(session.status.loaded)) {
          let txSpinner = ora(
            DebugUtils.formatTransactionStartMessage()
          ).start();
          try {
            await this.session.load(cmdArgs);
            txSpinner.succeed();
            this.repl.setPrompt(DebugUtils.formatPrompt(this.network, cmdArgs));
          } catch (_) {
            txSpinner.fail();
            loadFailed = true;
          }
        } else {
          loadFailed = true;
          this.printer.print(
            "Please unload the current transaction before loading a new one."
          );
        }
      } else {
        loadFailed = true;
        this.printer.print(
          "Cannot change transactions in fetch-external mode.  Please quit and restart the debugger instead."
        );
      }
    }
    if (cmd === "T") {
      if (!this.fetchExternal) {
        if (this.session.view(session.status.loaded)) {
          await this.session.unload();
          this.printer.print("Transaction unloaded.");
          this.repl.setPrompt(DebugUtils.formatPrompt(this.network));
        } else {
          this.printer.print("No transaction to unload.");
          this.printer.print("");
        }
      } else {
        this.printer.print(
          "Cannot change transactions in fetch-external mode.  Please quit and restart the debugger instead."
        );
      }
    }
    if (cmd === "g") {
      if (!this.session.view(controller.stepIntoInternalSources)) {
        this.session.setInternalStepping(true);
        this.printer.print(
          "All debugger commands can now step into generated sources."
        );
      } else {
        this.printer.print("Generated sources already activated.");
      }
    }
    if (cmd === "G") {
      if (this.session.view(controller.stepIntoInternalSources)) {
        this.session.setInternalStepping(false);
        this.printer.print(
          "Commands other than (;) and (c) will now skip over generated sources."
        );
      } else {
        this.printer.print("Generated sources already off.");
      }
    }

    // Check if execution has (just now) stopped.
    if (this.session.view(trace.finished) && !alreadyFinished) {
      this.printer.print("");
      //check if transaction failed
      if (!this.session.view(evm.transaction.status)) {
        await this.printer.printRevertMessage();
        this.printer.print("");
        this.printer.printStacktrace(true); //final stacktrace
        this.printer.print("");
        this.printer.printErrorLocation();
      } else {
        //case if transaction succeeded
        this.printer.print("Transaction completed successfully.");
        if (this.session.view(solidity.current.source).language !== "Vyper") {
          //HACK: not supported for vyper yet
          await this.printer.printReturnValue();
        }
      }
    }

    // Perform post printing
    // (we want to see if execution stopped before printing state).
    switch (cmd) {
      case "+":
        if (cmdArgs[0] === ":") {
          watchExpressionAnalytics(cmdArgs.substring(1));
        }
        this.enabledExpressions.add(cmdArgs);
        await this.printer.printWatchExpressionResult(cmdArgs);
        break;
      case "-":
        this.enabledExpressions.delete(cmdArgs);
        break;
      case "!":
        this.printer.printSelector(cmdArgs);
        break;
      case "?":
        this.printer.printWatchExpressions(this.enabledExpressions);
        this.printer.printBreakpoints();
        this.printer.printGeneratedSourcesState();
        break;
      case "v":
        if (this.session.view(solidity.current.source).language === "Vyper") {
          this.printer.print(
            "Decoding of variables is not currently supported for Vyper."
          );
          break;
        }
        await this.printer.printVariables();
        if (this.session.view(trace.finished)) {
          await this.printer.printReturnValue();
        }
        break;
      case ":":
        watchExpressionAnalytics(cmdArgs);
        this.printer.evalAndPrintExpression(cmdArgs);
        break;
      case "b":
        await this.setOrClearBreakpoint(splitArgs, true);
        break;
      case "B":
        await this.setOrClearBreakpoint(splitArgs, false);
        break;
      case "p":
        //first: process which locations we should print out
        let temporaryPrintouts = new Set();
        for (let argument of splitArgs) {
          let fullLocation;
          if (argument[0] === "+" || argument[0] === "-") {
            fullLocation = argument.slice(1);
          } else {
            fullLocation = argument;
          }
          let location = this.printer.locations.find(possibleLocation =>
            fullLocation.startsWith(possibleLocation)
          );
          if (argument[0] === "+") {
            this.printer.printouts.add(location);
          } else if (argument[0] === "-") {
            this.printer.printouts.delete(location);
          } else {
            temporaryPrintouts.add(location);
          }
        }
        for (let location of this.printer.printouts) {
          debug("location: %s", location);
          temporaryPrintouts.add(location);
        }
        if (this.session.view(session.status.loaded)) {
          if (this.session.view(trace.steps).length > 0) {
            this.printer.printInstruction(temporaryPrintouts);
            this.printer.printFile();
            this.printer.printState();
          } else {
            //if there are no trace steps, let's just print a warning message
            this.printer.print("No trace steps to inspect.");
          }
        }
        //finally, print watch expressions
        await this.printer.printWatchExpressionsResults(
          this.enabledExpressions
        );
        break;
      case "l":
        if (this.session.view(session.status.loaded)) {
          this.printer.printFile();
          this.printer.printState(LINES_BEFORE_LONG, LINES_AFTER_LONG);
        }
        break;
      case ";":
        if (!this.session.view(trace.finishedOrUnloaded)) {
          this.printer.printInstruction();
          this.printer.printFile();
          this.printer.printState();
        }
        await this.printer.printWatchExpressionsResults(
          this.enabledExpressions
        );
        break;
      case "s":
        if (this.session.view(session.status.loaded)) {
          //print final report if finished & failed, intermediate if not
          if (
            this.session.view(trace.finished) &&
            !this.session.view(evm.transaction.status)
          ) {
            this.printer.printStacktrace(true); //print final stack trace
            //Now: actually show the point where things went wrong
            this.printer.printErrorLocation(
              LINES_BEFORE_LONG,
              LINES_AFTER_LONG
            );
          } else {
            this.printer.printStacktrace(false); //intermediate call stack
          }
        }
        break;
      case "o":
      case "i":
      case "u":
      case "n":
      case "c":
        if (!this.session.view(trace.finishedOrUnloaded)) {
          if (!this.session.view(solidity.current.source).source) {
            this.printer.printInstruction();
          }
          this.printer.printFile();
          this.printer.printState();
        }
        await this.printer.printWatchExpressionsResults(
          this.enabledExpressions
        );
        break;
      case "r":
        if (this.session.view(session.status.loaded)) {
          this.printer.printAddressesAffected();
          this.printer.warnIfNoSteps();
          this.printer.printFile();
          this.printer.printState();
        }
        break;
      case "t":
        if (!loadFailed) {
          this.printer.printAddressesAffected();
          this.printer.warnIfNoSteps();
          this.printer.printFile();
          this.printer.printState();
        } else if (this.session.view(session.status.isError)) {
          let loadError = this.session.view(session.status.error);
          this.printer.print(loadError);
        }
        break;
      case "T":
      case "g":
      case "G":
        //nothing to print
        break;
      default:
        this.printer.printHelp(this.lastCommand);
    }

    if (
      cmd !== "b" &&
      cmd !== "B" &&
      cmd !== "v" &&
      cmd !== "h" &&
      cmd !== "p" &&
      cmd !== "l" &&
      cmd !== "?" &&
      cmd !== "!" &&
      cmd !== ":" &&
      cmd !== "+" &&
      cmd !== "r" &&
      cmd !== "-" &&
      cmd !== "t" &&
      cmd !== "T" &&
      cmd !== "g" &&
      cmd !== "G" &&
      cmd !== "s"
    ) {
      this.lastCommand = cmd;
    }
  }
}

module.exports = {
  DebugInterpreter
};


/***/ }),

/***/ 212834:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const colors = __webpack_require__(183196);
const util = __webpack_require__(431669);

const { CLIDebugger } = __webpack_require__(900458);
const execute = __webpack_require__(141441);

class CLIDebugHook {
  constructor(config, compilations, runner) {
    this.config = config;
    this.compilations = compilations;
    this.runner = runner; // mocha runner (**not** lib/test/testrunner)
  }

  async debug(operation) {
    // turn off timeouts for the current runnable
    // HACK we don't turn it back on because it doesn't work...
    // tests that take a long time _after_ debug break just won't timeout
    this.disableTimeout();

    const { txHash, result, method } = await this.invoke(operation);

    this.printStartTestHook(method);

    const interpreter = await new CLIDebugger(this.config, {
      compilations: this.compilations
    }).run(txHash);
    await interpreter.start();

    this.printStopTestHook();

    return result;
  }

  async start() {}

  disableTimeout() {
    this.runner.currentRunnable.timeout(0);
  }

  async invoke(operation) {
    const method = await this.detectMethod(operation);
    const { action } = method;

    switch (action) {
      case "deploy": {
        const result = await operation;

        return {
          txHash: result.transactionHash, // different name; who knew
          method,
          result
        };
      }
      case "send": {
        const result = await operation;

        return { txHash: result.tx, method, result };
      }
      case "call": {
        // replays as send
        const { contract, fn, abi, args, address } = method;

        // get the result of the call
        const result = await operation;

        // and replay it as a transaction so we can debug
        // bit of a HACK: properly making a call act like a tx requires forking
        const { tx: txHash } = await execute.send.call(
          contract,
          fn,
          abi,
          address
        )(...args);

        return { txHash, method, result };
      }
      default: {
        throw new Error(`Unsupported action for debugging: ${action}`);
      }
    }
  }

  detectMethod(promiEvent) {
    return new Promise(accept => {
      for (let action of ["send", "call", "deploy"]) {
        promiEvent.on(
          `execute:${action}:method`,
          ({ fn, abi, args, contract, address }) => {
            accept({
              fn,
              abi,
              args,
              address,
              contract,
              action
            });
          }
        );
      }
    });
  }

  printStartTestHook(method) {
    const formatOperation = ({
      action,
      contract: { contractName },
      abi,
      args
    }) => {
      switch (action) {
        case "deploy": {
          return colors.bold(
            `${contractName}.new(${args.map(util.inspect).join(", ")})`
          );
        }
        case "call":
        case "send": {
          return colors.bold(
            `${contractName}.${abi.name}(${args.map(util.inspect).join(", ")})`
          );
        }
      }
    };

    this.config.logger.log("");
    this.config.logger.log("  ...");
    this.config.logger.log(
      colors.cyan(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
      )
    );
    this.config.logger.log("  Test run interrupted.");
    this.config.logger.log(`  Debugging ${formatOperation(method)}`);
    this.config.logger.log(
      colors.cyan(
        ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
      )
    );
    this.config.logger.log("");
  }

  printStopTestHook() {
    this.config.logger.log("");
    this.config.logger.log("");
    this.config.logger.log(
      colors.cyan(
        "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
      )
    );
    this.config.logger.log("  Debugger stopped. Test resuming");
    this.config.logger.log(
      colors.cyan(
        "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
      )
    );
    this.config.logger.log("  ...");
    this.config.logger.log("");
  }
}

module.exports = {
  CLIDebugHook
};


/***/ }),

/***/ 429099:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debugModule = __webpack_require__(354686);
const debug = debugModule("lib:debug:printer");

const path = __webpack_require__(385622);

const DebugUtils = __webpack_require__(93293);
const Codec = __webpack_require__(20102);
const colors = __webpack_require__(183196);
const Interpreter = __webpack_require__(797941);

const selectors = __webpack_require__(538621).selectors;
const {
  session,
  solidity,
  trace,
  controller,
  data,
  evm,
  stacktrace
} = selectors;

class DebugPrinter {
  constructor(config, session) {
    this.config = config;
    this.session = session;
    this.select = expr => {
      let selector, result;

      try {
        selector = expr
          .split(".")
          .reduce((sel, next) => (next.length ? sel[next] : sel), selectors);
      } catch (_) {
        throw new Error("Unknown selector: %s", expr);
      }

      // throws its own exception
      // note: we avoid using this.session so that this
      // can be called from js-interpreter
      result = session.view(selector);

      return result;
    };

    const colorizeSourceObject = source => {
      const { source: raw, language } = source;
      const detabbed = DebugUtils.tabsToSpaces(raw);
      return DebugUtils.colorize(detabbed, language);
    };

    this.colorizedSources = Object.assign(
      {},
      ...Object.entries(this.session.view(solidity.views.sources)).map(
        ([id, source]) => ({
          [id]: colorizeSourceObject(source)
        })
      )
    );

    this.printouts = new Set(["sta"]);
    this.locations = ["sto", "cal", "mem", "sta"]; //should remain constant
  }

  print(...args) {
    this.config.logger.log(...args);
  }

  printSessionLoaded() {
    this.printAddressesAffected();
    this.warnIfNoSteps();
    this.printHelp();
    debug("Help printed");
    this.printFile();
    debug("File printed");
    this.printState();
    debug("State printed");
  }

  printSessionError() {
    this.print(this.session.view(session.status.error));
    this.printHelp();
  }

  printAddressesAffected() {
    const affectedInstances = this.session.view(session.info.affectedInstances);

    this.config.logger.log("");
    this.config.logger.log("Addresses affected:");
    this.config.logger.log(
      DebugUtils.formatAffectedInstances(affectedInstances)
    );
  }

  warnIfNoSteps() {
    if (this.session.view(trace.steps).length === 0) {
      this.config.logger.log(
        `${colors.bold(
          "Warning:"
        )} this transaction has no trace steps. This may happen if you are attempting to debug a transaction sent to an externally-owned account, or if the node you are connecting to failed to produce a trace for some reason. Please check your configuration and try again.`
      );
    }
  }

  printHelp(lastCommand) {
    this.config.logger.log("");
    this.config.logger.log(DebugUtils.formatHelp(lastCommand));
  }

  printFile(location = this.session.view(controller.current.location)) {
    let message = "";

    const sourcePath = location.source.sourcePath;

    if (sourcePath) {
      message += path.basename(sourcePath);
    } else {
      message += "?";
    }

    this.config.logger.log("");
    this.config.logger.log(message + ":");
  }

  printState(
    contextBefore = 2,
    contextAfter = 0,
    location = this.session.view(controller.current.location)
  ) {
    const {
      source: { id: sourceId },
      sourceRange: range
    } = location;

    if (sourceId === undefined) {
      this.config.logger.log();
      this.config.logger.log("1: // No source code found.");
      this.config.logger.log("");
      return;
    }

    //we don't just get extract the source text from the location because passed-in location may be
    //missing the source text
    const source = this.session.view(solidity.views.sources)[sourceId].source;
    const colorizedSource = this.colorizedSources[sourceId];

    debug("range: %o", range);

    // We were splitting on OS.EOL, but it turns out on Windows,
    // in some environments (perhaps?) line breaks are still denoted by just \n
    const splitLines = str => str.split(/\r?\n/g);

    const lines = splitLines(source);
    const colorizedLines = splitLines(colorizedSource);

    this.config.logger.log("");

    //HACK -- the line-pointer formatter doesn't work right with colorized
    //lines, so we pass in the uncolored version too
    this.config.logger.log(
      DebugUtils.formatRangeLines(
        colorizedLines,
        range.lines,
        lines,
        contextBefore,
        contextAfter
      )
    );

    this.config.logger.log("");
  }

  printInstruction(locations = this.printouts) {
    const instruction = this.session.view(solidity.current.instruction);
    const step = this.session.view(trace.step);
    const traceIndex = this.session.view(trace.index);
    const totalSteps = this.session.view(trace.steps).length;
    //note calldata will be a Uint8Array, not a hex string or array of such
    const calldata = this.session.view(data.current.state.calldata);
    //storage here is an object mapping hex words to hex words, all w/o 0x prefix
    const storage = this.session.view(evm.current.codex.storage);

    this.config.logger.log("");
    if (locations.has("sto")) {
      this.config.logger.log(DebugUtils.formatStorage(storage));
      this.config.logger.log("");
    }
    if (locations.has("cal")) {
      this.config.logger.log(DebugUtils.formatCalldata(calldata));
      this.config.logger.log("");
    }
    if (locations.has("mem")) {
      this.config.logger.log(DebugUtils.formatMemory(step.memory));
      this.config.logger.log("");
    }
    if (locations.has("sta")) {
      this.config.logger.log(DebugUtils.formatStack(step.stack));
      this.config.logger.log("");
    }
    this.config.logger.log(
      DebugUtils.formatInstruction(traceIndex + 1, totalSteps, instruction)
    );
    this.config.logger.log(DebugUtils.formatPC(step.pc));
    this.config.logger.log("");
    this.config.logger.log(step.gas + " gas remaining");
  }

  /**
   * @param {string} selector
   */
  printSelector(selector) {
    const result = this.select(selector);
    const debugSelector = debugModule(selector);
    debugSelector.enabled = true;
    debugSelector("%O", result);
  }

  printWatchExpressions(expressions) {
    if (expressions.size === 0) {
      this.config.logger.log("No watch expressions added.");
      return;
    }

    this.config.logger.log("");
    for (const expression of expressions) {
      this.config.logger.log("  " + expression);
    }
  }

  printBreakpoints() {
    const sources = this.session.view(solidity.views.sources);
    const sourceNames = Object.assign(
      //note: only include user sources
      {},
      ...Object.entries(sources).map(([id, source]) => ({
        [id]: path.basename(source.sourcePath)
      }))
    );
    const breakpoints = this.session.view(controller.breakpoints);
    if (breakpoints.length > 0) {
      for (let breakpoint of this.session.view(controller.breakpoints)) {
        let currentLocation = this.session.view(controller.current.location);
        let locationMessage = DebugUtils.formatBreakpointLocation(
          breakpoint,
          currentLocation.node !== undefined &&
            breakpoint.sourceId === currentLocation.source.sourceId &&
            breakpoint.node === currentLocation.astRef,
          currentLocation.source.id,
          sourceNames
        );
        this.config.logger.log("  Breakpoint at " + locationMessage);
      }
    } else {
      this.config.logger.log("No breakpoints added.");
    }
  }

  printGeneratedSourcesState() {
    if (this.session.view(controller.stepIntoInternalSources)) {
      this.config.logger.log("Generated sources are turned on.");
    } else {
      this.config.logger.log("Generated sources are turned off.");
    }
  }

  //this doesn't really *need* to be async as we could use codec directly, but, eh
  async printRevertMessage() {
    this.config.logger.log(
      DebugUtils.truffleColors.red("Transaction halted with a RUNTIME ERROR.")
    );
    this.config.logger.log("");
    const revertDecodings = await this.session.returnValue(); //in this context we know it's a revert
    debug("revertDecodings: %o", revertDecodings);
    switch (revertDecodings.length) {
      case 0:
        this.config.logger.log(
          "There was a revert message, but it could not be decoded."
        );
        break;
      case 1:
        const revertDecoding = revertDecodings[0];
        switch (revertDecoding.kind) {
          case "failure":
            this.config.logger.log(
              "There was no revert message.  This may be due to an in intentional halting expression, such as assert(), revert(), or require(), or could be due to an unintentional exception such as out-of-gas exceptions."
            );
            break;
          case "revert":
            switch (revertDecoding.abi.name) {
              case "Error":
                const revertStringInfo =
                  revertDecoding.arguments[0].value.value;
                let revertString;
                switch (revertStringInfo.kind) {
                  case "valid":
                    revertString = revertStringInfo.asString;
                    this.config.logger.log(`Revert message: ${revertString}`);
                    break;
                  case "malformed":
                    //turn into a JS string while smoothing over invalid UTF-8
                    //slice 2 to remove 0x prefix
                    revertString = Buffer.from(
                      revertStringInfo.asHex.slice(2),
                      "hex"
                    ).toString();
                    this.config.logger.log(`Revert message: ${revertString}`);
                    this.config.logger.log(
                      `${colors.bold(
                        "Warning:"
                      )} This message contained invalid UTF-8.`
                    );
                    break;
                }
                break;
              case "Panic":
                const panicCode = revertDecoding.arguments[0].value.value.asBN;
                const panicString = DebugUtils.panicString(panicCode, true); //get verbose panic string :)
                this.config.logger.log(
                  `Panic: Code 0x${panicCode.toString(
                    16
                  )}. This code indicates that ${panicString.toLowerCase()}`
                );
                break;
              default:
                this.config.logger.log(
                  "There was a revert message, but it was of an unrecognized type."
                );
            }
            break;
        }
        break;
      default:
        //Note: This shouldn't happen
        this.config.logger.log(
          "There was a revert message, but it could not be unambiguously decoded."
        );
        break;
    }
    this.config.logger.log(
      "Please inspect your transaction parameters and contract code to determine the meaning of this error."
    );
  }

  async printReturnValue() {
    //note: when printing revert messages, this will do so in a somewhat
    //different way than printRevertMessage does
    const allocationFound = Boolean(
      this.session.view(data.current.returnAllocation)
    );
    const decodings = await this.session.returnValue();
    debug("decodings: %o", decodings);
    if (!allocationFound && decodings.length === 0) {
      //case 1: no allocation found, decoding failed
      this.config.logger.log("");
      this.config.logger.log(
        "A value was returned but it could not be decoded."
      );
      this.config.logger.log("");
    } else if (!allocationFound && decodings[0].status === true) {
      //case 2: no allocation found, decoding succeeded, but not a revert
      //(i.e. it's a presumed selfdestruct; no value was returned)
      //do nothing
    } else if (allocationFound && decodings.length === 0) {
      //case 3: allocation found but decoding failed
      this.config.logger.log("");
      this.config.logger.log("The return value could not be decoded.");
      this.config.logger.log("");
    } else if (allocationFound && decodings[0].kind === "selfdestruct") {
      //case 4: allocation found, apparent self-destruct (note due to the use of [0] this
      //won't occur if no return value was expected, as return takes priority over selfdestruct)
      //Oops -- in an actual selfdestruct, we won't have the code! >_>
      //(Not until reconstruct mode exists...) Oh well, leaving this in
      this.config.logger.log("");
      this.config.logger.log(
        "No value was returned even though one was expected.  This may indicate a self-destruct."
      );
      this.config.logger.log("");
    } else if (decodings[0].kind === "failure") {
      //case 5: revert (no message)
      this.config.logger.log("");
      this.config.logger.log("There was no revert message.");
      this.config.logger.log("");
    } else if (decodings[0].kind === "unknownbytecode") {
      //case 6: unknown bytecode
      this.config.logger.log("");
      this.config.logger.log(
        "Bytecode was returned, but it could not be identified."
      );
      this.config.logger.log("");
    } else if (
      decodings[0].kind === "return" &&
      decodings[0].arguments.length === 0
    ) {
      //case 7: return values but with no content
      //do nothing
    } else if (decodings[0].kind === "bytecode") {
      //case 8: known bytecode
      this.config.logger.log("");
      const decoding = decodings[0];
      const contractKind = decoding.contractKind || "contract";
      if (decoding.address !== undefined) {
        this.config.logger.log(
          `Returned bytecode for a ${contractKind} ${decoding.class.typeName} at ${decoding.address}.`
        );
      } else {
        this.config.logger.log(
          `Returned bytecode for a ${contractKind} ${decoding.class.typeName}.`
        );
      }
      if (decoding.immutables && decoding.immutables.length > 0) {
        this.config.logger.log("Immutable values:");
        const prefixes = decoding.immutables.map(
          ({ name, class: { typeName } }) => `${typeName}.${name}: `
        );
        const maxLength = Math.max(...prefixes.map(prefix => prefix.length));
        const paddedPrefixes = prefixes.map(prefix =>
          prefix.padStart(maxLength)
        );
        for (let index = 0; index < decoding.immutables.length; index++) {
          const { value } = decoding.immutables[index];
          const prefix = paddedPrefixes[index];
          const formatted = DebugUtils.formatValue(value, maxLength);
          this.config.logger.log(prefix + formatted);
        }
      }
      this.config.logger.log("");
    } else if (decodings[0].kind === "revert") {
      //case 9: revert (with message)
      const decoding = decodings[0];
      this.config.logger.log("");
      switch (decoding.abi.name) {
        case "Error": {
          //case 9a: revert string
          const prefix = "Revert string: ";
          const value = decodings[0].arguments[0].value;
          const formatted = DebugUtils.formatValue(value, prefix.length);
          this.config.logger.log(prefix + formatted);
          break;
        }
        case "Panic": {
          //case 9b: panic code
          const prefix = "Panic code: ";
          const value = decodings[0].arguments[0].value;
          const formatted = DebugUtils.formatValue(value, prefix.length);
          const meaning = DebugUtils.panicString(value.value.asBN);
          this.config.logger.log(`${prefix} ${formatted} (${meaning})`);
          break;
        }
        default:
          //case 9c: ??? this shouldn't happen
          this.config.logger.log(
            "There was a revert message, but it was not of a recognized type."
          );
      }
      this.config.logger.log("");
    } else if (
      decodings[0].kind === "return" &&
      decodings[0].arguments.length > 0
    ) {
      //case 10: actual return values to print!
      this.config.logger.log("");
      const values = decodings[0].arguments;
      if (values.length === 1 && !values[0].name) {
        //case 10a: if there's only one value and it's unnamed
        const value = values[0].value;
        const prefix = "Returned value: ";
        const formatted = DebugUtils.formatValue(value, prefix.length);
        this.config.logger.log(prefix + formatted);
      } else {
        //case 10b: otherwise
        this.config.logger.log("Returned values:");
        const prefixes = values.map(({ name }, index) =>
          name ? `${name}: ` : `Component #${index + 1}: `
        );
        const maxLength = Math.max(...prefixes.map(prefix => prefix.length));
        const paddedPrefixes = prefixes.map(prefix =>
          prefix.padStart(maxLength)
        );
        for (let index = 0; index < values.length; index++) {
          const { value } = values[index];
          const prefix = paddedPrefixes[index];
          const formatted = DebugUtils.formatValue(value, maxLength);
          this.config.logger.log(prefix + formatted);
        }
      }
      this.config.logger.log("");
    } else if (decodings[0].kind === "returnmessage") {
      //case 11: raw binary data
      this.config.logger.log("");
      const fallbackOutputDefinition = this.session.view(
        data.current.fallbackOutputForContext
      );
      const name = (fallbackOutputDefinition || {}).name;
      const prettyData = `${colors.green("hex")}${DebugUtils.formatValue(
        decodings[0].data.slice(2), //remove '0x'
        0,
        true
      )}`;
      if (name) {
        //case 11a: it has a name
        this.config.logger.log("Returned values:");
        this.config.logger.log(`${name}: ${prettyData}`);
      } else {
        //case 11b: it doesn't
        this.config.logger.log(`Returned value: ${prettyData}`);
      }
      //it's already a string, so we'll pass the nativized parameter
      //and hack this together :)
      //also, since we only have one thing and it's a string, we'll skip
      //fancy indent processing
      this.config.logger.log("");
    }
  }

  printStacktrace(final) {
    this.config.logger.log(final ? "Stacktrace:" : "Call stack:");
    let report = final
      ? this.session.view(stacktrace.current.finalReport)
      : this.session.view(stacktrace.current.report);
    this.config.logger.log(DebugUtils.formatStacktrace(report));
  }

  printErrorLocation(linesBefore, linesAfter) {
    const stacktraceReport = this.session.view(stacktrace.current.finalReport);
    const lastUserFrame = stacktraceReport
      .slice()
      .reverse() //clone before reversing, reverse is in-place!
      .find(frame => !frame.location.internal);
    if (lastUserFrame) {
      this.config.logger.log("");
      this.config.logger.log(
        DebugUtils.truffleColors.red("Location of error:")
      );
      this.printFile(lastUserFrame.location);
      this.printState(linesBefore, linesAfter, lastUserFrame.location);
    }
  }

  async printWatchExpressionsResults(expressions) {
    debug("expressions %o", expressions);
    for (let expression of expressions) {
      this.config.logger.log(expression);
      // Add some padding. Note: This won't work with all loggers,
      // meaning it's not portable. But doing this now so we can get something
      // pretty until we can build more architecture around this.
      // Note: Selector results already have padding, so this isn't needed.
      if (expression[0] === ":") {
        process.stdout.write("  ");
      }
      await this.printWatchExpressionResult(expression);
    }
  }

  async printWatchExpressionResult(expression) {
    const type = expression[0];
    const exprArgs = expression.substring(1);

    if (type === "!") {
      this.printSelector(exprArgs);
    } else {
      await this.evalAndPrintExpression(exprArgs, 2, true);
    }
  }

  async printVariables() {
    const values = await this.session.variables();
    const sections = this.session.view(data.current.identifiers.sections);

    const sectionNames = {
      builtin: "Solidity built-ins",
      global: "Global constants",
      contract: "Contract variables",
      local: "Local variables"
    };

    this.config.logger.log();

    for (const [section, variables] of Object.entries(sections)) {
      if (variables.length > 0) {
        this.config.logger.log(sectionNames[section] + ":");
        // Get the length of the longest name.
        const longestNameLength = variables.reduce((longest, name) => {
          return name.length > longest ? name.length : longest;
        }, -Infinity);
        for (const variable of variables) {
          const paddedName = variable.padStart(longestNameLength) + ":";
          const value = values[variable];
          const formatted = DebugUtils.formatValue(
            value,
            longestNameLength + 5
          );
          this.config.logger.log("  " + paddedName, formatted);
        }
        this.config.logger.log();
      }
    }
  }

  /**
   * @param {string} raw - user input for watch expression
   *
   * performs pre-processing on `raw`, using !<...> delimeters to refer
   * to selector expressions.
   *
   * e.g., to see a particular part of the current trace step's stack:
   *
   *    debug(development:0x4228cdd1...)>
   *
   *        :!<trace.step.stack>[1]
   */
  async evalAndPrintExpression(raw, indent, suppress) {
    let variables = await this.session.variables();

    //if we're just dealing with a single variable, handle that case
    //separately (so that we can do things in a better way for that
    //case)
    let variable = raw.trim();
    if (variable in variables) {
      let formatted = DebugUtils.formatValue(variables[variable], indent);
      this.config.logger.log(formatted);
      this.config.logger.log();
      return;
    }
    debug("expression case");

    // converts all !<...> expressions to JS-valid selector requests
    const preprocessSelectors = expr => {
      const regex = /!<([^>]+)>/g;
      const select = "$"; // expect repl context to have this func
      const replacer = (_, selector) => `${select}("${selector}")`;

      return expr.replace(regex, replacer);
    };

    //HACK
    //if we're not in the single-variable case, we'll need to do some
    //things to Javascriptify our variables so that the JS syntax for
    //using them is closer to the Solidity syntax
    let context = Codec.Format.Utils.Inspect.nativizeVariables(variables);

    //HACK -- we can't use "this" as a variable name, so we're going to
    //find an available replacement name, and then modify the context
    //and expression appropriately
    let pseudoThis = "_this";
    while (pseudoThis in context) {
      pseudoThis = "_" + pseudoThis;
    }
    //in addition to pseudoThis, which replaces this, we also have
    //pseudoPseudoThis, which replaces pseudoThis in order to ensure
    //that any uses of pseudoThis yield an error instead of showing this
    let pseudoPseudoThis = "thereisnovariableofthatname";
    while (pseudoPseudoThis in context) {
      pseudoPseudoThis = "_" + pseudoPseudoThis;
    }
    context = DebugUtils.cleanThis(context, pseudoThis);
    let expr = raw.replace(
      //those characters in [] are the legal JS variable name characters
      //note that pseudoThis contains no special characters
      new RegExp("(?<![a-zA-Z0-9_$])" + pseudoThis + "(?![a-zA-Z0-9_$])"),
      pseudoPseudoThis
    );
    expr = expr.replace(
      //those characters in [] are the legal JS variable name characters
      /(?<![a-zA-Z0-9_$])this(?![a-zA-Z0-9_$])/,
      pseudoThis
    );
    //note that pseudoThis contains no dollar signs to screw things up

    expr = preprocessSelectors(expr);

    try {
      const result = this.safelyEvaluateWithSelectors(expr, context);
      const formatted = DebugUtils.formatValue(result, indent, true);
      this.config.logger.log(formatted);
      this.config.logger.log();
    } catch (e) {
      if (!suppress) {
        this.config.logger.log(e);
      } else {
        this.config.logger.log(DebugUtils.formatValue(undefined, indent, true));
      }
    }
  }

  //evaluates expression with the variables in context,
  //but also has `$` as a variable that is the select function
  safelyEvaluateWithSelectors(expression, context) {
    const select = this.select;
    let interpreter;
    interpreter = new Interpreter(expression, function (
      interpreter,
      globalObject
    ) {
      //first let's set up our select function (which will be called $)
      interpreter.setProperty(
        globalObject,
        "$",
        interpreter.createNativeFunction(selectorName => {
          debug("selecting %s", selectorName);
          return interpreter.nativeToPseudo(select(selectorName));
        })
      );
      //now let's set up the variables
      for (const [variable, value] of Object.entries(context)) {
        try {
          debug("variable: %s", variable);
          //note: circular objects wll raise an exception here and get excluded.
          interpreter.setProperty(
            globalObject,
            variable,
            interpreter.nativeToPseudo(value)
          );
        } catch (_) {
          debug("failure");
          //just omit things that don't work
        }
      }
    });
    interpreter.run();
    return interpreter.pseudoToNative(interpreter.value);
  }
}

module.exports = {
  DebugPrinter
};


/***/ }),

/***/ 142863:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const colors = __webpack_require__(183196);
const TruffleError = __webpack_require__(673321);

class BuildError extends TruffleError {
  constructor(message) {
    message =
      "Error building:\n\n" +
      message +
      "\n\n" +
      colors.red("Build failed. See above.");
    super(message);
  }
}

module.exports = BuildError;


/***/ }),

/***/ 478979:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const fs = __webpack_require__(935747);
const path = __webpack_require__(385622);
const OS = __webpack_require__(712087);
const BlockchainUtils = __webpack_require__(986317);
const Provider = __webpack_require__(200509);
const { createInterfaceAdapter } = __webpack_require__(936339);

const Networks = {
  deployed: async function(options) {
    let files;
    try {
      // Only read JSON files in directory
      files = fs
        .readdirSync(options.contracts_build_directory)
        .filter(fn => fn.endsWith(".json"));
    } catch (error) {
      // We can't read the directory. Act like we found nothing.
      files = [];
    }

    const binaries = files.map(file => {
      const filePath = path.join(options.contracts_build_directory, file);
      const fileContents = fs.readFileSync(filePath, "utf8");
      return JSON.parse(fileContents);
    });

    const idsToNames = {};
    const networks = {};

    for (let networkName in options.networks) {
      const network = options.networks[networkName];
      const networkId = network.network_id;

      if (networkId == null) return;

      idsToNames[networkId] = networkName;
      networks[networkName] = {};
    }

    for (let json of binaries) {
      for (let networkId in json.networks) {
        const networkName = idsToNames[networkId] || networkId;

        if (networks[networkName] == null) networks[networkName] = {};

        const address = json.networks[networkId].address;

        if (address == null) return;

        networks[networkName][json.contractName] = address;
      }
    }
    return networks;
  },

  display: async function(config) {
    const networks = await this.deployed(config);
    const { networkNames, starNetworks } = Object.keys(networks)
      .sort()
      .reduce(
        (acc, networkName) => {
          if (
            config.networks[networkName] &&
            config.networks[networkName].network_id === "*"
          ) {
            acc.starNetworks.push(networkName);
          } else {
            acc.networkNames.push(networkName);
          }
          return acc;
        },
        { networkNames: [], starNetworks: [] }
      );

    const unknownNetworks = networkNames.filter(networkName => {
      const configuredNetworks = Object.keys(config.networks);
      let found = false;
      for (let i = 0; i < configuredNetworks.length; i++) {
        const configuredNetworkName = configuredNetworks[i];
        if (networkName === configuredNetworkName) {
          found = true;
          break;
        }
      }

      return !found;
    });

    // Only display this warning if:
    //
    //   At least one network is configured with the wildcard ('*') network id
    //   There's a least one network deployed to
    //   And one of those networks deployed to is unknown (i.e., unconfigured).
    if (
      starNetworks.length > 0 &&
      networkNames.length > 0 &&
      unknownNetworks.length > 0
    ) {
      config.logger.log(
        OS.EOL +
          "The following networks are configured to match any network id ('*'):" +
          OS.EOL
      );

      starNetworks.forEach(networkName => {
        config.logger.log("    " + networkName);
      });

      config.logger.log(
        OS.EOL +
          "Closely inspect the deployed networks below, and use `truffle networks --clean` to remove any networks that don't match your configuration. You should not use the wildcard configuration ('*') for staging and production networks for which you intend to deploy your application."
      );
    }

    networkNames.forEach(networkName => {
      config.logger.log("");

      let output = Object.keys(networks[networkName])
        .sort()
        .map(contract_name => {
          const address = networks[networkName][contract_name];
          return contract_name + ": " + address;
        });

      if (output.length === 0) output = ["No contracts deployed."];

      let message = "Network: ";

      const is_id = config.networks[networkName] == null;

      if (is_id) {
        message += "UNKNOWN (id: " + networkName + ")";
      } else {
        message +=
          networkName +
          " (id: " +
          config.networks[networkName].network_id +
          ")";
      }

      config.logger.log(message);
      config.logger.log("  " + output.join("\n  "));
    });

    if (networkNames.length === 0) {
      config.logger.log(
        OS.EOL + "Contracts have not been deployed to any network."
      );
    }
    config.logger.log("");
  },

  clean: async function(config) {
    // Only read JSON files in directory
    let files = fs
      .readdirSync(config.contracts_build_directory)
      .filter(fn => fn.endsWith(".json"));
    const configuredNetworks = Object.keys(config.networks);
    const results = [];

    files.forEach(file => {
      const filePath = path.join(config.contracts_build_directory, file);
      const fileContents = fs.readFileSync(filePath, "utf8");
      const body = JSON.parse(fileContents);

      for (let installedNetworkId of Object.keys(body.networks)) {
        let found = false;
        for (let i = 0; i < configuredNetworks.length; i++) {
          const configuredNetwork = configuredNetworks[i];

          // If an installed network id matches a configured id, then we can ignore this one.
          let parsedNetworkId;
          try {
            // Account for an integer or string in the config
            parsedNetworkId = parseInt(installedNetworkId);
          } catch (_error) {
            // If it can't be parsed into an int like * then don't worry about it
          }
          if (
            installedNetworkId ===
              config.networks[configuredNetwork].network_id ||
            parsedNetworkId === config.networks[configuredNetwork].network_id
          ) {
            found = true;
            break;
          }
        }
        // If we didn't find a suitable configuration, delete this network.
        if (found === false) delete body.networks[installedNetworkId];
      }
      // Our work is done here. Save the file.
      fs.writeFileSync(filePath, JSON.stringify(body, null, 2), "utf8");
      results.push(body);
    });

    // TODO: Display what's removed?
    return results;
  },

  // Try to connect to every named network except for "test" and "development"
  asURIs: async function(options, networks) {
    const result = {
      uris: {},
      failed: []
    };

    for (const networkName of networks) {
      const provider = Provider.create(options.networks[networkName]);
      try {
        const uri = await BlockchainUtils.asURI(provider);
        result.uris[networkName] = uri;
      } catch (error) {
        result.failed.push(networkName);
      }
    }

    return result;
  },

  matchesNetwork: async function(network_id, network_options) {
    const provider = Provider.create(network_options);

    const first = network_id + "";
    const second = network_options.network_id + "";

    if (first === second) return true;

    const isFirstANumber = isNaN(parseInt(network_id)) === false;
    const isSecondANumber =
      isNaN(parseInt(network_options.network_id)) === false;

    // If both network ids are numbers, then they don't match, and we should quit.
    if (isFirstANumber && isSecondANumber) return false;

    const interfaceAdapter = createInterfaceAdapter({
      provider,
      networkType: network_options.type
    });

    const currentNetworkID = await interfaceAdapter.getNetworkId();
    if (first === currentNetworkID) return true;
    if (isFirstANumber === false)
      await BlockchainUtils.matches(first, provider);
    else {
      // Nothing else to compare.
      return false;
    }
  }
};

module.exports = Networks;


/***/ }),

/***/ 883513:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const expect = __webpack_require__(139883);
const TruffleError = __webpack_require__(673321);
const Networks = __webpack_require__(478979);
const EthPM = __webpack_require__(954733);
const EthPMRegistry = __webpack_require__(838182);
const Web3 = __webpack_require__(503283);
const { createInterfaceAdapter } = __webpack_require__(936339);
const path = __webpack_require__(385622);
const fs = __webpack_require__(935747);
const OS = __webpack_require__(712087);

const Package = {
  install: async function(options, callback) {
    const callbackPassed = typeof callback === "function";
    expect.options(options, ["working_directory", "ethpm"]);

    expect.options(options.ethpm, ["registry", "ipfs_host"]);

    expect.one(options.ethpm, ["provider", "install_provider_uri"]);

    // ipfs_port and ipfs_protocol are optinal.

    const provider =
      options.ethpm.provider ||
      new Web3.providers.HttpProvider(options.ethpm.install_provider_uri, {
        keepAlive: false
      });
    let host = options.ethpm.ipfs_host;

    if (host instanceof EthPM.hosts.IPFS === false) {
      host = new EthPM.hosts.IPFSWithLocalReader(
        options.ethpm.ipfs_host,
        options.ethpm.ipfs_port,
        options.ethpm.ipfs_protocol
      );
    }

    // When installing, we use infura to make a bunch of eth_call's.
    // We don't make any transactions. To satisfy APIs we'll put a from address,
    // but it doesn't really matter in this case.
    const fakeAddress = "0x1234567890123456789012345678901234567890";

    let registry = options.ethpm.registry;

    if (typeof registry === "string") {
      try {
        registry = await EthPMRegistry.use(
          options.ethpm.registry,
          fakeAddress,
          provider
        );
      } catch (error) {
        if (callbackPassed) {
          callback(error);
          return;
        }
        throw error;
      }
    }

    const pkg = new EthPM(options.working_directory, host, registry);

    if (options.packages) {
      const promises = options.packages.map(package_name => {
        const pieces = package_name.split("@");
        package_name = pieces[0];

        let version = "*";

        if (pieces.length > 1) version = pieces[1];

        return pkg.installDependency(package_name, version);
      });

      await Promise.all(promises);
      if (options.packages.length > 0) {
        console.log("");
        console.log("Successfully installed the following package(s)...");
        console.log("==================================================");
        options.packages.forEach(singlePackage => {
          console.log(`> ${singlePackage}`);
        });
        console.log("");
      }
      if (callbackPassed) {
        callback();
      }
      return;
    } else {
      let manifest;
      try {
        fs.accessSync(
          path.join(options.working_directory, "ethpm.json"),
          fs.constants.R_OK
        );
      } catch (_error) {
        // If the ethpm.json file doesn't exist, use the config as the manifest.
        manifest = options;
      }
      try {
        await pkg.install(manifest);
        if (callbackPassed) {
          callback();
        }
      } catch (error) {
        if (callbackPassed) {
          callback(error);
          return;
        }
        throw error;
      }
    }
  },

  publish: async function(options, callback) {
    const callbackPassed = typeof callback === "function";
    var self = this;

    expect.options(options, [
      "ethpm",
      "working_directory",
      "contracts_directory",
      "networks"
    ]);

    expect.options(options.ethpm, ["registry", "ipfs_host"]);

    // ipfs_port and ipfs_protocol are optinal.

    // When publishing, you need a ropsten network configured.
    var ropsten = options.networks.ropsten;

    if (!ropsten) {
      const message =
        "You need to have a `ropsten` network configured in " +
        "order to publish to the Ethereum Package Registry. See the " +
        "following link for an example configuration:" +
        OS.EOL +
        OS.EOL +
        "    http://trufflesuite.com/tutorials/using-infura-custom-provider" +
        OS.EOL;
      if (callbackPassed) {
        callback(new TruffleError(message));
        return;
      }
      throw new TruffleError(message);
    }

    options.network = "ropsten";

    var provider = options.provider;
    const interfaceAdapter = createInterfaceAdapter({
      provider: options.provider,
      networkType: "ethereum"
    });
    var host = options.ethpm.ipfs_host;

    if (!(host instanceof EthPM.hosts.IPFS)) {
      host = new EthPM.hosts.IPFS(
        options.ethpm.ipfs_host,
        options.ethpm.ipfs_port,
        options.ethpm.ipfs_protocol
      );
    }

    options.logger.log("Finding publishable artifacts...");

    try {
      const artifacts = await self.publishable_artifacts(options);

      const accs = await interfaceAdapter.getAccounts();
      var registry = await EthPMRegistry.use(
        options.ethpm.registry,
        accs[0],
        provider
      );
      var pkg = new EthPM(options.working_directory, host, registry);
      let manifest;
      try {
        fs.accessSync(
          path.join(options.working_directory, "ethpm.json"),
          fs.constants.R_OK
        );
      } catch (error) {
        // If the ethpm.json file doesn't exist, use the config as the manifest.
        manifest = options;
      }

      options.logger.log("Uploading sources and publishing to registry...");

      // TODO: Gather contract_types and deployments
      const lockfile = await pkg.publish(
        artifacts.contract_types,
        artifacts.deployments,
        manifest
      );
      // If we get here, publishing was a success.
      options.logger.log("+ " + lockfile.package_name + "@" + lockfile.version);
      if (callbackPassed) {
        callback();
      }
      return;
    } catch (error) {
      if (callbackPassed) {
        return callback(error);
      }
      throw error;
    }
  },

  digest: function(options, callback) {
    callback(new Error("Not yet implemented"));
  },

  // Return a list of publishable artifacts
  publishable_artifacts: async function(options, callback) {
    const callbackPassed = typeof callback === "function";
    // Filter out "test" and "development" networks.
    const ifReservedNetworks = new Set(["test", "development"]);
    var deployed_networks = Object.keys(options.networks).filter(
      name => !ifReservedNetworks.has(name)
    );

    // Now get the URIs of each network that's been deployed to.
    let result;
    try {
      result = await Networks.asURIs(options, deployed_networks);
    } catch (error) {
      if (callbackPassed) {
        return callback(err);
      }
      throw err;
    }

    var uris = result.uris;

    if (result.failed.length > 0) {
      const message =
        "Could not connect to the following networks: " +
        result.failed.join(", ") +
        ". These networks have deployed " +
        "artifacts that can't be published as a package without an active " +
        "and accessible connection. Please ensure clients for each " +
        "network are up and running prior to publishing, or use the -n " +
        "option to specify specific networks you'd like published.";
      if (callbackPassed) {
        return callback(new Error(message));
      }
      throw new Error(message);
    }

    var files = fs.readdirSync(options.contracts_build_directory);
    files = files.filter(file => file.endsWith(".json"));

    if (!files.length) {
      const message =
        "Could not locate any publishable artifacts in " +
        options.contracts_build_directory +
        ". " +
        "Run `truffle compile` before publishing.";
      if (callbackPassed) {
        return callback(new Error(message));
      }
      throw new Error(message);
    }

    const promises = files.map(file => {
      return new Promise((resolve, reject) => {
        fs.readFile(
          path.join(options.contracts_build_directory, file),
          "utf8",
          (error, data) => {
            if (error) {
              reject(error);
            }
            resolve(JSON.parse(data));
          }
        );
      });
    });

    const contracts = await Promise.all(promises);

    var contract_types = {};
    var deployments = {};

    // contract_types first.
    contracts.forEach(data => {
      contract_types[data.contractName] = {
        contract_name: data.contractName,
        bytecode: data.bytecode,
        abi: data.abi
      };
    });

    //var network_cache = {};
    const matchingPromises = [];

    contracts.forEach(data => {
      Object.keys(data.networks).forEach(network_id => {
        matchingPromises.push(
          new Promise(async (accept, reject) => {
            try {
              // Go through each deployed network and see if this network matches.
              for (const deployedNetwork of deployed_networks) {
                const matches = await Networks.matchesNetwork(
                  network_id,
                  options.networks[deployedNetwork]
                );
                if (matches) {
                  var uri = uris[deployed_network];

                  if (!deployments[uri]) {
                    deployments[uri] = {};
                  }

                  deployments[uri][data.contractName] = {
                    contract_type: data.contractName, // TODO: Handle conflict resolution
                    address: data.networks[network_id].address
                  };

                  accept();
                }
              }
            } catch (error) {
              reject(error);
            }
          })
        );
      });
    });

    try {
      await Promise.all(matchingPromises);
      const toReturn = {
        contract_types: contract_types,
        deployments: deployments
      };
      if (callbackPassed) {
        callback(null, toReturn);
        return;
      }
      return toReturn;
    } catch (error) {
      if (callbackPassed) {
        return callback(error);
      }
      throw error;
    }
  }
};

module.exports = Package;


/***/ }),

/***/ 795614:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Config = __webpack_require__(120553);

const analytics = {
  send: function(eventObject) {
    const userConfig = Config.getUserConfig();

    if (!userConfig.get("enableAnalytics")) {
      // don't bother with creating a new process if we already
      // know the user doesn't want to send analytics
      return;
    }

    let analyticsPath;
    const path = __webpack_require__(385622);
    if (true) {
      analyticsPath = path.join(__dirname, "analytics.bundled.js");
    } else {}

    const cp = __webpack_require__(63129);
    const child = cp.fork(analyticsPath, { silent: true });
    child.send(eventObject);
  }
};

module.exports = analytics;


/***/ }),

/***/ 569575:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const TestCase = __webpack_require__(82414);
const Suite = __webpack_require__(863868);
const Deployer = __webpack_require__(400669);
const { Compile } = __webpack_require__(611105);
const { Shims } = __webpack_require__(529833);
const RangeUtils = __webpack_require__(141016);
const debug = __webpack_require__(354686)("lib:testing:soliditytest");

const SolidityTest = {
  async define(abstraction, dependencyPaths, runner, mocha) {
    const self = this;

    const suite = new Suite(abstraction.contract_name, {});
    suite.timeout(runner.BEFORE_TIMEOUT);

    // Set up our runner's needs first.
    suite.beforeAll("prepare suite", async function () {
      // This compiles some native contracts (including the assertion library
      // contracts) which need to be compiled before initializing the runner
      await self.compileNewAbstractInterface.bind(this)(runner);
      await runner.initialize.bind(runner)();
      await self.deployTestDependencies.bind(this)(
        abstraction,
        dependencyPaths,
        runner
      );
    });

    suite.beforeEach("before test", async function () {
      await runner.startTest(this);
    });

    // Function that checks transaction logs to see if a test failed.
    async function checkResultForFailure(result) {
      const logs = result.receipt.rawLogs;
      for (const log of logs) {
        const decodings = await runner.decoder.decodeLog(log);
        for (const decoding of decodings) {
          //check: is this a TestEvent?
          //note: we don't check the argument names
          if (
            decoding.abi.name === "TestEvent" &&
            decoding.arguments.length === 2 &&
            decoding.arguments[0].value.type.typeClass === "bool" &&
            decoding.arguments[0].indexed &&
            decoding.arguments[1].value.type.typeClass === "string" &&
            !decoding.arguments[1].indexed
          ) {
            //if so: did the test fail?
            if (!decoding.arguments[0].value.value.asBoolean) {
              //if so: extract the message
              let messageDecoding = decoding.arguments[1].value;
              let message;
              switch (messageDecoding.value.kind) {
                case "valid":
                  message = messageDecoding.value.asString;
                  break;
                case "malformed":
                  //use buffer to convert hex to string
                  //(this causes malformed UTF-8 to become U+FFFD)
                  message = Buffer.from(
                    messageDecoding.value.asHex.slice(2),
                    "hex"
                  ).toString();
              }
              throw new Error(message);
            }
          }
        }
      }
    }

    // Add functions from test file.
    for (const item of abstraction.abi) {
      if (item.type !== "function") {
        continue;
      }

      const hookTypes = ["beforeAll", "beforeEach", "afterAll", "afterEach"];
      for (const hookType of hookTypes) {
        if (item.name.startsWith(hookType)) {
          suite[hookType](item.name, async () => {
            let deployed = await abstraction.deployed();
            await checkResultForFailure(await deployed[item.name]());
          });
        }
      }

      if (item.name.startsWith("test")) {
        const test = new TestCase(item.name, async () => {
          let deployed = await abstraction.deployed();
          await checkResultForFailure(await deployed[item.name]());
        });

        test.timeout(runner.TEST_TIMEOUT);
        suite.addTest(test);
      }
    }

    suite.afterEach("after test", async function () {
      await runner.endTest(this);
    });

    mocha.suite.addSuite(suite);
  },

  async compileNewAbstractInterface(runner) {
    debug("compiling");
    const config = runner.config;
    let solcVersion = config.compilers.solc.version;
    solcVersion = RangeUtils.resolveToRange(solcVersion);

    const truffleLibraries = [
      "truffle/Assert.sol",
      "truffle/AssertAddress.sol",
      "truffle/AssertAddressArray.sol",
      "truffle/AssertBalance.sol",
      "truffle/AssertBool.sol",
      "truffle/AssertBytes32.sol",
      "truffle/AssertBytes32Array.sol",
      "truffle/AssertGeneral.sol",
      "truffle/AssertInt.sol",
      "truffle/AssertIntArray.sol",
      "truffle/AssertString.sol",
      "truffle/AssertUint.sol",
      "truffle/AssertUintArray.sol",
      "truffle/DeployedAddresses.sol",
      `truffle/SafeSend.sol`
    ];

    const { compilations } = await Compile.sourcesWithDependencies({
      paths: truffleLibraries,
      options: runner.config.with({
        quiet: true
      })
    });
    const contracts = compilations.reduce((a, compilation) => {
      return a.concat(compilation.contracts);
    }, []);

    // Set network values.
    for (let contract of contracts) {
      contract.network_id = config.network_id;
      contract.default_network = config.default_network;
    }

    await config.artifactor.saveAll(
      contracts.map(Shims.NewToLegacy.forContract)
    );
    debug("compiled");
  },

  async deployTestDependencies(abstraction, dependencyPaths, runner) {
    debug("deploying %s", abstraction.contract_name);
    const deployer = new Deployer(
      runner.config.with({
        logger: { log() {} }
      })
    );

    debug("starting deployer");
    await deployer.start();

    const testLibraries = [
      "Assert",
      "AssertAddress",
      "AssertAddressArray",
      "AssertBalance",
      "AssertBool",
      "AssertBytes32",
      "AssertBytes32Array",
      "AssertGeneral",
      "AssertInt",
      "AssertIntArray",
      "AssertString",
      "AssertUint",
      "AssertUintArray",
      "DeployedAddresses"
    ];

    const testAbstractions = testLibraries.map(name =>
      runner.config.resolver.require(`truffle/${name}.sol`)
    );

    const SafeSend = runner.config.resolver.require("SafeSend");

    debug("deploying test libs");
    for (const testLib of testAbstractions) {
      await deployer.deploy(testLib);
      await deployer.link(testLib, abstraction);
    }

    debug("linking dependencies");
    for (const dependencyPath of dependencyPaths) {
      const dependency = runner.config.resolver.require(dependencyPath);

      if (dependency.isDeployed()) {
        await deployer.link(dependency, abstraction);
      }
    }

    debug("deploying contract");
    await deployer.deploy(abstraction);
    const deployed = await abstraction.deployed();
    let balance;
    if (deployed.initialBalance) {
      balance = await deployed.initialBalance.call();
    } else {
      balance = 0;
    }

    if (balance !== 0) {
      await deployer.deploy(SafeSend);
      const safeSend = await SafeSend.deployed();
      await safeSend.deliver(deployed.address, { value: balance });
    }

    debug("deployed %s", abstraction.contract_name);
  }
};

module.exports = SolidityTest;


/***/ }),

/***/ 952422:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const colors = __webpack_require__(183196);
const chai = __webpack_require__(614960);
const path = __webpack_require__(385622);
const {
  Web3Shim,
  createInterfaceAdapter
} = __webpack_require__(936339);
const Config = __webpack_require__(120553);
const WorkflowCompile = __webpack_require__(577135);
const Resolver = __webpack_require__(648511);
const TestRunner = __webpack_require__(68710);
const SolidityTest = __webpack_require__(569575);
const RangeUtils = __webpack_require__(141016);
const expect = __webpack_require__(139883);
const Migrate = __webpack_require__(523459);
const Profiler = __webpack_require__(879127);
const originalrequire = __webpack_require__(588277);
const Codec = __webpack_require__(20102);
const debug = __webpack_require__(354686)("lib:test");
const Debugger = __webpack_require__(538621);

let Mocha; // Late init with "mocha" or "mocha-parallel-tests"

chai.use(__webpack_require__(119354));

const Test = {
  run: async function (options) {
    expect.options(options, [
      "contracts_directory",
      "contracts_build_directory",
      "migrations_directory",
      "test_files",
      "network",
      "network_id",
      "provider"
    ]);

    const config = Config.default().merge(options);

    config.test_files = config.test_files.map(testFile => {
      return path.resolve(testFile);
    });

    const interfaceAdapter = createInterfaceAdapter({
      provider: config.provider,
      networkType: config.networks[config.network].type
    });

    // `accounts` will be populated before each contract() invocation
    // and passed to it so tests don't have to call it themselves.
    const web3 = new Web3Shim({
      provider: config.provider,
      networkType: config.networks[config.network].type
        ? config.networks[config.network].type
        : "web3js"
    });

    // Override console.warn() because web3 outputs gross errors to it.
    // e.g., https://github.com/ethereum/web3.js/blob/master/lib/web3/allevents.js#L61
    // Output looks like this during tests: https://gist.github.com/tcoulter/1988349d1ec65ce6b958
    const warn = config.logger.warn;
    config.logger.warn = function (message) {
      if (message === "cannot find event for log") {
        return;
      } else {
        if (warn) warn.apply(console, arguments);
      }
    };

    const mocha = this.createMocha(config);

    const jsTests = config.test_files.filter(file => {
      return path.extname(file) !== ".sol";
    });

    const solTests = config.test_files.filter(file => {
      return path.extname(file) === ".sol";
    });

    // Add Javascript tests because there's nothing we need to do with them.
    // Solidity tests will be handled later.
    jsTests.forEach(file => {
      // There's an idiosyncracy in Mocha where the same file can't be run twice
      // unless we delete the `require` cache.
      // https://github.com/mochajs/mocha/issues/995
      delete originalrequire.cache[file];

      mocha.addFile(file);
    });

    const accounts = await this.getAccounts(interfaceAdapter);

    const testResolver = new Resolver(config, {
      includeTruffleSources: true
    });

    const { compilations } = await this.compileContractsWithTestFilesIfNeeded(
      solTests,
      config,
      testResolver
    );

    const testContracts = solTests.map(testFilePath => {
      return testResolver.require(testFilePath);
    });

    const runner = new TestRunner(config);

    await this.performInitialDeploy(config, testResolver);

    const sourcePaths = []
      .concat(
        ...compilations.map(compilation => compilation.sourceIndexes) //we don't need the indices here, just the paths
      )
      .filter(path => path); //make sure we don't pass in any undefined

    await this.defineSolidityTests(mocha, testContracts, sourcePaths, runner);

    const debuggerCompilations = Codec.Compilations.Utils.shimCompilations(
      compilations
    );

    //for stack traces, we'll need to set up a light-mode debugger...
    let bugger;
    if (config.stacktrace) {
      debug("stacktraces on!");
      bugger = await Debugger.forProject({
        compilations: debuggerCompilations,
        provider: config.provider,
        lightMode: true
      });
    }

    await this.setJSTestGlobals({
      config,
      web3,
      interfaceAdapter,
      accounts,
      testResolver,
      runner,
      compilations: debuggerCompilations,
      bugger
    });

    // Finally, run mocha.
    process.on("unhandledRejection", reason => {
      throw reason;
    });

    return new Promise(resolve => {
      this.mochaRunner = mocha.run(failures => {
        config.logger.warn = warn;
        resolve(failures);
      });
    });
  },

  createMocha: function (config) {
    // Allow people to specify config.mocha in their config.
    const mochaConfig = config.mocha || {};

    // Propagate --bail option to mocha
    mochaConfig.bail = config.bail;

    // If the command line overrides color usage, use that.
    if (config.color != null) {
      mochaConfig.color = config.color;
    } else if (config.colors != null) {
      // --colors is a mocha alias for --color
      mochaConfig.color = config.colors;
    }

    // Default to true if configuration isn't set anywhere.
    if (mochaConfig.color == null) {
      mochaConfig.color = true;
    }

    Mocha = mochaConfig.package || __webpack_require__(348450);
    delete mochaConfig.package;
    const mocha = new Mocha(mochaConfig);

    return mocha;
  },

  getAccounts: function (interfaceAdapter) {
    return interfaceAdapter.getAccounts();
  },

  compileContractsWithTestFilesIfNeeded: async function (
    solidityTestFiles,
    config,
    testResolver
  ) {
    const updated =
      (await Profiler.updated(config.with({ resolver: testResolver }))) || [];

    const compiler =
      config.compileNone || config["--compile-none"] ? "none" : config.compiler;

    let compileConfig = config.with({
      all: config.compileAll === true,
      compiler,
      files: updated.concat(solidityTestFiles),
      resolver: testResolver,
      quiet: config.runnerOutputOnly || config.quiet,
      quietWrite: true
    });
    if (config.compileAllDebug) {
      let versionString = ((compileConfig.compilers || {}).solc || {}).version;
      versionString = RangeUtils.resolveToRange(versionString);
      if (RangeUtils.rangeContainsAtLeast(versionString, "0.6.3")) {
        compileConfig = compileConfig.merge({
          compilers: {
            solc: {
              settings: {
                debug: {
                  revertStrings: "debug"
                }
              }
            }
          }
        });
      } else {
        config.logger.log(
          `\n${colors.bold(
            "Warning:"
          )} Extra revert string info requires Solidity v0.6.3 or higher. For more\n  information, see release notes <https://github.com/ethereum/solidity/releases/tag/v0.6.3>`
        );
      }
    }

    // Compile project contracts and test contracts
    const { contracts, compilations } = await WorkflowCompile.compileAndSave(
      compileConfig
    );

    return {
      contracts,
      compilations
    };
  },

  performInitialDeploy: function (config, resolver) {
    const migrateConfig = config.with({
      reset: true,
      resolver: resolver,
      quiet: true
    });
    return Migrate.run(migrateConfig);
  },

  defineSolidityTests: async (mocha, contracts, dependencyPaths, runner) => {
    for (const contract of contracts) {
      await SolidityTest.define(contract, dependencyPaths, runner, mocha);
      debug("defined solidity tests for %s", contract.contractName);
    }
  },

  setJSTestGlobals: async function ({
    config,
    web3,
    interfaceAdapter,
    accounts,
    testResolver,
    runner,
    compilations,
    bugger //for stacktracing
  }) {
    global.interfaceAdapter = interfaceAdapter;
    global.web3 = web3;
    global.assert = chai.assert;
    global.expect = chai.expect;
    global.artifacts = {
      require: importPath => {
        let contract = testResolver.require(importPath);
        //HACK: both of the following should go by means
        //of the provisioner, but I'm not sure how to make
        //that work at the moment
        contract.reloadJson = function () {
          const reloaded = testResolver.require(importPath);
          this._json = reloaded._json;
        };
        if (bugger) {
          contract.debugger = bugger;
        }
        return contract;
      }
    };
    global.config = config.normalize(config);

    global[config.debugGlobal] = async operation => {
      if (!config.debug) {
        config.logger.log(
          `${colors.bold(
            "Warning:"
          )} Invoked in-test debugger without --debug flag. ` +
            `Try: \`truffle test --debug\``
        );
        return operation;
      }

      // wrapped inside function so as not to load debugger on every test
      const { CLIDebugHook } = __webpack_require__(212834);

      // note: this.mochaRunner will be available by the time debug()
      // is invoked
      const hook = new CLIDebugHook(config, compilations, this.mochaRunner);

      return await hook.debug(operation);
    };

    const template = function (tests) {
      this.timeout(runner.TEST_TIMEOUT);

      before("prepare suite", async function () {
        this.timeout(runner.BEFORE_TIMEOUT);
        await runner.initialize();
      });

      beforeEach("before test", async function () {
        await runner.startTest();
      });

      afterEach("after test", async function () {
        await runner.endTest(this);
      });

      tests(accounts);
    };

    global.contract = function (name, tests) {
      Mocha.describe("Contract: " + name, function () {
        template.bind(this, tests)();
      });
    };

    global.contract.only = function (name, tests) {
      Mocha.describe.only("Contract: " + name, function () {
        template.bind(this, tests)();
      });
    };

    global.contract.skip = function (name, tests) {
      Mocha.describe.skip("Contract: " + name, function () {
        template.bind(this, tests)();
      });
    };
  }
};

module.exports = Test;


/***/ }),

/***/ 68710:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const { createInterfaceAdapter } = __webpack_require__(936339);
const web3Utils = __webpack_require__(118269);
const Config = __webpack_require__(120553);
const Migrate = __webpack_require__(523459);
const Resolver = __webpack_require__(648511);
const expect = __webpack_require__(139883);
const util = __webpack_require__(431669);
const debug = __webpack_require__(354686)("lib:testing:testrunner");
const Decoder = __webpack_require__(18852);
const Codec = __webpack_require__(20102);

class TestRunner {
  constructor(options = {}) {
    expect.options(options, [
      "resolver",
      "provider",
      "contracts_build_directory"
    ]);

    this.config = Config.default().merge(options);

    this.logger = options.logger || console;
    this.provider = options.provider;

    this.can_snapshot = false;
    this.first_snapshot = true;
    this.initial_snapshot = null;
    this.interfaceAdapter = createInterfaceAdapter({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });
    this.decoder = null;

    // For each test
    this.currentTestStartBlock = null;

    this.BEFORE_TIMEOUT =
      (options.mocha && options.mocha.before_timeout) || 120000;
    this.TEST_TIMEOUT = (options.mocha && options.mocha.timeout) || 300000;
  }

  async initialize() {
    debug("initializing");
    this.config.resolver = new Resolver(this.config, {
      includeTruffleSources: true
    });

    if (this.first_snapshot) {
      debug("taking first snapshot");
      try {
        let initial_snapshot = await this.snapshot();
        this.can_snapshot = true;
        this.initial_snapshot = initial_snapshot;
      } catch (error) {
        debug("first snapshot failed");
        debug("Error: %O", error);
      }
      this.first_snapshot = false;
    } else {
      await this.resetState();
    }

    this.decoder = await Decoder.forProject(this.provider, {
      config: this.config
    });
  }

  async deploy() {
    await Migrate.run(
      this.config.with({
        reset: true,
        quiet: true
      })
    );
  }

  async resetState() {
    if (this.can_snapshot) {
      debug("reverting...");
      await this.revert(this.initial_snapshot);
      this.initial_snapshot = await this.snapshot();
    } else {
      debug("redeploying...");
      await this.deploy();
    }
  }

  async startTest() {
    let blockNumber = await this.interfaceAdapter.getBlockNumber();
    let one = web3Utils.toBN(1);
    blockNumber = web3Utils.toBN(blockNumber);

    // Add one in base 10
    this.currentTestStartBlock = blockNumber.add(one);
  }

  async endTest(mocha) {
    // Skip logging if test passes and `show-events` option is not true
    if (mocha.currentTest.state !== "failed" && !this.config["show-events"]) {
      return;
    }

    function indent(input, indentation, initialPrefix = "") {
      const unindented = typeof input === "string" ? input.split("\n") : input;
      return unindented
        .map((line, index) =>
          index === 0
            ? initialPrefix + " ".repeat(indentation - initialPrefix) + line
            : " ".repeat(indentation) + line
        )
        .join("\n");
    }

    function printEvent(decoding, indentation = 0, initialPrefix = "") {
      const anonymousPrefix =
        decoding.kind === "anonymous" ? "<anonymous> " : "";
      const className = decoding.definedIn
        ? decoding.definedIn.typeName
        : decoding.class.typeName;
      const eventName = decoding.abi.name;
      const fullEventName = anonymousPrefix + `${className}.${eventName}`;
      const eventArgs = decoding.arguments.map(({ name, indexed, value }) => {
        let namePrefix = name ? `${name}: ` : "";
        let indexedPrefix = indexed ? "<indexed> " : "";
        let displayValue = util.inspect(
          new Codec.Format.Utils.Inspect.ResultInspector(value),
          {
            depth: null,
            colors: true,
            maxArrayLength: null,
            breakLength: 80 - indentation //should this include prefix lengths as well?
          }
        );
        let typeString = ` (type: ${Codec.Format.Types.typeStringWithoutLocation(
          value.type
        )})`;
        return namePrefix + indexedPrefix + displayValue + typeString + ",";
      });
      {
        const len = eventArgs.length - 1;
        eventArgs[len] = eventArgs[len].slice(0, -1); // remove the final comma
      }
      if (decoding.arguments.length > 0) {
        return indent(
          `${fullEventName}(\n${indent(eventArgs, 2)}\n)`,
          indentation,
          initialPrefix
        );
      } else {
        return indent(`${fullEventName}()`, indentation, initialPrefix);
      }
    }

    const logs = await this.decoder.events({
      //NOTE: block numbers shouldn't be over 2^53 so this
      //should be fine, but should change this once decoder
      //accepts more general types for blocks
      fromBlock: this.currentTestStartBlock.toNumber(),
      extras: "necessary" //include weird decodings if usual ones fail :P
    });

    const userDefinedEventLogs = logs.filter(log => {
      return log.decodings.every(decoding => decoding.abi.name !== "TestEvent");
    });

    if (userDefinedEventLogs.length === 0) {
      this.logger.log("    > No events were emitted");
      return;
    }

    this.logger.log("\n    Events emitted during test:");
    this.logger.log("    ---------------------------");
    this.logger.log("");

    for (const log of userDefinedEventLogs) {
      switch (log.decodings.length) {
        case 0:
          this.logger.log(`    Warning: Could not decode event!`);
          this.logger.log("");
          break;
        case 1:
          this.logger.log(printEvent(log.decodings[0], 4));
          this.logger.log("");
          break;
        default:
          this.logger.log(`    Ambiguous event, possible interpretations:`);
          for (const decoding of log.decodings) {
            this.logger.log(printEvent(decoding, 6, "    * "));
          }
          this.logger.log("");
          break;
      }
    }
    this.logger.log("\n    ---------------------------");
  }

  async snapshot() {
    return (await this.rpc("evm_snapshot")).result;
  }

  async revert(snapshot_id) {
    await this.rpc("evm_revert", [snapshot_id]);
  }

  async rpc(method, arg) {
    let request = {
      jsonrpc: "2.0",
      method: method,
      id: Date.now(),
      params: arg
    };

    let result = await util.promisify(this.provider.send)(request);

    if (result.error != null) {
      throw new Error("RPC Error: " + (result.error.message || result.error));
    }

    return result;
  }
}

module.exports = TestRunner;


/***/ }),

/***/ 287352:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 287352;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 557817:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 557817;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 990670:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Abi = exports.ConstructorEntry = exports.FallbackEntry = exports.ReceiveEntry = exports.FunctionEntry = exports.ErrorEntry = exports.EventEntry = exports.EventParameter = exports.Parameter = void 0;
const fc = __importStar(__webpack_require__(145794));
const faker_1 = __importDefault(__webpack_require__(285384));
const change_case_1 = __webpack_require__(377159);
const Parameter = () => fc
    .tuple(fc.record({
    name: ParameterName()
}), TypeRecord())
    .map(([{ name }, type]) => (Object.assign({ name }, type)));
exports.Parameter = Parameter;
const EventParameter = () => fc
    .tuple(fc.record({
    name: ParameterName(),
    indexed: fc.boolean()
}), TypeRecord())
    .map(([{ name, indexed }, type]) => (Object.assign({ name, indexed }, type)));
exports.EventParameter = EventParameter;
const EventEntry = () => fc.record({
    type: fc.constant("event"),
    name: EventName(),
    inputs: fc.array(exports.EventParameter(), { maxLength: 10 }).filter(inputs => {
        if (inputs.filter(({ indexed }) => indexed).length > 3) {
            // only up to 3 params can be indexed
            return false;
        }
        // names that are not blank should be unique
        const names = inputs.map(({ name }) => name).filter(name => name !== "");
        return names.length === new Set(names).size;
    }),
    anonymous: fc.boolean()
});
exports.EventEntry = EventEntry;
const ErrorEntry = () => fc.record({
    type: fc.constant("error"),
    name: ErrorName(),
    inputs: fc.array(exports.Parameter(), { maxLength: 10 }).filter(inputs => {
        // names that are not blank should be unique
        const names = inputs.map(({ name }) => name).filter(name => name !== "");
        return names.length === new Set(names).size;
    })
});
exports.ErrorEntry = ErrorEntry;
const FunctionEntry = () => fc
    .tuple(fc.record({
    type: fc.constant("function")
}, { withDeletedKeys: true }), fc.record({
    name: FunctionName(),
    inputs: fc.array(exports.Parameter(), { maxLength: 10 })
}), fc.record({
    outputs: fc.array(exports.Parameter(), { maxLength: 10 })
}, { withDeletedKeys: true }), fc
    .tuple(fc.oneof(fc.constant("pure"), fc.constant("view"), fc.constant("nonpayable"), fc.constant("payable")), fc.boolean(), fc.boolean())
    .map(([stateMutability, includeLegacy, includeModern]) => {
    const payable = stateMutability === "payable";
    const constant = stateMutability === "view" || stateMutability === "pure";
    const modern = { stateMutability };
    const legacy = { payable, constant };
    return includeLegacy && includeModern
        ? Object.assign(Object.assign({}, modern), legacy) : includeModern
        ? modern
        : legacy;
}))
    .map(records => records.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {}))
    .filter(entry => {
    const { inputs, outputs = [] } = entry;
    // names that are not blank should be unique
    const names = [...inputs, ...outputs]
        .map(({ name }) => name)
        .filter(name => name !== "");
    return names.length === new Set(names).size;
});
exports.FunctionEntry = FunctionEntry;
const ReceiveEntry = () => fc.record({
    type: fc.constant("receive"),
    stateMutability: fc.constant("payable")
});
exports.ReceiveEntry = ReceiveEntry;
const FallbackEntry = () => fc
    .tuple(fc.record({
    type: fc.constant("fallback")
}), fc
    .tuple(fc.oneof(fc.constant("nonpayable"), fc.constant("payable")), fc.boolean(), fc.boolean())
    .map(([stateMutability, includeLegacy, includeModern]) => {
    const payable = stateMutability === "payable";
    const modern = { stateMutability };
    const legacy = { payable };
    return includeLegacy && includeModern
        ? Object.assign(Object.assign({}, modern), legacy) : includeModern
        ? modern
        : legacy;
}))
    .map(([{ type }, mutabilityFields]) => (Object.assign({ type }, mutabilityFields)));
exports.FallbackEntry = FallbackEntry;
const ConstructorEntry = () => fc
    .tuple(fc.record({
    type: fc.constant("constructor"),
    inputs: fc.array(exports.Parameter(), { maxLength: 10 }).filter(inputs => {
        // names that are not blank should be unique
        const names = inputs.map(({ name }) => name).filter(name => name !== "");
        return names.length === new Set(names).size;
    })
}), fc
    .tuple(fc.oneof(fc.constant("nonpayable"), fc.constant("payable")), fc.boolean(), fc.boolean())
    .map(([stateMutability, includeLegacy, includeModern]) => {
    const payable = stateMutability === "payable";
    const modern = { stateMutability };
    const legacy = { payable };
    return includeLegacy && includeModern
        ? Object.assign(Object.assign({}, modern), legacy) : includeModern
        ? modern
        : legacy;
}))
    .map(([{ type, inputs }, mutabilityFields]) => (Object.assign({ type,
    inputs }, mutabilityFields)));
exports.ConstructorEntry = ConstructorEntry;
const Abi = () => fc
    .tuple(exports.ConstructorEntry(), exports.FallbackEntry(), exports.ReceiveEntry(), fc.array(fc.oneof(exports.FunctionEntry(), exports.EventEntry(), exports.ErrorEntry())))
    .chain(([constructor, fallback, receive, entries]) => fc.shuffledSubarray([constructor, fallback, receive, ...entries]));
exports.Abi = Abi;
var Numerics;
(function (Numerics) {
    // 0 < n <= 32
    // use subtraction so that fast-check treats 32 as simpler than 1
    Numerics.Bytes = () => fc.nat(31).map(k => 32 - k);
    // 0 < n <= 256, 8 | n
    Numerics.Bits = () => Numerics.Bytes().map(k => 8 * k);
    // 0 < n <= 80
    // use fancy math so that fast-check treats 18 as the simplest case
    //
    //     0 ----------------- 79
    //     lines up as:
    //     18 ------ 80, 0 --- 17
    Numerics.DecimalPlaces = () => fc.nat(79).map(k => ((k + 17) % 80) + 1);
    Numerics.Precision = () => fc.tuple(Numerics.Bits(), Numerics.DecimalPlaces());
})(Numerics || (Numerics = {}));
var Primitives;
(function (Primitives) {
    Primitives.Uint = () => Numerics.Bits().map(m => `uint${m}`);
    Primitives.Int = () => Numerics.Bits().map(m => `int${m}`);
    Primitives.Address = () => fc.constant("address");
    Primitives.Bool = () => fc.constant("bool");
    Primitives.Fixed = () => Numerics.Precision().map(([m, n]) => `fixed${m}x${n}`);
    Primitives.Ufixed = () => Numerics.Precision().map(([m, n]) => `ufixed${m}x${n}`);
    Primitives.BytesM = () => Numerics.Bytes().map(m => `bytes${m}`);
    Primitives.Function = () => fc.constant("function");
    Primitives.Bytes = () => fc.constant("bytes");
    Primitives.String = () => fc.constant("string");
    Primitives.Tuple = () => fc.constant("tuple");
})(Primitives || (Primitives = {}));
const Primitive = () => fc.oneof(Primitives.Uint(), Primitives.Int(), Primitives.Address(), Primitives.Bool(), Primitives.Fixed(), Primitives.Ufixed(), Primitives.BytesM(), Primitives.Function(), Primitives.Bytes(), Primitives.String(), Primitives.Tuple());
const Type = fc.memo(n => n === 0
    ? Primitive()
    : // we cap this at 3 so that fast-check doesn't blow the stack
        fc.oneof(Primitive(), ArrayFixed(n > 3 ? 3 : n), ArrayDynamic(n)));
const ArrayFixed = fc.memo(n => fc
    .tuple(Type(n - 1), fc.integer(1, 256))
    .map(([type, length]) => `${type}[${length}]`));
const ArrayDynamic = fc.memo(n => Type(n - 1).map(type => `${type}[]`));
const reservedWords = new Set([
    "Error",
    "Panic",
    "_",
    "abi",
    "abstract",
    "addmod",
    "address",
    "after",
    "alias",
    "anonymous",
    "apply",
    "as",
    "assembly",
    "assert",
    "auto",
    "block",
    "blockhash",
    "bool",
    "break",
    "byte",
    "bytes",
    "calldata",
    "case",
    "catch",
    "constant",
    "constructor",
    "continue",
    "contract",
    "copyof",
    "days",
    "default",
    "define",
    "delete",
    "ecrecover",
    "else",
    "emit",
    "enum",
    "error",
    "ether",
    "event",
    "external",
    "fallback",
    "false",
    "final",
    "finney",
    "fixed",
    "for",
    "from",
    "function",
    "gasleft",
    "gwei",
    "hours",
    "if",
    "immutable",
    "implements",
    "import",
    "in",
    "indexed",
    "inline",
    "int",
    "interface",
    "internal",
    "is",
    "keccak256",
    "let",
    "library",
    "log0",
    "log1",
    "log2",
    "log3",
    "log4",
    "macro",
    "mapping",
    "match",
    "memory",
    "minutes",
    "modifier",
    "msg",
    "mulmod",
    "mutable",
    "new",
    "now",
    "null",
    "of",
    "override",
    "partial",
    "payable",
    "pragma",
    "private",
    "promise",
    "public",
    "pure",
    "receive",
    "reference",
    "relocatable",
    "require",
    "return",
    "returns",
    "revert",
    "ripemd160",
    "sealed",
    "seconds",
    "selfdestruct",
    "sha256",
    "sha3",
    "sizeof",
    "static",
    "storage",
    "string",
    "struct",
    "suicide",
    "super",
    "supports",
    "switch",
    "szabo",
    "this",
    "throw",
    "true",
    "try",
    "tx",
    "type",
    "typedef",
    "typeof",
    "ufixed",
    "uint",
    "unchecked",
    "using",
    "var",
    "view",
    "virtual",
    "weeks",
    "wei",
    "while",
    "years"
]);
// borrowed from https://runkit.com/dubzzz/faker-to-fast-check
const fakerToArb = (template, transform = change_case_1.camelCase) => {
    return fc
        .integer()
        .noBias()
        .noShrink()
        .map(seed => {
        faker_1.default.seed(seed);
        return transform(faker_1.default.fake(template));
    })
        .filter(word => !reservedWords.has(word));
};
const ParameterName = () => fc.frequency({ arbitrary: fakerToArb("{{hacker.noun}}"), weight: 9 }, { arbitrary: fc.constant(""), weight: 1 });
const EventName = () => fakerToArb("{{hacker.verb}} {{hacker.noun}}", change_case_1.pascalCase);
const ErrorName = () => fakerToArb("{{hacker.noun}} {{hacker.noun}}", change_case_1.pascalCase);
const FunctionName = () => fakerToArb("{{hacker.verb}} {{hacker.noun}}");
const TypeRecord = () => Type().chain(type => type.startsWith("tuple")
    ? fc.record({
        type: fc.constant(type),
        components: fc
            .array(exports.Parameter().filter(({ name }) => name !== ""), { minLength: 1, maxLength: 5 })
            .filter(items => {
            const names = items
                .map(({ name }) => name)
                .filter(name => name !== "");
            return names.length === new Set(names).size;
        })
    })
    : fc.record({
        type: fc.constant(type)
    }));
//# sourceMappingURL=arbitrary.js.map

/***/ }),

/***/ 207651:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Arbitrary = void 0;
__exportStar(__webpack_require__(851931), exports);
__exportStar(__webpack_require__(857794), exports);
const Arbitrary = __importStar(__webpack_require__(990670));
exports.Arbitrary = Arbitrary;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 857794:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.normalizeEntry = exports.normalize = void 0;
const normalize = (looseAbi) => looseAbi.map(exports.normalizeEntry);
exports.normalize = normalize;
const normalizeEntry = (looseEntry) => {
    if (looseEntry.type === "event" || looseEntry.type === "error") {
        // nothing gets normalized for events or errors right now
        return looseEntry;
    }
    const entry = Object.assign(Object.assign(Object.assign({}, looseEntry), normalizeStateMutability(looseEntry)), { type: looseEntry.type || "function" });
    if (entry.type === "function") {
        entry.outputs = entry.outputs || [];
    }
    delete entry.payable;
    delete entry.constant;
    return entry;
};
exports.normalizeEntry = normalizeEntry;
const normalizeStateMutability = ({ stateMutability, payable, constant }) => {
    if (stateMutability) {
        return { stateMutability };
    }
    return {
        stateMutability: payable ? "payable" : constant ? "view" : "nonpayable"
    };
};
//# sourceMappingURL=normalize.js.map

/***/ }),

/***/ 851931:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 529463:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const contract_schema_1 = __importDefault(__webpack_require__(418370));
const fs_extra_1 = __importDefault(__webpack_require__(655674));
const path_1 = __importDefault(__webpack_require__(385622));
const os_1 = __importDefault(__webpack_require__(712087));
const utils_1 = __webpack_require__(437285);
const debug = __webpack_require__(690247)("artifactor");
class Artifactor {
    constructor(destination) {
        this.destination = destination;
    }
    save(artifactObject) {
        return __awaiter(this, void 0, void 0, function* () {
            const normalizedNewArtifact = contract_schema_1.default.normalize(artifactObject);
            const contractName = normalizedNewArtifact.contractName;
            if (!contractName)
                throw new Error("You must specify a contract name.");
            const outputPath = path_1.default.join(this.destination, `${contractName}.json`);
            try {
                const existingArtifact = fs_extra_1.default.readFileSync(outputPath, "utf8"); // check if artifact already exists
                const existingArtifactObject = JSON.parse(existingArtifact); // parse existing artifact
                const normalizedExistingArtifact = contract_schema_1.default.normalize(existingArtifactObject);
                const completeArtifact = utils_1.finalizeArtifact(normalizedExistingArtifact, normalizedNewArtifact);
                utils_1.writeArtifact(completeArtifact, outputPath);
            }
            catch (e) {
                // if artifact doesn't already exist, write new file
                if (e.code === "ENOENT")
                    return utils_1.writeArtifact(normalizedNewArtifact, outputPath);
                else if (e instanceof SyntaxError)
                    throw e; // catches improperly formatted artifact json
                throw e; // catch all other errors
            }
        });
    }
    saveAll(artifactObjects) {
        return __awaiter(this, void 0, void 0, function* () {
            let newArtifactObjects = {};
            if (Array.isArray(artifactObjects)) {
                const tmpArtifactArray = artifactObjects;
                tmpArtifactArray.forEach(artifactObj => {
                    if (newArtifactObjects[artifactObj.contract_name || artifactObj.contractName]) {
                        console.warn(`${os_1.default.EOL}> Duplicate contract names found for ${artifactObj.contract_name}.${os_1.default.EOL}` +
                            `> This can cause errors and unknown behavior. Please rename one of your contracts.`);
                    }
                    newArtifactObjects[artifactObj.contract_name || artifactObj.contractName] = artifactObj;
                });
            }
            else {
                newArtifactObjects = artifactObjects;
            }
            try {
                fs_extra_1.default.statSync(this.destination); // check if destination exists
            }
            catch (e) {
                if (e.code === "ENOENT")
                    // if destination doesn't exist, throw error
                    throw new Error(`Destination "${this.destination}" doesn't exist!`);
                throw e; // throw on all other errors
            }
            Object.keys(newArtifactObjects).forEach(contractName => {
                let artifactObject = newArtifactObjects[contractName];
                this.save(artifactObject);
            });
        });
    }
}
module.exports = Artifactor;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 437285:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.finalizeArtifact = exports.writeArtifact = void 0;
const fs_extra_1 = __importDefault(__webpack_require__(655674));
const lodash_merge_1 = __importDefault(__webpack_require__(672378));
const lodash_assign_1 = __importDefault(__webpack_require__(631730));
function writeArtifact(completeArtifact, outputPath) {
    completeArtifact.updatedAt = new Date().toISOString();
    fs_extra_1.default.writeFileSync(outputPath, JSON.stringify(completeArtifact, null, 2), "utf8");
}
exports.writeArtifact = writeArtifact;
function finalizeArtifact(normalizedExistingArtifact, normalizedNewArtifact) {
    const knownNetworks = lodash_merge_1.default({}, normalizedExistingArtifact.networks, normalizedNewArtifact.networks);
    const completeArtifact = lodash_assign_1.default({}, normalizedExistingArtifact, normalizedNewArtifact, { networks: knownNetworks });
    return completeArtifact;
}
exports.finalizeArtifact = finalizeArtifact;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 986317:
/***/ ((module) => {

"use strict";

const Blockchain = {
    getBlockByNumber(blockNumber, provider, callback) {
        const params = [blockNumber, true];
        provider.send({
            jsonrpc: "2.0",
            method: "eth_getBlockByNumber",
            params,
            id: Date.now()
        }, callback);
    },
    getBlockByHash(blockHash, provider, callback) {
        const params = [blockHash, true];
        provider.send({
            jsonrpc: "2.0",
            method: "eth_getBlockByHash",
            params,
            id: Date.now()
        }, callback);
    },
    parse(uri) {
        const parsed = {};
        if (uri.indexOf("blockchain://") !== 0)
            return parsed;
        const cleanUri = uri.replace("blockchain://", "");
        const pieces = cleanUri.split("/block/");
        parsed.genesis_hash = `0x${pieces[0]}`;
        parsed.block_hash = `0x${pieces[1]}`;
        return parsed;
    },
    asURI(provider) {
        return new Promise((resolve, reject) => {
            let genesis, latest;
            this.getBlockByNumber("0x0", provider, (err, { result }) => {
                if (err)
                    return reject(err);
                genesis = result;
                this.getBlockByNumber("latest", provider, (err, { result }) => {
                    if (err)
                        return reject(err);
                    latest = result;
                    const url = `blockchain://${genesis.hash.replace("0x", "")}/block/${latest.hash.replace("0x", "")}`;
                    resolve(url);
                });
            });
        });
    },
    matches(uri, provider) {
        return new Promise((resolve, reject) => {
            const parsedUri = this.parse(uri);
            const expectedGenesis = parsedUri.genesis_hash;
            const expectedBlock = parsedUri.block_hash;
            this.getBlockByNumber("0x0", provider, (err, { result }) => {
                if (err)
                    return reject(err);
                const block = result;
                if (block.hash !== expectedGenesis)
                    return resolve(false);
                this.getBlockByHash(expectedBlock, provider, (err, { result }) => {
                    // Treat an error as if the block didn't exist. This is because
                    // some clients respond differently.
                    const block = result;
                    if (err || block == null) {
                        return resolve(false);
                    }
                    resolve(true);
                });
            });
        });
    }
};
module.exports = Blockchain;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 908135:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.parseCode = void 0;
const opcodes_1 = __importDefault(__webpack_require__(489537));
const cbor = __importStar(__webpack_require__(82141));
/**
 * parseCode - return a list of instructions given a 0x-prefixed code string.
 *
 * If numInstructions is not passed in, we attempt to strip contract
 * metadata.  This won't work very well if the code is for a constructor or a
 * contract that can create other contracts, but it's better than nothing.
 *
 * WARNING: Don't invoke the function that way if you're dealing with a
 * constructor with arguments attached!  Then you could get disaster!
 *
 * If you pass in numInstructions (hint: count the semicolons in the source
 * map, then add one) this is used to exclude metadata instead.
 *
 * @param  {String} hexString Hex string representing the code
 * @return Array               Array of instructions
 */
function parseCode(hexString, numInstructions = null) {
    // Convert to an array of bytes
    let code = new Uint8Array((hexString.slice(2).match(/(..?)/g) || []).map(hex => parseInt(hex, 16)));
    const stripMetadata = numInstructions === null;
    if (stripMetadata && code.length >= 2) {
        // Remove the contract metadata; last two bytes encode its length (not
        // including those two bytes)
        const metadataLength = (code[code.length - 2] << 8) + code[code.length - 1];
        //check: is this actually valid CBOR?
        if (metadataLength + 2 <= code.length) {
            const metadata = code.subarray(-(metadataLength + 2), -2);
            if (isValidCBOR(metadata)) {
                code = code.subarray(0, -(metadataLength + 2));
            }
        }
    }
    let instructions = [];
    for (let pc = 0; pc < code.length &&
        (stripMetadata || instructions.length < numInstructions); pc++) {
        let opcode = {
            pc,
            name: opcodes_1.default(code[pc])
        };
        if (opcode.name.slice(0, 4) === "PUSH") {
            const length = code[pc] - 0x60 + 1; //0x60 is code for PUSH1
            let pushData = code.subarray(pc + 1, pc + length + 1);
            if (pushData.length < length) {
                //if we run out of bytes for our pushdata, fill the rest
                //with zeroes
                pushData = Uint8Array.from([
                    ...pushData,
                    ...new Uint8Array(length - pushData.length)
                ]);
            }
            // convert pushData to hex
            opcode.pushData = `0x${Buffer.from(pushData).toString("hex")}`;
            pc += length;
        }
        instructions.push(opcode);
    }
    return instructions;
}
exports.parseCode = parseCode;
exports.default = {
    //for compatibility
    parseCode
};
function isValidCBOR(metadata) {
    try {
        //attempt to decode but discard the value
        //note this *will* throw if there's data left over,
        //which is what we want it to do
        cbor.decodeFirstSync(metadata);
    }
    catch (_a) {
        return false;
    }
    return true;
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 489537:
/***/ ((module) => {

"use strict";

const codes = {
    0x00: "STOP",
    0x01: "ADD",
    0x02: "MUL",
    0x03: "SUB",
    0x04: "DIV",
    0x05: "SDIV",
    0x06: "MOD",
    0x07: "SMOD",
    0x08: "ADDMOD",
    0x09: "MULMOD",
    0x0a: "EXP",
    0x0b: "SIGNEXTEND",
    // 0x10 range - bit ops
    0x10: "LT",
    0x11: "GT",
    0x12: "SLT",
    0x13: "SGT",
    0x14: "EQ",
    0x15: "ISZERO",
    0x16: "AND",
    0x17: "OR",
    0x18: "XOR",
    0x19: "NOT",
    0x1a: "BYTE",
    0x1b: "SHL",
    0x1c: "SHR",
    0x1d: "SAR",
    // 0x20 range - crypto
    0x20: "SHA3",
    // 0x30 range - closure state
    0x30: "ADDRESS",
    0x31: "BALANCE",
    0x32: "ORIGIN",
    0x33: "CALLER",
    0x34: "CALLVALUE",
    0x35: "CALLDATALOAD",
    0x36: "CALLDATASIZE",
    0x37: "CALLDATACOPY",
    0x38: "CODESIZE",
    0x39: "CODECOPY",
    0x3a: "GASPRICE",
    0x3b: "EXTCODESIZE",
    0x3c: "EXTCODECOPY",
    0x3d: "RETURNDATASIZE",
    0x3e: "RETURNDATACOPY",
    0x3f: "EXTCODEHASH",
    // 0x40 range - block operations
    0x40: "BLOCKHASH",
    0x41: "COINBASE",
    0x42: "TIMESTAMP",
    0x43: "NUMBER",
    0x44: "DIFFICULTY",
    0x45: "GASLIMIT",
    0x46: "CHAINID",
    0x47: "SELFBALANCE",
    // 0x50 range - 'storage' and execution
    0x50: "POP",
    0x51: "MLOAD",
    0x52: "MSTORE",
    0x53: "MSTORE8",
    0x54: "SLOAD",
    0x55: "SSTORE",
    0x56: "JUMP",
    0x57: "JUMPI",
    0x58: "PC",
    0x59: "MSIZE",
    0x5a: "GAS",
    0x5b: "JUMPDEST",
    // 0x60 & 0x70 range - pushes
    0x60: "PUSH1",
    0x61: "PUSH2",
    0x62: "PUSH3",
    0x63: "PUSH4",
    0x64: "PUSH5",
    0x65: "PUSH6",
    0x66: "PUSH7",
    0x67: "PUSH8",
    0x68: "PUSH9",
    0x69: "PUSH10",
    0x6a: "PUSH11",
    0x6b: "PUSH12",
    0x6c: "PUSH13",
    0x6d: "PUSH14",
    0x6e: "PUSH15",
    0x6f: "PUSH16",
    0x70: "PUSH17",
    0x71: "PUSH18",
    0x72: "PUSH19",
    0x73: "PUSH20",
    0x74: "PUSH21",
    0x75: "PUSH22",
    0x76: "PUSH23",
    0x77: "PUSH24",
    0x78: "PUSH25",
    0x79: "PUSH26",
    0x7a: "PUSH27",
    0x7b: "PUSH28",
    0x7c: "PUSH29",
    0x7d: "PUSH30",
    0x7e: "PUSH31",
    0x7f: "PUSH32",
    // 0x80 range - duplication
    0x80: "DUP1",
    0x81: "DUP2",
    0x82: "DUP3",
    0x83: "DUP4",
    0x84: "DUP5",
    0x85: "DUP6",
    0x86: "DUP7",
    0x87: "DUP8",
    0x88: "DUP9",
    0x89: "DUP10",
    0x8a: "DUP11",
    0x8b: "DUP12",
    0x8c: "DUP13",
    0x8d: "DUP14",
    0x8e: "DUP15",
    0x8f: "DUP16",
    // 0x90 range - swaps
    0x90: "SWAP1",
    0x91: "SWAP2",
    0x92: "SWAP3",
    0x93: "SWAP4",
    0x94: "SWAP5",
    0x95: "SWAP6",
    0x96: "SWAP7",
    0x97: "SWAP8",
    0x98: "SWAP9",
    0x99: "SWAP10",
    0x9a: "SWAP11",
    0x9b: "SWAP12",
    0x9c: "SWAP13",
    0x9d: "SWAP14",
    0x9e: "SWAP15",
    0x9f: "SWAP16",
    // '0xa0' range - logging
    0xa0: "LOG0",
    0xa1: "LOG1",
    0xa2: "LOG2",
    0xa3: "LOG3",
    0xa4: "LOG4",
    // '0xf0' range - closures
    0xf0: "CREATE",
    0xf1: "CALL",
    0xf2: "CALLCODE",
    0xf3: "RETURN",
    0xf4: "DELEGATECALL",
    0xf5: "CREATE2",
    0xfa: "STATICCALL",
    0xfd: "REVERT",
    //(we can omit 0xfe INVALID)
    0xff: "SELFDESTRUCT"
};
module.exports = (op) => (codes[op] ? codes[op] : "INVALID");
//# sourceMappingURL=opcodes.js.map

/***/ }),

/***/ 151325:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getEventAllocations = exports.getCalldataAllocations = exports.abiSizeInfo = exports.getAbiAllocations = exports.FallbackOutputAllocation = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abi-data:allocate");
const Import = __importStar(__webpack_require__(753137));
const AbiDataUtils = __importStar(__webpack_require__(785941));
const Evm = __importStar(__webpack_require__(149218));
const Common = __importStar(__webpack_require__(299987));
const Ast = __importStar(__webpack_require__(114442));
const Format = __importStar(__webpack_require__(429965));
const lodash_partition_1 = __importDefault(__webpack_require__(246748));
exports.FallbackOutputAllocation = {
    kind: "returnmessage",
    selector: new Uint8Array(),
    allocationMode: "full"
};
function getAbiAllocations(userDefinedTypes) {
    let allocations = {};
    for (const dataType of Object.values(userDefinedTypes)) {
        if (dataType.typeClass === "struct") {
            try {
                allocations = allocateStruct(dataType, userDefinedTypes, allocations);
            }
            catch (_) {
                //if allocation fails... oh well, allocation fails, we do nothing and just move on :P
                //note: a better way of handling this would probably be to *mark* it
                //as failed rather than throwing an exception as that would lead to less
                //recomputation, but this is simpler and I don't think the recomputation
                //should really be a problem
            }
        }
    }
    return allocations;
}
exports.getAbiAllocations = getAbiAllocations;
function allocateStruct(dataType, userDefinedTypes, existingAllocations) {
    //NOTE: dataType here should be a *stored* type!
    //it is up to the caller to take care of this
    return allocateMembers(dataType.id, dataType.memberTypes, userDefinedTypes, existingAllocations);
}
//note: we will still allocate circular structs, even though they're not allowed in the abi, because it's
//not worth the effort to detect them.  However on mappings or internal functions, we'll vomit (allocate null)
function allocateMembers(parentId, members, userDefinedTypes, existingAllocations, start = 0) {
    let dynamic = false;
    //note that we will mutate the start argument also!
    //don't allocate things that have already been allocated
    if (parentId in existingAllocations) {
        return existingAllocations;
    }
    let allocations = Object.assign({}, existingAllocations); //otherwise, we'll be adding to this, so we better clone
    let memberAllocations = [];
    for (const member of members) {
        let length;
        let dynamicMember;
        ({ size: length, dynamic: dynamicMember, allocations } = abiSizeAndAllocate(member.type, userDefinedTypes, allocations));
        //vomit on illegal types in calldata -- note the short-circuit!
        if (length === undefined) {
            allocations[parentId] = null;
            return allocations;
        }
        let pointer = {
            location: "abi",
            start,
            length
        };
        memberAllocations.push({
            name: member.name,
            type: member.type,
            pointer
        });
        start += length;
        dynamic = dynamic || dynamicMember;
    }
    allocations[parentId] = {
        members: memberAllocations,
        length: dynamic ? Evm.Utils.WORD_SIZE : start,
        dynamic
    };
    return allocations;
}
//first return value is the actual size.
//second return value is whether the type is dynamic
//both will be undefined if type is a mapping or internal function
//third return value is resulting allocations, INCLUDING the ones passed in
function abiSizeAndAllocate(dataType, userDefinedTypes, existingAllocations) {
    switch (dataType.typeClass) {
        case "bool":
        case "address":
        case "contract":
        case "int":
        case "uint":
        case "fixed":
        case "ufixed":
        case "enum":
            return {
                size: Evm.Utils.WORD_SIZE,
                dynamic: false,
                allocations: existingAllocations
            };
        case "string":
            return {
                size: Evm.Utils.WORD_SIZE,
                dynamic: true,
                allocations: existingAllocations
            };
        case "bytes":
            return {
                size: Evm.Utils.WORD_SIZE,
                dynamic: dataType.kind === "dynamic",
                allocations: existingAllocations
            };
        case "mapping":
            return {
                allocations: existingAllocations
            };
        case "function":
            switch (dataType.visibility) {
                case "external":
                    return {
                        size: Evm.Utils.WORD_SIZE,
                        dynamic: false,
                        allocations: existingAllocations
                    };
                case "internal":
                    return {
                        allocations: existingAllocations
                    };
            }
        case "array": {
            switch (dataType.kind) {
                case "dynamic":
                    return {
                        size: Evm.Utils.WORD_SIZE,
                        dynamic: true,
                        allocations: existingAllocations
                    };
                case "static":
                    if (dataType.length.isZero()) {
                        //arrays of length 0 are static regardless of base type
                        return {
                            size: 0,
                            dynamic: false,
                            allocations: existingAllocations
                        };
                    }
                    const { size: baseSize, dynamic, allocations } = abiSizeAndAllocate(dataType.baseType, userDefinedTypes, existingAllocations);
                    return {
                        //WARNING!  The use of toNumber() here may throw an exception!
                        //I'm judging this OK since if you have arrays that large we have bigger problems :P
                        size: dataType.length.toNumber() * baseSize,
                        dynamic,
                        allocations
                    };
            }
        }
        case "struct": {
            let allocations = existingAllocations;
            let allocation = allocations[dataType.id];
            if (allocation === undefined) {
                //if we don't find an allocation, we'll have to do the allocation ourselves
                const storedType = (userDefinedTypes[dataType.id]);
                if (!storedType) {
                    throw new Common.UnknownUserDefinedTypeError(dataType.id, Format.Types.typeString(dataType));
                }
                allocations = allocateStruct(storedType, userDefinedTypes, existingAllocations);
                allocation = allocations[storedType.id];
            }
            //having found our allocation, if it's not null, we can just look up its size and dynamicity
            if (allocation !== null) {
                return {
                    size: allocation.length,
                    dynamic: allocation.dynamic,
                    allocations
                };
            }
            //if it is null, this type doesn't go in the abi
            else {
                return {
                    allocations
                };
            }
        }
        case "tuple": {
            //Warning! Yucky wasteful recomputation here!
            let size = 0;
            let dynamic = false;
            //note that we don't just invoke allocateStruct here!
            //why not? because it has no ID to store the result in!
            //and we can't use a fake like -1 because there might be a recursive call to it,
            //and then the results would overwrite each other
            //I mean, we could do some hashing thing or something, but I think it's easier to just
            //copy the logic in this one case (sorry)
            for (let member of dataType.memberTypes) {
                let { size: memberSize, dynamic: memberDynamic } = abiSizeAndAllocate(member.type, userDefinedTypes, existingAllocations);
                size += memberSize;
                dynamic = dynamic || memberDynamic;
            }
            return { size, dynamic, allocations: existingAllocations };
        }
    }
}
//assumes you've already done allocation! don't use if you haven't!
/**
 * @protected
 */
function abiSizeInfo(dataType, allocations) {
    let { size, dynamic } = abiSizeAndAllocate(dataType, null, allocations);
    //the above line should work fine... as long as allocation is already done!
    //the middle argument, userDefinedTypes, is only needed during allocation
    //again, this function is only for use if allocation is done, so it's safe to pass null here
    return { size, dynamic };
}
exports.abiSizeInfo = abiSizeInfo;
//allocates an external call
//NOTE: returns just a single allocation; assumes primary allocation is already complete!
//NOTE: returns undefined if attempting to allocate a constructor but we don't have the
//bytecode for the constructor
function allocateCalldataAndReturndata(abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler, constructorContext, deployedContext) {
    //first: determine the corresponding function node
    //(simultaneously: determine the offset)
    let node = undefined;
    let inputParametersFull;
    let outputParametersFull;
    let inputParametersAbi;
    let outputParametersAbi;
    let offset; //refers to INPUT offset; output offset is always 0
    switch (abiEntry.type) {
        case "constructor":
            if (!constructorContext) {
                return undefined;
            }
            let rawLength = constructorContext.binary.length;
            offset = (rawLength - 2) / 2; //number of bytes in 0x-prefixed bytestring
            //for a constructor, we only want to search the particular contract
            if (contractNode) {
                node = contractNode.nodes.find(functionNode => AbiDataUtils.definitionMatchesAbi(
                //note this needn't actually be a function node, but then it will
                //return false (well, unless it's a getter node!)
                abiEntry, functionNode, referenceDeclarations));
            }
            //if we can't find it, we'll handle this below
            break;
        case "function":
            offset = Evm.Utils.SELECTOR_SIZE;
            //search through base contracts, from most derived (left) to most base (right)
            if (contractNode) {
                const linearizedBaseContracts = contractNode.linearizedBaseContracts;
                debug("linearized: %O", linearizedBaseContracts);
                node = findNodeAndContract(linearizedBaseContracts, referenceDeclarations, functionNode => AbiDataUtils.definitionMatchesAbi(abiEntry, functionNode, referenceDeclarations), contractNode).node; //may be undefined!  that's OK!
            }
            break;
    }
    //now: get the parameters (both full-mode & ABI)
    if (node) {
        switch (node.nodeType) {
            case "FunctionDefinition":
                //normal case
                inputParametersFull = node.parameters.parameters;
                outputParametersFull = node.returnParameters.parameters; //this exists even for constructors!
                break;
            case "VariableDeclaration":
                //getter case
                ({
                    inputs: inputParametersFull,
                    outputs: outputParametersFull
                } = Ast.Utils.getterParameters(node, referenceDeclarations));
                break;
        }
    }
    else {
        inputParametersFull = undefined;
        outputParametersFull = undefined;
    }
    inputParametersAbi = abiEntry.inputs;
    switch (abiEntry.type) {
        case "function":
            outputParametersAbi = abiEntry.outputs;
            break;
        case "constructor":
            //we just leave this empty for constructors
            outputParametersAbi = [];
            break;
    }
    //now: do the allocation!
    let { allocation: abiAllocationInput, mode: inputMode } = allocateDataArguments(inputParametersFull, inputParametersAbi, userDefinedTypes, abiAllocations, compilationId, compiler, offset);
    let { allocation: abiAllocationOutput, mode: outputMode } = allocateDataArguments(outputParametersFull, outputParametersAbi, userDefinedTypes, abiAllocations, compilationId, compiler
    //note no offset
    );
    //finally: transform the allocation appropriately
    let inputArgumentsAllocation = abiAllocationInput.members.map(member => (Object.assign(Object.assign({}, member), { pointer: {
            location: "calldata",
            start: member.pointer.start,
            length: member.pointer.length
        } })));
    let outputArgumentsAllocation = abiAllocationOutput.members.map(member => (Object.assign(Object.assign({}, member), { pointer: {
            location: "returndata",
            start: member.pointer.start,
            length: member.pointer.length
        } })));
    let inputsAllocation = {
        abi: abiEntry,
        offset,
        arguments: inputArgumentsAllocation,
        allocationMode: inputMode
    };
    let outputsAllocation;
    switch (abiEntry.type) {
        case "function":
            outputsAllocation = {
                selector: new Uint8Array(),
                arguments: outputArgumentsAllocation,
                allocationMode: outputMode,
                kind: "return"
            };
            break;
        case "constructor":
            outputsAllocation = constructorOutputAllocation(deployedContext, contractNode, referenceDeclarations, outputMode);
            break;
    }
    return { input: inputsAllocation, output: outputsAllocation };
}
//note: allocateEvent doesn't use this because it needs additional
//handling for indexed parameters (maybe these can be unified in
//the future though?)
function allocateDataArguments(fullModeParameters, abiParameters, userDefinedTypes, abiAllocations, compilationId, compiler, offset = 0) {
    let allocationMode = fullModeParameters ? "full" : "abi"; //can degrade
    let parameterTypes;
    let abiAllocation;
    if (allocationMode === "full") {
        let id = "-1"; //fake ID that doesn't matter
        parameterTypes = fullModeParameters.map(parameter => ({
            name: parameter.name,
            type: Ast.Import.definitionToType(parameter, compilationId, compiler) //if node is defined, compiler had also better be!
        }));
        debug("parameterTypes: %O", parameterTypes);
        //now: perform the allocation!
        try {
            abiAllocation = allocateMembers(id, parameterTypes, userDefinedTypes, abiAllocations, offset)[id];
        }
        catch (_a) {
            //if something goes wrong, switch to ABI mdoe
            allocationMode = "abi";
        }
    }
    if (allocationMode === "abi") {
        //THIS IS DELIBERATELY NOT AN ELSE
        //this is the ABI case.  we end up here EITHER
        //if node doesn't exist, OR if something went wrong
        //during allocation
        let id = "-1"; //fake irrelevant ID
        parameterTypes = abiParameters.map(parameter => ({
            name: parameter.name,
            type: Import.abiParameterToType(parameter)
        }));
        abiAllocation = allocateMembers(id, parameterTypes, userDefinedTypes, abiAllocations, offset)[id];
    }
    return { allocation: abiAllocation, mode: allocationMode };
}
//allocates an event
//NOTE: returns just a single allocation; assumes primary allocation is already complete!
function allocateEvent(abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler) {
    let parameterTypes;
    let id;
    //first: determine the corresponding event node
    //search through base contracts, from most derived (right) to most base (left)
    let node = undefined;
    let definedIn = undefined;
    let allocationMode = "full"; //degrade to abi as needed
    debug("allocating ABI: %O", abiEntry);
    if (contractNode) {
        //first: check same contract for the event
        node = contractNode.nodes.find(eventNode => AbiDataUtils.definitionMatchesAbi(
        //note this needn't actually be an event node, but then it will
        //return false
        abiEntry, eventNode, referenceDeclarations));
        //if we found the node, great!  If not...
        if (!node) {
            debug("didn't find node in base contract...");
            //let's search for the node among the base contracts.
            //but if we find it...
            //[note: the following code is overcomplicated; it was used
            //when we were trying to get the actual node, it's overcomplicated
            //now that we're just determining its presence.  oh well]
            let linearizedBaseContractsMinusSelf = contractNode.linearizedBaseContracts.slice();
            linearizedBaseContractsMinusSelf.shift(); //remove self
            debug("checking contracts: %o", linearizedBaseContractsMinusSelf);
            node = findNodeAndContract(linearizedBaseContractsMinusSelf, referenceDeclarations, eventNode => AbiDataUtils.definitionMatchesAbi(
            //note this needn't actually be a event node, but then it will return false
            abiEntry, eventNode, referenceDeclarations)
            //don't pass deriveContractNode here, we're not checking the contract itself
            ).node; //may be undefined! that's OK!
            if (node) {
                //...if we find the node in an ancestor, we
                //deliberately *don't* allocate!  instead such cases
                //will be handled during a later combination step
                debug("bailing out for later handling!");
                debug("ABI: %O", abiEntry);
                return undefined;
            }
        }
    }
    //otherwise, leave node undefined
    if (node) {
        debug("found node");
        //if we found the node, let's also turn it into a type
        definedIn = (Ast.Import.definitionToStoredType(contractNode, compilationId, compiler)); //can skip reference declarations argument here
    }
    else {
        //if no node, have to fall back into ABI mode
        debug("falling back to ABI because no node");
        allocationMode = "abi";
    }
    //now: construct the list of parameter types, attaching indexedness info
    //and overall position (for later reconstruction)
    let indexed;
    let nonIndexed;
    let abiAllocation; //the untransformed allocation for the non-indexed parameters
    if (allocationMode === "full") {
        let id = node.id.toString();
        let parameters = node.parameters.parameters;
        parameterTypes = parameters.map(definition => ({
            //note: if node is defined, compiler had better be defined, too!
            type: Ast.Import.definitionToType(definition, compilationId, compiler),
            name: definition.name,
            indexed: definition.indexed
        }));
        //now: split the list of parameters into indexed and non-indexed
        [indexed, nonIndexed] = lodash_partition_1.default(parameterTypes, (parameter) => parameter.indexed);
        try {
            //now: perform the allocation for the non-indexed parameters!
            abiAllocation = allocateMembers(id, nonIndexed, userDefinedTypes, abiAllocations)[id]; //note the implicit conversion from EventParameterInfo to NameTypePair
        }
        catch (_a) {
            allocationMode = "abi";
        }
    }
    if (allocationMode === "abi") {
        //THIS IS DELIBERATELY NOT AN ELSE
        id = "-1"; //fake irrelevant ID
        parameterTypes = abiEntry.inputs.map(abiParameter => ({
            type: Import.abiParameterToType(abiParameter),
            name: abiParameter.name,
            indexed: abiParameter.indexed
        }));
        //now: split the list of parameters into indexed and non-indexed
        [indexed, nonIndexed] = lodash_partition_1.default(parameterTypes, (parameter) => parameter.indexed);
        //now: perform the allocation for the non-indexed parameters!
        abiAllocation = allocateMembers(id, nonIndexed, userDefinedTypes, abiAllocations)[id]; //note the implicit conversion from EventParameterInfo to NameTypePair
    }
    //now: transform the result appropriately
    const nonIndexedArgumentsAllocation = abiAllocation.members.map(member => (Object.assign(Object.assign({}, member), { pointer: {
            location: "eventdata",
            start: member.pointer.start,
            length: member.pointer.length
        } })));
    //now: allocate the indexed parameters
    const startingTopic = abiEntry.anonymous ? 0 : 1; //if not anonymous, selector takes up topic 0
    const indexedArgumentsAllocation = indexed.map(({ type, name }, position) => ({
        type,
        name,
        pointer: {
            location: "eventtopic",
            topic: startingTopic + position
        }
    }));
    //finally: weave these back together
    let argumentsAllocation = [];
    for (let parameter of parameterTypes) {
        let arrayToGrabFrom = parameter.indexed
            ? indexedArgumentsAllocation
            : nonIndexedArgumentsAllocation;
        argumentsAllocation.push(arrayToGrabFrom.shift()); //note that push and shift both modify!
    }
    //...and return
    return {
        abi: abiEntry,
        contextHash: undefined,
        definedIn,
        arguments: argumentsAllocation,
        allocationMode,
        anonymous: abiEntry.anonymous
    };
}
function getCalldataAllocationsForContract(abi, contractNode, constructorContext, deployedContext, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler) {
    let allocations = {
        constructorAllocation: undefined,
        //(if it doesn't then it will remain as default)
        functionAllocations: {}
    };
    if (!abi) {
        //if no ABI, can't do much!
        allocations.constructorAllocation = defaultConstructorAllocation(constructorContext, contractNode, referenceDeclarations, deployedContext);
        return allocations;
    }
    for (let abiEntry of abi) {
        if (AbiDataUtils.abiEntryIsObviouslyIllTyped(abiEntry) ||
            AbiDataUtils.abiEntryHasStorageParameters(abiEntry)) {
            //the first of these conditions is a hack workaround for a Solidity bug.
            //the second of these is because... seriously? we're not handling these
            //(at least not for now!) (these only exist prior to Solidity 0.5.6,
            //thankfully)
            continue;
        }
        switch (abiEntry.type) {
            case "constructor":
                allocations.constructorAllocation = allocateCalldataAndReturndata(abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler, constructorContext, deployedContext);
                debug("constructor alloc: %O", allocations.constructorAllocation);
                break;
            case "function":
                allocations.functionAllocations[AbiDataUtils.abiSelector(abiEntry)] = allocateCalldataAndReturndata(abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler, constructorContext, deployedContext);
                break;
            default:
                //skip over fallback and event
                break;
        }
    }
    if (!allocations.constructorAllocation) {
        //set a default constructor allocation if we haven't allocated one yet
        allocations.constructorAllocation = defaultConstructorAllocation(constructorContext, contractNode, referenceDeclarations, deployedContext);
        debug("default constructor alloc: %O", allocations.constructorAllocation);
    }
    return allocations;
}
function defaultConstructorAllocation(constructorContext, contractNode, referenceDeclarations, deployedContext) {
    if (!constructorContext) {
        return undefined;
    }
    const rawLength = constructorContext.binary.length;
    const offset = (rawLength - 2) / 2; //number of bytes in 0x-prefixed bytestring
    const input = {
        offset,
        abi: AbiDataUtils.DEFAULT_CONSTRUCTOR_ABI,
        arguments: [],
        allocationMode: "full"
    };
    const output = constructorOutputAllocation(deployedContext, contractNode, referenceDeclarations, "full"); //assume full, degrade as necessary
    return { input, output };
}
//note: context should be deployed context!
function constructorOutputAllocation(context, contractNode, referenceDeclarations, allocationMode) {
    if (!context) {
        //just return a default abi mode result
        return {
            selector: new Uint8Array(),
            allocationMode: "abi",
            kind: "bytecode",
            delegatecallGuard: false
        };
    }
    const { immutableReferences, compilationId, compiler, contractKind, binary } = context;
    let immutables;
    if (allocationMode === "full" && immutableReferences) {
        if (contractNode) {
            debug("allocating immutables");
            immutables = [];
            for (const [id, references] of Object.entries(immutableReferences)) {
                if (references.length === 0) {
                    continue; //don't allocate immutables that don't exist
                }
                const astId = parseInt(id);
                //get the corresponding variable node; potentially fail
                const { node: definition, contract: definedIn } = findNodeAndContract(contractNode.linearizedBaseContracts, referenceDeclarations, node => node.id === astId, contractNode);
                if (!definition || definition.nodeType !== "VariableDeclaration") {
                    debug("didn't find definition for %d!", astId);
                    allocationMode = "abi";
                    immutables = undefined;
                    break;
                }
                const definedInClass = (Ast.Import.definitionToStoredType(definedIn, compilationId, compiler)); //can skip reference declarations argument here
                const dataType = Ast.Import.definitionToType(definition, compilationId, compiler);
                immutables.push({
                    name: definition.name,
                    definedIn: definedInClass,
                    type: dataType,
                    pointer: {
                        location: "returndata",
                        start: references[0].start,
                        length: references[0].length
                    }
                });
            }
        }
        else if (Object.entries(immutableReferences).length > 0) {
            //if there are immutables, but no contract mode, go to abi mode
            debug("immutables but no node!");
            allocationMode = "abi";
        }
    }
    else {
        debug("no immutables");
    }
    //now, is there a delegatecall guard?
    let delegatecallGuard = false;
    if (contractKind === "library") {
        //note: I am relying on this being present!
        //(also this part is a bit HACKy)
        const pushAddressInstruction = (0x60 + Evm.Utils.ADDRESS_SIZE - 1).toString(16); //"73"
        const delegateCallGuardString = "0x" + pushAddressInstruction + "..".repeat(Evm.Utils.ADDRESS_SIZE);
        if (binary.startsWith(delegateCallGuardString)) {
            delegatecallGuard = true;
        }
    }
    return {
        selector: new Uint8Array(),
        allocationMode,
        kind: "bytecode",
        immutables,
        delegatecallGuard
    };
}
function getCalldataAllocations(contracts, referenceDeclarations, userDefinedTypes, abiAllocations) {
    let allocations = {
        constructorAllocations: {},
        functionAllocations: {}
    };
    for (let contract of contracts) {
        const contractAllocations = getCalldataAllocationsForContract(contract.abi, contract.contractNode, contract.constructorContext, contract.deployedContext, referenceDeclarations[contract.compilationId], userDefinedTypes, abiAllocations, contract.compilationId, contract.compiler);
        if (contract.constructorContext) {
            allocations.constructorAllocations[contract.constructorContext.context] =
                contractAllocations.constructorAllocation;
        }
        if (contract.deployedContext) {
            allocations.functionAllocations[contract.deployedContext.context] =
                contractAllocations.functionAllocations;
            //set this up under both constructor *and* deployed! this is to handle
            //constructor returndata decoding
            allocations.constructorAllocations[contract.deployedContext.context] =
                contractAllocations.constructorAllocation;
        }
    }
    return allocations;
}
exports.getCalldataAllocations = getCalldataAllocations;
function getEventAllocationsForContract(abi, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler) {
    return abi
        .filter((abiEntry) => abiEntry.type === "event")
        .filter((abiEntry) => !AbiDataUtils.abiEntryIsObviouslyIllTyped(abiEntry)) //hack workaround
        .map((abiEntry) => ({
        selector: AbiDataUtils.abiSelector(abiEntry),
        anonymous: abiEntry.anonymous,
        topics: AbiDataUtils.topicsCount(abiEntry),
        allocation: allocateEvent(abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler)
    }));
    //note we do *not* filter out undefined allocations; we need these as placeholders
}
//note: constructor context is ignored by this function; no need to pass it in
//WARNING: this function is full of hacks... sorry
function getEventAllocations(contracts, referenceDeclarations, userDefinedTypes, abiAllocations) {
    //first: do allocations for individual contracts
    let individualAllocations = {};
    let groupedAllocations = {};
    let allocations = {};
    for (let { abi, deployedContext, contractNode, compilationId, compiler } of contracts) {
        if (!deployedContext && !contractNode) {
            //we'll need *one* of these two at least
            continue;
        }
        let contractAllocations = getEventAllocationsForContract(abi, contractNode, referenceDeclarations[compilationId], userDefinedTypes, abiAllocations, compilationId, compiler);
        let key = makeContractKey(deployedContext, contractNode ? contractNode.id : undefined, compilationId);
        if (individualAllocations[key] === undefined) {
            individualAllocations[key] = {};
        }
        for (let allocationTemporary of contractAllocations) {
            //we'll use selector *even for anonymous* here, because it's just
            //for determining what overrides what at this point
            individualAllocations[key][allocationTemporary.selector] = {
                context: deployedContext,
                contractNode,
                allocationTemporary,
                compilationId
            };
        }
    }
    //now: put things together for inheritance
    //note how we always put things in order from most derived to most base
    for (let contextOrId in individualAllocations) {
        groupedAllocations[contextOrId] = {};
        for (let selector in individualAllocations[contextOrId]) {
            let { context, contractNode, allocationTemporary, compilationId } = individualAllocations[contextOrId][selector];
            debug("allocationTemporary: %O", allocationTemporary);
            let allocationsTemporary = allocationTemporary.allocation
                ? [allocationTemporary]
                : []; //filter out undefined allocations
            //first, copy from individual allocations
            groupedAllocations[contextOrId][selector] = {
                context,
                contractNode,
                allocationsTemporary
            };
            //if no contract node, that's all.  if there is...
            if (contractNode) {
                //...we have to do inheritance processing
                debug("contract Id: %d", contractNode.id);
                debug("base contracts: %o", contractNode.linearizedBaseContracts);
                let linearizedBaseContractsMinusSelf = contractNode.linearizedBaseContracts.slice();
                linearizedBaseContractsMinusSelf.shift(); //remove contract itself; only want ancestors
                for (let baseId of linearizedBaseContractsMinusSelf) {
                    debug("checking baseId: %d", baseId);
                    let baseNode = referenceDeclarations[compilationId][baseId];
                    if (!baseNode || baseNode.nodeType !== "ContractDefinition") {
                        debug("failed to find node for baseId: %d", baseId);
                        break; //not a continue!
                        //if we can't find the base node, it's better to stop the loop,
                        //rather than continue to potentially erroneous things
                    }
                    //note: we're not actually going to *use* the baseNode here.
                    //we're just checking for whether we can *find* it
                    //why? because if we couldn't find it, that means that events defined in
                    //base contracts *weren't* skipped earlier, and so we shouldn't now add them in
                    let baseContractInfo = contracts.find(contractAllocationInfo => contractAllocationInfo.compilationId === compilationId &&
                        contractAllocationInfo.contractNode &&
                        contractAllocationInfo.contractNode.id === baseId);
                    if (!baseContractInfo) {
                        //similar to above... this failure case can happen when there are
                        //two contracts with the same name and you attempt to use the
                        //artifacts; say you have contracts A, B, and B', where A inherits
                        //from B, and B and B' have the same name, and B' is the one that
                        //gets the artifact; B will end up in reference declarations and so
                        //get found above, but it won't appear in contracts, causing the
                        //problem here.  Unfortunately I don't know any great way to handle this,
                        //so, uh, we treat it as a failure same as above.
                        debug("failed to find contract info for baseId: %d", baseId);
                        break;
                    }
                    let baseContext = baseContractInfo.deployedContext;
                    let baseKey = makeContractKey(baseContext, baseId, compilationId);
                    if (individualAllocations[baseKey][selector] !== undefined) {
                        let baseAllocation = individualAllocations[baseKey][selector].allocationTemporary;
                        debug("(probably) pushing inherited alloc from baseId: %d", baseId);
                        if (baseAllocation.allocation) {
                            //don't push undefined!
                            groupedAllocations[contextOrId][selector].allocationsTemporary.push(baseAllocation);
                        }
                    }
                }
            }
        }
    }
    //finally: transform into final form & return,
    //filtering out things w/o a context
    for (let contractKey in groupedAllocations) {
        if (!hasContext(contractKey)) {
            continue;
            //(this filters out ones that had no context and therefore were
            //given by ID; we needed these at the previous stage but from
            //here on they're irrelevant)
        }
        let contextHash = contextHashForKey(contractKey);
        for (let selector in groupedAllocations[contextHash]) {
            let { allocationsTemporary, context } = groupedAllocations[contextHash][selector];
            for (let { anonymous, topics, allocation } of allocationsTemporary) {
                let contractKind = context.contractKind; //HACK: this is the wrong context, but libraries can't inherit, so it's OK
                if (contractKind !== "library") {
                    contractKind = "contract"; //round off interfaces to being contracts for our purposes :P
                }
                allocation = Object.assign(Object.assign({}, allocation), { contextHash }); //the allocation's context hash at this point depends on where it was defined, but
                //that's not what we want going in the final allocation table!
                if (allocations[topics] === undefined) {
                    allocations[topics] = {
                        bySelector: {},
                        anonymous: { contract: {}, library: {} }
                    };
                }
                if (!anonymous) {
                    if (allocations[topics].bySelector[selector] === undefined) {
                        allocations[topics].bySelector[selector] = {
                            contract: {},
                            library: {}
                        };
                    }
                    if (allocations[topics].bySelector[selector][contractKind][contextHash] === undefined) {
                        allocations[topics].bySelector[selector][contractKind][contextHash] = [];
                    }
                    allocations[topics].bySelector[selector][contractKind][contextHash].push(allocation);
                }
                else {
                    if (allocations[topics].anonymous[contractKind][contextHash] ===
                        undefined) {
                        allocations[topics].anonymous[contractKind][contextHash] = [];
                    }
                    allocations[topics].anonymous[contractKind][contextHash].push(allocation);
                }
            }
        }
    }
    return allocations;
}
exports.getEventAllocations = getEventAllocations;
//if derivedContractNode is passed, we check that before referenceDeclarations
function findNodeAndContract(linearizedBaseContracts, referenceDeclarations, condition, derivedContractNode) {
    const searchResult = linearizedBaseContracts.reduce((foundNodeAndContract, baseContractId) => {
        if (foundNodeAndContract !== undefined) {
            return foundNodeAndContract; //once we've found something, we don't need to keep looking
        }
        debug("searching contract %d", baseContractId);
        let baseContractNode = derivedContractNode && baseContractId === derivedContractNode.id
            ? derivedContractNode //skip the lookup if we already have the right node! this is to reduce errors from collision
            : referenceDeclarations[baseContractId];
        if (baseContractNode === undefined ||
            baseContractNode.nodeType !== "ContractDefinition") {
            debug("bad contract node!");
            return null; //return null rather than undefined so that this will propagate through
            //(i.e. by returning null here we give up the search)
            //(we don't want to continue due to possibility of grabbing the wrong override)
        }
        const node = baseContractNode.nodes.find(condition); //may be undefined! that's OK!
        if (node) {
            debug("found node: %o", node);
            return {
                node,
                contract: baseContractNode
            };
        }
        else {
            return undefined;
        }
    }, undefined //start with no node found
    );
    return searchResult || { node: undefined, contract: undefined };
}
function makeContractKey(context, id, compilationId) {
    return context ? context.context : id + ":" + compilationId; //HACK!
}
function hasContext(key) {
    return key.startsWith("0x"); //HACK!
}
function contextHashForKey(key) {
    return hasContext(key)
        ? key //HACK!
        : undefined;
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 607343:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeAbiReferenceStatic = exports.decodeAbiReferenceByAddress = exports.decodeAbi = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abi-data:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Format = __importStar(__webpack_require__(429965));
const Evm = __importStar(__webpack_require__(149218));
const allocate_1 = __webpack_require__(151325);
const errors_1 = __webpack_require__(672325);
function* decodeAbi(dataType, pointer, info, options = {}) {
    if (Format.Types.isReferenceType(dataType) ||
        dataType.typeClass === "tuple") {
        //I don't want tuples to be considered a reference type, but it makes sense
        //to group them for this purpose
        let dynamic;
        try {
            dynamic = allocate_1.abiSizeInfo(dataType, info.allocations.abi).dynamic;
        }
        catch (error) {
            return errors_1.handleDecodingError(dataType, error, options.strictAbiMode);
        }
        if (dynamic) {
            return yield* decodeAbiReferenceByAddress(dataType, pointer, info, options);
        }
        else {
            return yield* decodeAbiReferenceStatic(dataType, pointer, info, options);
        }
    }
    else {
        debug("pointer %o", pointer);
        return yield* Basic.Decode.decodeBasic(dataType, pointer, info, options);
    }
}
exports.decodeAbi = decodeAbi;
function* decodeAbiReferenceByAddress(dataType, pointer, info, options = {}) {
    let { strictAbiMode: strict, abiPointerBase: base, lengthOverride } = options;
    base = base || 0; //in case base was undefined
    const { allocations: { abi: allocations }, state } = info;
    debug("pointer %o", pointer);
    //this variable holds the location we should look to *next*
    //stack pointers point to calldata; other pointers point to same location
    const location = pointer.location === "stack" || pointer.location === "stackliteral"
        ? "calldata"
        : pointer.location;
    if (pointer.location !== "stack" && pointer.location !== "stackliteral") {
        //length overrides are only applicable when you're decoding a pointer
        //from the stack!  otherwise they must be ignored!
        lengthOverride = undefined;
    }
    let rawValue;
    try {
        rawValue = yield* read_1.default(pointer, state);
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error, strict);
    }
    let rawValueAsBN = Conversion.toBN(rawValue);
    debug("rawValue: %O", rawValue);
    debug("rawValueAsBN: %O", rawValueAsBN);
    let rawValueAsNumber;
    try {
        rawValueAsNumber = rawValueAsBN.toNumber();
    }
    catch (_a) {
        let error = {
            kind: "OverlargePointersNotImplementedError",
            pointerAsBN: rawValueAsBN
        };
        if (strict) {
            throw new errors_1.StopDecodingError(error);
        }
        return {
            //again with the TS failures...
            type: dataType,
            kind: "error",
            error
        };
    }
    let startPosition = rawValueAsNumber + base;
    debug("startPosition %d", startPosition);
    let dynamic;
    let size;
    try {
        ({ dynamic, size } = allocate_1.abiSizeInfo(dataType, allocations));
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error, strict);
    }
    if (!dynamic) {
        //this will only come up when called from stack.ts
        let staticPointer = {
            location,
            start: startPosition,
            length: size
        };
        return yield* decodeAbiReferenceStatic(dataType, staticPointer, info, options);
    }
    let length;
    let lengthAsBN;
    let rawLength;
    switch (dataType.typeClass) {
        case "bytes":
        case "string":
            //initial word contains length (unless an override was given)
            if (lengthOverride !== undefined) {
                lengthAsBN = lengthOverride;
                //note in this case we do *not* increment start position;
                //if a length override is given, that means the given start
                //position skips over the length word!
            }
            else {
                try {
                    rawLength = yield* read_1.default({
                        location,
                        start: startPosition,
                        length: Evm.Utils.WORD_SIZE
                    }, state);
                }
                catch (error) {
                    return errors_1.handleDecodingError(dataType, error, strict);
                }
                lengthAsBN = Conversion.toBN(rawLength);
                startPosition += Evm.Utils.WORD_SIZE; //increment start position after reading length
                //so it'll be set up to read the data
            }
            if (strict && lengthAsBN.gtn(state[location].length)) {
                //you may notice that the comparison is a bit crude; that's OK, this is
                //just to prevent huge numbers from DOSing us, other errors will still
                //be caught regardless
                throw new errors_1.StopDecodingError({
                    kind: "OverlongArrayOrStringStrictModeError",
                    lengthAsBN,
                    dataLength: state[location].length
                });
            }
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_b) {
                //note: if we're in this situation, we can assume we're not in strict mode,
                //as the strict case was handled above
                return {
                    //again with the TS failures...
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "OverlongArraysAndStringsNotImplementedError",
                        lengthAsBN
                    }
                };
            }
            let childPointer = {
                location,
                start: startPosition,
                length
            };
            return yield* Bytes.Decode.decodeBytes(dataType, childPointer, info, options);
        case "array":
            if (dataType.kind === "static") {
                //static-length array
                lengthAsBN = dataType.length;
                //note we don't increment start position; static arrays don't
                //include a length word!
            }
            else if (lengthOverride !== undefined) {
                debug("override: %o", lengthOverride);
                //dynamic-length array, but with length override
                lengthAsBN = lengthOverride;
                //we don't increment start position; if a length override was
                //given, that means the pointer skipped the length word!
            }
            else {
                //dynamic-length array, read length from data
                //initial word contains array length
                try {
                    rawLength = yield* read_1.default({
                        location,
                        start: startPosition,
                        length: Evm.Utils.WORD_SIZE
                    }, state);
                }
                catch (error) {
                    return errors_1.handleDecodingError(dataType, error, strict);
                }
                lengthAsBN = Conversion.toBN(rawLength);
                startPosition += Evm.Utils.WORD_SIZE; //increment startPosition
                //to next word, as first word was used for length
            }
            if (strict && lengthAsBN.gtn(state[location].length)) {
                //you may notice that the comparison is a bit crude; that's OK, this is
                //just to prevent huge numbers from DOSing us, other errors will still
                //be caught regardless
                throw new errors_1.StopDecodingError({
                    kind: "OverlongArraysAndStringsNotImplementedError",
                    lengthAsBN,
                    dataLength: state[location].length
                });
            }
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_c) {
                //again, if we get here, we can assume we're not in strict mode
                return {
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "OverlongArraysAndStringsNotImplementedError",
                        lengthAsBN
                    }
                };
            }
            //note: I've written this fairly generically, but it is worth noting that
            //since this array is of dynamic type, we know that if it's static length
            //then size must be EVM.WORD_SIZE
            let baseSize;
            try {
                baseSize = allocate_1.abiSizeInfo(dataType.baseType, allocations).size;
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error, strict);
            }
            let decodedChildren = [];
            for (let index = 0; index < length; index++) {
                decodedChildren.push(yield* decodeAbi(dataType.baseType, {
                    location,
                    start: startPosition + index * baseSize,
                    length: baseSize
                }, info, Object.assign(Object.assign({}, options), { abiPointerBase: startPosition }))); //pointer base is always start of list, never the length
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedChildren
            };
        case "struct":
            return yield* decodeAbiStructByPosition(dataType, location, startPosition, info, options);
        case "tuple":
            return yield* decodeAbiTupleByPosition(dataType, location, startPosition, info, options);
    }
}
exports.decodeAbiReferenceByAddress = decodeAbiReferenceByAddress;
function* decodeAbiReferenceStatic(dataType, pointer, info, options = {}) {
    debug("static");
    debug("pointer %o", pointer);
    const location = pointer.location;
    switch (dataType.typeClass) {
        case "array":
            //we're in the static case, so we know the array must be statically sized
            const lengthAsBN = dataType.length;
            let length;
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_a) {
                //note: since this is the static case, we don't bother including the stronger
                //strict-mode guard against getting DOSed by large array sizes, since in this
                //case we're not reading the size from the input; if there's a huge static size
                //array, well, we'll just have to deal with it
                let error = {
                    kind: "OverlongArraysAndStringsNotImplementedError",
                    lengthAsBN
                };
                if (options.strictAbiMode) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            let baseSize;
            try {
                baseSize = allocate_1.abiSizeInfo(dataType.baseType, info.allocations.abi).size;
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error, options.strictAbiMode);
            }
            let decodedChildren = [];
            for (let index = 0; index < length; index++) {
                decodedChildren.push(yield* decodeAbi(dataType.baseType, {
                    location,
                    start: pointer.start + index * baseSize,
                    length: baseSize
                }, info, options));
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedChildren
            };
        case "struct":
            return yield* decodeAbiStructByPosition(dataType, location, pointer.start, info, options);
        case "tuple":
            return yield* decodeAbiTupleByPosition(dataType, location, pointer.start, info, options);
    }
}
exports.decodeAbiReferenceStatic = decodeAbiReferenceStatic;
//note that this function takes the start position as a *number*; it does not take a pointer
function* decodeAbiStructByPosition(dataType, location, startPosition, info, options = {}) {
    const { allocations: { abi: allocations } } = info;
    const typeLocation = location === "calldata" ? "calldata" : null; //other abi locations are not valid type locations
    const typeId = dataType.id;
    const structAllocation = allocations[typeId];
    if (!structAllocation) {
        let error = {
            kind: "UserDefinedTypeNotFoundError",
            type: dataType
        };
        if (options.strictAbiMode || options.allowRetry) {
            throw new errors_1.StopDecodingError(error, true);
            //note that we allow a retry if we couldn't locate the allocation!
        }
        return {
            type: dataType,
            kind: "error",
            error
        };
    }
    let decodedMembers = [];
    for (let index = 0; index < structAllocation.members.length; index++) {
        const memberAllocation = structAllocation.members[index];
        const memberPointer = memberAllocation.pointer;
        const childPointer = {
            location,
            start: startPosition + memberPointer.start,
            length: memberPointer.length
        };
        let memberName = memberAllocation.name;
        let memberType = Format.Types.specifyLocation(memberAllocation.type, typeLocation);
        decodedMembers.push({
            name: memberName,
            value: yield* decodeAbi(memberType, childPointer, info, Object.assign(Object.assign({}, options), { abiPointerBase: startPosition }))
            //note that the base option is only needed in the dynamic case, but we're being indiscriminate
        });
    }
    return {
        type: dataType,
        kind: "value",
        value: decodedMembers
    };
}
//note that this function takes the start position as a *number*; it does not take a pointer
function* decodeAbiTupleByPosition(dataType, location, startPosition, info, options = {}) {
    //WARNING: This case is written in a way that involves a bunch of unnecessary recomputation!
    //I'm writing it this way anyway for simplicity, to avoid rewriting the decoder
    //However it may be worth revisiting this in the future if performance turns out to be a problem
    //(changing this may be pretty hard though)
    let decodedMembers = [];
    let position = startPosition;
    for (const { name, type: memberType } of dataType.memberTypes) {
        const memberSize = allocate_1.abiSizeInfo(memberType, info.allocations.abi).size;
        const childPointer = {
            location,
            start: position,
            length: memberSize
        };
        decodedMembers.push({
            name,
            value: yield* decodeAbi(memberType, childPointer, info, Object.assign(Object.assign({}, options), { abiPointerBase: startPosition }))
            //note that the base option is only needed in the dynamic case, but we're being indiscriminate
        });
        position += memberSize;
    }
    return {
        type: dataType,
        kind: "value",
        value: decodedMembers
    };
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 554840:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.encodeTupleAbi = exports.encodeAbi = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abi-data:encode");
const Conversion = __importStar(__webpack_require__(152714));
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Evm = __importStar(__webpack_require__(149218));
const allocate_1 = __webpack_require__(151325);
const lodash_sum_1 = __importDefault(__webpack_require__(858364));
//UGH -- it turns out TypeScript can't handle nested tagged unions
//see: https://github.com/microsoft/TypeScript/issues/18758
//so, I'm just going to have to throw in a bunch of type coercions >_>
/**
 * @Category Encoding (low-level)
 */
function encodeAbi(input, allocations) {
    //errors can't be encoded
    if (input.kind === "error") {
        return undefined;
    }
    let bytes;
    //TypeScript can at least infer in the rest of this that we're looking
    //at a value, not an error!  But that's hardly enough...
    switch (input.type.typeClass) {
        case "mapping":
        case "magic":
        case "type":
            //none of these can go in the ABI
            return undefined;
        case "bytes":
            switch (input.type.kind) {
                case "static":
                    return Basic.Encode.encodeBasic(input);
                case "dynamic":
                    bytes = Bytes.Encode.encodeBytes((input));
                    return padAndPrependLength(bytes);
            }
        case "string":
            bytes = Bytes.Encode.encodeBytes(input);
            return padAndPrependLength(bytes);
        case "function": {
            switch (input.type.visibility) {
                case "internal":
                    return undefined; //internal functions can't go in the ABI!
                //Yes, technically we could defer to encodeBasic here, but,
                //c'mon, that's not how the function's supposed to be used
                case "external":
                    return Basic.Encode.encodeBasic(input);
            }
        }
        //now for the serious cases
        case "array": {
            let coercedInput = (input);
            if (coercedInput.reference !== undefined) {
                return undefined; //circular values can't be encoded
            }
            let staticEncoding = encodeTupleAbi(coercedInput.value, allocations);
            switch (input.type.kind) {
                case "static":
                    return staticEncoding;
                case "dynamic":
                    let encoded = new Uint8Array(Evm.Utils.WORD_SIZE + staticEncoding.length); //leave room for length
                    encoded.set(staticEncoding, Evm.Utils.WORD_SIZE); //again, leave room for length beforehand
                    let lengthBytes = Conversion.toBytes(coercedInput.value.length, Evm.Utils.WORD_SIZE);
                    encoded.set(lengthBytes); //and now we set the length
                    return encoded;
            }
        }
        case "struct": {
            let coercedInput = (input);
            if (coercedInput.reference !== undefined) {
                return undefined; //circular values can't be encoded
            }
            return encodeTupleAbi(coercedInput.value.map(({ value }) => value), allocations);
        }
        case "tuple":
            //WARNING: This case is written in a way that involves a bunch of unnecessary recomputation!
            //(That may not be apparent from this one line, but it's true)
            //I'm writing it this way anyway for simplicity, to avoid rewriting the encoder
            //However it may be worth revisiting this in the future if performance turns out to be a problem
            return encodeTupleAbi(input.value.map(({ value }) => value), allocations);
        default:
            return Basic.Encode.encodeBasic(input);
    }
}
exports.encodeAbi = encodeAbi;
/**
 * @Category Encoding (low-level)
 */
function padAndPrependLength(bytes) {
    let length = bytes.length;
    let paddedLength = Evm.Utils.WORD_SIZE * Math.ceil(length / Evm.Utils.WORD_SIZE);
    let encoded = new Uint8Array(Evm.Utils.WORD_SIZE + paddedLength);
    encoded.set(bytes, Evm.Utils.WORD_SIZE); //start 32 in to leave room for the length beforehand
    let lengthBytes = Conversion.toBytes(length, Evm.Utils.WORD_SIZE);
    encoded.set(lengthBytes); //and now we set the length
    return encoded;
}
/**
 * @Category Encoding (low-level)
 */
function encodeTupleAbi(tuple, allocations) {
    let elementEncodings = tuple.map(element => encodeAbi(element, allocations));
    if (elementEncodings.some(element => element === undefined)) {
        return undefined;
    }
    let elementSizeInfo = tuple.map(element => allocate_1.abiSizeInfo(element.type, allocations));
    //heads and tails here are as discussed in the ABI docs;
    //for a static type the head is the encoding and the tail is empty,
    //for a dynamic type the head is the pointer and the tail is the encoding
    let heads = [];
    let tails = [];
    //but first, we need to figure out where the first tail will start,
    //by adding up the sizes of all the heads (we can easily do this in
    //advance via elementSizeInfo, without needing to know the particular
    //values of the heads)
    let startOfNextTail = lodash_sum_1.default(elementSizeInfo.map(elementInfo => elementInfo.size));
    for (let i = 0; i < tuple.length; i++) {
        let head;
        let tail;
        if (!elementSizeInfo[i].dynamic) {
            //static case
            head = elementEncodings[i];
            tail = new Uint8Array(); //empty array
        }
        else {
            //dynamic case
            head = Conversion.toBytes(startOfNextTail, Evm.Utils.WORD_SIZE);
            tail = elementEncodings[i];
        }
        heads.push(head);
        tails.push(tail);
        startOfNextTail += tail.length;
    }
    //finally, we need to concatenate everything together!
    //since we're dealing with Uint8Arrays, we have to do this manually
    let totalSize = startOfNextTail;
    let encoded = new Uint8Array(totalSize);
    let position = 0;
    for (let head of heads) {
        encoded.set(head, position);
        position += head.length;
    }
    for (let tail of tails) {
        encoded.set(tail, position);
        position += tail.length;
    }
    return encoded;
}
exports.encodeTupleAbi = encodeTupleAbi;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 753137:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.abiParameterToType = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abi-data:import");
const bn_js_1 = __importDefault(__webpack_require__(213550));
function abiParameterToType(abi) {
    let typeName = abi.type;
    let typeHint = abi.internalType;
    //first: is it an array?
    let arrayMatch = typeName.match(/(.*)\[(\d*)\]$/);
    if (arrayMatch) {
        let baseTypeName = arrayMatch[1];
        let lengthAsString = arrayMatch[2]; //may be empty!
        let baseAbi = Object.assign(Object.assign({}, abi), { type: baseTypeName });
        let baseType = abiParameterToType(baseAbi);
        if (lengthAsString === "") {
            return {
                typeClass: "array",
                kind: "dynamic",
                baseType,
                typeHint
            };
        }
        else {
            let length = new bn_js_1.default(lengthAsString);
            return {
                typeClass: "array",
                kind: "static",
                length,
                baseType,
                typeHint
            };
        }
    }
    //otherwise, here are the simple cases
    let typeClass = typeName.match(/^([^0-9]+)/)[1];
    switch (typeClass) {
        case "uint":
        case "int": {
            let bits = typeName.match(/^u?int([0-9]+)/)[1];
            return {
                typeClass,
                bits: parseInt(bits),
                typeHint
            };
        }
        case "bytes":
            let length = typeName.match(/^bytes([0-9]*)/)[1];
            if (length === "") {
                return {
                    typeClass,
                    kind: "dynamic",
                    typeHint
                };
            }
            else {
                return {
                    typeClass,
                    kind: "static",
                    length: parseInt(length),
                    typeHint
                };
            }
        case "address":
            return {
                typeClass,
                kind: "general",
                typeHint
            };
        case "string":
        case "bool":
            return {
                typeClass,
                typeHint
            };
        case "fixed":
        case "ufixed": {
            let [_, bits, places] = typeName.match(/^u?fixed([0-9]+)x([0-9]+)/);
            return {
                typeClass,
                bits: parseInt(bits),
                places: parseInt(places),
                typeHint
            };
        }
        case "function":
            return {
                typeClass,
                visibility: "external",
                kind: "general",
                typeHint
            };
        case "tuple":
            let memberTypes = abi.components.map(component => ({
                name: component.name || undefined,
                type: abiParameterToType(component)
            }));
            return {
                typeClass,
                memberTypes,
                typeHint
            };
    }
}
exports.abiParameterToType = abiParameterToType;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 20907:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = exports.Import = exports.Decode = exports.Encode = exports.Allocate = void 0;
const Allocate = __importStar(__webpack_require__(151325));
exports.Allocate = Allocate;
const Encode = __importStar(__webpack_require__(554840));
exports.Encode = Encode;
const Decode = __importStar(__webpack_require__(607343));
exports.Decode = Decode;
const Import = __importStar(__webpack_require__(753137));
exports.Import = Import;
__exportStar(__webpack_require__(526365), exports);
const Utils = __importStar(__webpack_require__(785941));
exports.Utils = Utils;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 526365:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 785941:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.abiEntryHasStorageParameters = exports.abiEntryIsObviouslyIllTyped = exports.topicsCount = exports.definitionMatchesAbi = exports.abisMatch = exports.abiSelector = exports.abiTupleSignature = exports.abiSignature = exports.abiHasPayableFallback = exports.computeSelectors = exports.DEFAULT_CONSTRUCTOR_ABI = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abi-data:utils");
// untyped import since no @types/web3-utils exists
const Web3Utils = __webpack_require__(118269);
const Evm = __importStar(__webpack_require__(149218));
const Ast = __importStar(__webpack_require__(114442));
exports.DEFAULT_CONSTRUCTOR_ABI = {
    type: "constructor",
    inputs: [],
    stateMutability: "nonpayable"
};
//note the return value only includes functions!
function computeSelectors(abi) {
    if (abi === undefined) {
        return undefined;
    }
    return Object.assign({}, ...abi
        .filter((abiEntry) => abiEntry.type === "function")
        .map((abiEntry) => ({
        [abiSelector(abiEntry)]: abiEntry
    })));
}
exports.computeSelectors = computeSelectors;
//does this ABI have a payable fallback (or receive) function?
function abiHasPayableFallback(abi) {
    if (abi === undefined) {
        return undefined;
    }
    return abi.some(abiEntry => (abiEntry.type === "fallback" || abiEntry.type === "receive") &&
        abiEntry.stateMutability === "payable");
}
exports.abiHasPayableFallback = abiHasPayableFallback;
//NOTE: this function returns the written out SIGNATURE, not the SELECTOR
function abiSignature(abiEntry) {
    return abiEntry.name + abiTupleSignature(abiEntry.inputs);
}
exports.abiSignature = abiSignature;
function abiTupleSignature(parameters) {
    let components = parameters.map(abiTypeSignature);
    return "(" + components.join(",") + ")";
}
exports.abiTupleSignature = abiTupleSignature;
function abiTypeSignature(parameter) {
    let tupleMatch = parameter.type.match(/tuple(.*)/);
    if (tupleMatch === null) {
        //does not start with "tuple"
        return parameter.type;
    }
    else {
        let tail = tupleMatch[1]; //everything after "tuple"
        let tupleSignature = abiTupleSignature(parameter.components);
        return tupleSignature + tail;
    }
}
function abiSelector(abiEntry) {
    let signature = abiSignature(abiEntry);
    //NOTE: web3's soliditySha3 has a problem if the empty
    //string is passed in.  Fortunately, that should never happen here.
    let hash = Web3Utils.soliditySha3({ type: "string", value: signature });
    switch (abiEntry.type) {
        case "event":
            return hash;
        case "function":
        case "error":
            return hash.slice(0, 2 + 2 * Evm.Utils.SELECTOR_SIZE); //arithmetic to account for hex string
    }
}
exports.abiSelector = abiSelector;
//note: undefined does not match itself :P
function abisMatch(entry1, entry2) {
    //we'll consider two abi entries to match if they have the same
    //type, name (if applicable), and inputs (if applicable).
    //since there's already a signature function, we can just use that.
    if (!entry1 || !entry2) {
        return false;
    }
    if (entry1.type !== entry2.type) {
        return false;
    }
    switch (entry1.type) {
        case "function":
        case "event":
        case "error":
            return (abiSignature(entry1) ===
                abiSignature(entry2));
        case "constructor":
            return (abiTupleSignature(entry1.inputs) ===
                abiTupleSignature(entry2.inputs));
        case "fallback":
        case "receive":
            return true;
    }
}
exports.abisMatch = abisMatch;
function definitionMatchesAbi(abiEntry, definition, referenceDeclarations) {
    try {
        return abisMatch(abiEntry, Ast.Utils.definitionToAbi(definition, referenceDeclarations));
    }
    catch (_) {
        return false; //if an exception occurs, well, that's not a match!
    }
}
exports.definitionMatchesAbi = definitionMatchesAbi;
function topicsCount(abiEntry) {
    let selectorCount = abiEntry.anonymous ? 0 : 1; //if the event is not anonymous, we must account for the selector
    return (abiEntry.inputs.filter(({ indexed }) => indexed).length + selectorCount);
}
exports.topicsCount = topicsCount;
function abiEntryIsObviouslyIllTyped(abiEntry) {
    switch (abiEntry.type) {
        case "fallback":
        case "receive":
            return false;
        case "constructor":
        case "event":
        case "error":
            return abiEntry.inputs.some(abiParameterIsObviouslyIllTyped);
        case "function":
            return (abiEntry.inputs.some(abiParameterIsObviouslyIllTyped) ||
                abiEntry.outputs.some(abiParameterIsObviouslyIllTyped));
    }
}
exports.abiEntryIsObviouslyIllTyped = abiEntryIsObviouslyIllTyped;
function abiParameterIsObviouslyIllTyped(abiParameter) {
    const legalBaseTypeClasses = [
        "uint",
        "int",
        "fixed",
        "ufixed",
        "bool",
        "address",
        "bytes",
        "string",
        "function",
        "tuple"
    ];
    const baseTypeClass = abiParameter.type.match(/^([a-z]*)/)[1];
    const baseTypeClassIsObviouslyWrong = !legalBaseTypeClasses.includes(baseTypeClass);
    if (abiParameter.components) {
        return (abiParameter.components.some(abiParameterIsObviouslyIllTyped) ||
            baseTypeClassIsObviouslyWrong);
    }
    else {
        return baseTypeClassIsObviouslyWrong;
    }
}
function abiEntryHasStorageParameters(abiEntry) {
    const isStorage = (parameter) => parameter.type.endsWith(" storage");
    return (abiEntry.type === "function" &&
        (abiEntry.inputs.some(isStorage) || abiEntry.outputs.some(isStorage)));
    //Note the lack of recursion!  Storage parameters can only occur at
    //top level so there's no need to recurse here
    //(they can also only occur for functions)
}
exports.abiEntryHasStorageParameters = abiEntryHasStorageParameters;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 57320:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.abifyReturndataDecoding = exports.abifyLogDecoding = exports.abifyCalldataDecoding = exports.abifyResult = exports.abifyType = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:abify");
const Format = __importStar(__webpack_require__(429965));
const Common = __importStar(__webpack_require__(299987));
const Conversion = __importStar(__webpack_require__(152714));
/** @category ABIfication */
function abifyType(dataType, userDefinedTypes) {
    switch (dataType.typeClass) {
        //we only need to specially handle types that don't go in
        //the ABI, or that have some information loss when going
        //in the ABI
        //note that we do need to handle arrays, due to recursion!
        //First: types that do not go in the ABI
        case "mapping":
        case "magic":
            return undefined;
        //Next: address & contract, these can get handled together
        case "address":
        case "contract":
            return {
                typeClass: "address",
                kind: "general",
                typeHint: Format.Types.typeString(dataType)
            };
        case "function":
            switch (dataType.visibility) {
                case "external":
                    return {
                        typeClass: "function",
                        visibility: "external",
                        kind: "general",
                        typeHint: Format.Types.typeString(dataType)
                    };
                case "internal": //these don't go in the ABI
                    return undefined;
            }
            break; //to satisfy TypeScript
        //the complex cases: struct & enum
        case "struct": {
            const fullType = (Format.Types.fullType(dataType, userDefinedTypes));
            if (!fullType) {
                let typeToDisplay = Format.Types.typeString(dataType);
                throw new Common.UnknownUserDefinedTypeError(dataType.id, typeToDisplay);
            }
            const memberTypes = fullType.memberTypes.map(({ name, type: memberType }) => ({
                name,
                type: abifyType(memberType, userDefinedTypes)
            }));
            return {
                typeClass: "tuple",
                typeHint: Format.Types.typeString(fullType),
                memberTypes
            };
        }
        case "enum": {
            const fullType = (Format.Types.fullType(dataType, userDefinedTypes));
            if (!fullType) {
                let typeToDisplay = Format.Types.typeString(dataType);
                throw new Common.UnknownUserDefinedTypeError(dataType.id, typeToDisplay);
            }
            let numOptions = fullType.options.length;
            let bits = 8 * Math.ceil(Math.log2(numOptions) / 8);
            return {
                typeClass: "uint",
                bits,
                typeHint: Format.Types.typeString(fullType)
            };
        }
        //finally: arrays
        case "array":
            return Object.assign(Object.assign({}, dataType), { typeHint: Format.Types.typeString(dataType), baseType: abifyType(dataType.baseType, userDefinedTypes) });
        //default case: just leave as-is
        default:
            return dataType;
    }
}
exports.abifyType = abifyType;
/** @category ABIfication */
function abifyResult(result, userDefinedTypes) {
    switch (result.type.typeClass) {
        case "mapping": //doesn't go in ABI
        case "magic": //doesn't go in ABI
            return undefined;
        case "address":
            //abify the type but leave the value alone
            return Object.assign(Object.assign({}, result), { type: abifyType(result.type, userDefinedTypes) });
        case "contract": {
            let coercedResult = result;
            switch (coercedResult.kind) {
                case "value":
                    return {
                        type: (abifyType(result.type, userDefinedTypes)),
                        kind: "value",
                        value: {
                            asAddress: coercedResult.value.address,
                            rawAsHex: coercedResult.value.rawAddress
                        }
                    };
                case "error":
                    switch (coercedResult.error.kind) {
                        case "ContractPaddingError":
                            return {
                                type: (abifyType(result.type, userDefinedTypes)),
                                kind: "error",
                                error: {
                                    kind: "AddressPaddingError",
                                    paddingType: coercedResult.error.paddingType,
                                    raw: coercedResult.error.raw
                                }
                            };
                        default:
                            //other contract errors are generic errors!
                            //but TS doesn't know this so we coerce
                            return Object.assign(Object.assign({}, coercedResult), { type: (abifyType(result.type, userDefinedTypes)) });
                    }
            }
            break; //to satisfy typescript
        }
        case "function":
            switch (result.type.visibility) {
                case "external": {
                    let coercedResult = result;
                    return Object.assign(Object.assign({}, coercedResult), { type: (abifyType(result.type, userDefinedTypes)) });
                }
                case "internal": //these don't go in the ABI
                    return undefined;
            }
            break; //to satisfy TypeScript
        case "struct": {
            let coercedResult = result;
            switch (coercedResult.kind) {
                case "value":
                    if (coercedResult.reference !== undefined) {
                        return undefined; //no circular values in the ABI!
                    }
                    let abifiedMembers = coercedResult.value.map(({ name, value: member }) => ({
                        name,
                        value: abifyResult(member, userDefinedTypes)
                    }));
                    return {
                        kind: "value",
                        type: (abifyType(result.type, userDefinedTypes)),
                        value: abifiedMembers
                    };
                case "error":
                    return Object.assign(Object.assign({}, coercedResult), { type: (abifyType(result.type, userDefinedTypes)) //note: may throw exception
                     });
            }
        }
        case "enum": {
            //NOTE: this is the one case where errors are converted to non-error values!!
            //(other than recursively, I mean)
            //be aware!
            let coercedResult = result;
            let uintType = (abifyType(result.type, userDefinedTypes)); //may throw exception
            switch (coercedResult.kind) {
                case "value":
                    return {
                        type: uintType,
                        kind: "value",
                        value: {
                            asBN: coercedResult.value.numericAsBN.clone()
                        }
                    };
                case "error":
                    switch (coercedResult.error.kind) {
                        case "EnumOutOfRangeError":
                            return {
                                type: uintType,
                                kind: "value",
                                value: {
                                    asBN: coercedResult.error.rawAsBN.clone()
                                }
                            };
                        case "EnumPaddingError":
                            return {
                                type: uintType,
                                kind: "error",
                                error: {
                                    kind: "UintPaddingError",
                                    paddingType: coercedResult.error.paddingType,
                                    raw: coercedResult.error.raw
                                }
                            };
                        case "EnumNotFoundDecodingError":
                            let numericValue = coercedResult.error.rawAsBN.clone();
                            if (numericValue.bitLength() <= uintType.bits) {
                                return {
                                    type: uintType,
                                    kind: "value",
                                    value: {
                                        asBN: numericValue
                                    }
                                };
                            }
                            else {
                                return {
                                    type: uintType,
                                    kind: "error",
                                    error: {
                                        kind: "UintPaddingError",
                                        paddingType: "left",
                                        raw: Conversion.toHexString(numericValue)
                                    }
                                };
                            }
                        default:
                            return {
                                type: uintType,
                                kind: "error",
                                error: coercedResult.error
                            };
                    }
            }
        }
        case "array": {
            let coercedResult = result;
            switch (coercedResult.kind) {
                case "value":
                    if (coercedResult.reference !== undefined) {
                        return undefined; //no circular values in the ABI!
                    }
                    let abifiedMembers = coercedResult.value.map(member => abifyResult(member, userDefinedTypes));
                    return {
                        kind: "value",
                        type: (abifyType(result.type, userDefinedTypes)),
                        value: abifiedMembers
                    };
                case "error":
                    return Object.assign(Object.assign({}, coercedResult), { type: (abifyType(result.type, userDefinedTypes)) });
            }
        }
        default:
            return result;
    }
}
exports.abifyResult = abifyResult;
/** @category ABIfication */
function abifyCalldataDecoding(decoding, userDefinedTypes) {
    if (decoding.decodingMode === "abi") {
        return decoding;
    }
    switch (decoding.kind) {
        case "function":
        case "constructor":
            return Object.assign(Object.assign({}, decoding), { decodingMode: "abi", arguments: decoding.arguments.map(argument => (Object.assign(Object.assign({}, argument), { value: abifyResult(argument.value, userDefinedTypes) }))) });
        default:
            return Object.assign(Object.assign({}, decoding), { decodingMode: "abi" });
    }
}
exports.abifyCalldataDecoding = abifyCalldataDecoding;
/** @category ABIfication */
function abifyLogDecoding(decoding, userDefinedTypes) {
    if (decoding.decodingMode === "abi") {
        return decoding;
    }
    return Object.assign(Object.assign({}, decoding), { decodingMode: "abi", arguments: decoding.arguments.map(argument => (Object.assign(Object.assign({}, argument), { value: abifyResult(argument.value, userDefinedTypes) }))) });
}
exports.abifyLogDecoding = abifyLogDecoding;
/** @category ABIfication */
function abifyReturndataDecoding(decoding, userDefinedTypes) {
    if (decoding.decodingMode === "abi") {
        return decoding;
    }
    switch (decoding.kind) {
        case "return":
        case "revert":
            return Object.assign(Object.assign({}, decoding), { decodingMode: "abi", arguments: decoding.arguments.map(argument => (Object.assign(Object.assign({}, argument), { value: abifyResult(argument.value, userDefinedTypes) }))) });
        case "bytecode":
            return Object.assign(Object.assign({}, decoding), { decodingMode: "abi", immutables: undefined });
        default:
            return Object.assign(Object.assign({}, decoding), { decodingMode: "abi" });
    }
}
exports.abifyReturndataDecoding = abifyReturndataDecoding;
//# sourceMappingURL=abify.js.map

/***/ }),

/***/ 575511:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeConstant = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:ast:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
function* decodeConstant(dataType, pointer, info) {
    debug("pointer %o", pointer);
    //normally, we just dispatch to decodeBasic or decodeBytes.
    //for statically-sized bytes, however, we need to make a special case.
    //you see, decodeBasic expects to find the bytes at the *beginning*
    //of the word, but readDefinition will put them at the *end* of the
    //word.  So we'll have to adjust things ourselves.
    if (dataType.typeClass === "bytes" && dataType.kind === "static") {
        let size = dataType.length;
        let word;
        try {
            word = yield* read_1.default(pointer, info.state);
        }
        catch (error) {
            return errors_1.handleDecodingError(dataType, error);
        }
        //not bothering to check padding; shouldn't be necessary
        let bytes = word.slice(Evm.Utils.WORD_SIZE - size);
        return {
            type: dataType,
            kind: "value",
            value: {
                asHex: Conversion.toHexString(bytes)
            }
        }; //we'll skip including a raw value, as that would be meaningless
    }
    //otherwise, as mentioned, just dispatch to decodeBasic or decodeBytes
    debug("not a static bytes");
    if (dataType.typeClass === "bytes" || dataType.typeClass === "string") {
        return yield* Bytes.Decode.decodeBytes(dataType, pointer, info);
    }
    return yield* Basic.Decode.decodeBasic(dataType, pointer, info);
}
exports.decodeConstant = decodeConstant;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 488132:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Decode = exports.Read = void 0;
const Read = __importStar(__webpack_require__(538130));
exports.Read = Read;
const Decode = __importStar(__webpack_require__(575511));
exports.Decode = Decode;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 538130:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readDefinition = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:ast:read");
const Conversion = __importStar(__webpack_require__(152714));
const Evm = __importStar(__webpack_require__(149218));
const Ast = __importStar(__webpack_require__(114442));
const errors_1 = __webpack_require__(672325);
function readDefinition(pointer) {
    const definition = pointer.definition;
    debug("definition %o", definition);
    switch (Ast.Utils.typeClass(definition)) {
        case "rational":
            let numericalValue = Ast.Utils.rationalValue(definition);
            return Conversion.toBytes(numericalValue, Evm.Utils.WORD_SIZE);
        //you may be wondering, why do we not just use definition.value here,
        //like we do below? answer: because if this isn't a literal, that may not
        //exist
        case "stringliteral":
            return Conversion.toBytes(definition.hexValue);
        default:
            //unfortunately, other types of constants are just too complicated to
            //handle right now.  sorry.
            debug("unsupported constant definition type");
            throw new errors_1.DecodingError({
                kind: "UnsupportedConstantError",
                definition
            });
    }
}
exports.readDefinition = readDefinition;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 849965:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.definitionToStoredType = exports.definitionToType = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:ast:import");
const bn_js_1 = __importDefault(__webpack_require__(213550));
const Compiler = __importStar(__webpack_require__(884159));
const Utils = __importStar(__webpack_require__(707656));
const import_1 = __webpack_require__(560013);
//NOTE: the following function will *not* work for arbitrary nodes! It will,
//however, work well enough for what we need.  I.e., it will:
//1. work when given the actual variable definition as the node,
//2. work when given an elementary type as the node,
//3. work when given a user-defined type as the node,
//4. produce something of the correct size in all cases.
//Use beyond that is at your own risk!
//NOTE: set forceLocation to *null* to force no location. leave it undefined
//to not force a location.
function definitionToType(definition, compilationId, compiler, forceLocation) {
    let typeClass = Utils.typeClass(definition);
    let typeHint = Utils.typeStringWithoutLocation(definition);
    switch (typeClass) {
        case "bool":
            return {
                typeClass,
                typeHint
            };
        case "address": {
            switch (Compiler.Utils.solidityFamily(compiler)) {
                case "unknown": //I guess?
                case "pre-0.5.0":
                    return {
                        typeClass,
                        kind: "general",
                        typeHint
                    };
                case "0.5.x":
                case "0.8.x":
                    return {
                        typeClass,
                        kind: "specific",
                        payable: Utils.typeIdentifier(definition) === "t_address_payable"
                    };
            }
            break; //to satisfy typescript
        }
        case "uint": {
            let bytes = Utils.specifiedSize(definition);
            return {
                typeClass,
                bits: bytes * 8,
                typeHint
            };
        }
        case "int": {
            //typeScript won't let me group these for some reason
            let bytes = Utils.specifiedSize(definition);
            return {
                typeClass,
                bits: bytes * 8,
                typeHint
            };
        }
        case "fixed": {
            //typeScript won't let me group these for some reason
            let bytes = Utils.specifiedSize(definition);
            let places = Utils.decimalPlaces(definition);
            return {
                typeClass,
                bits: bytes * 8,
                places,
                typeHint
            };
        }
        case "ufixed": {
            let bytes = Utils.specifiedSize(definition);
            let places = Utils.decimalPlaces(definition);
            return {
                typeClass,
                bits: bytes * 8,
                places,
                typeHint
            };
        }
        case "string": {
            if (forceLocation === null) {
                return {
                    typeClass,
                    typeHint
                };
            }
            let location = forceLocation || Utils.referenceType(definition);
            return {
                typeClass,
                location,
                typeHint
            };
        }
        case "bytes": {
            let length = Utils.specifiedSize(definition);
            if (length !== null) {
                return {
                    typeClass,
                    kind: "static",
                    length,
                    typeHint
                };
            }
            else {
                if (forceLocation === null) {
                    return {
                        typeClass,
                        kind: "dynamic",
                        typeHint
                    };
                }
                let location = forceLocation || Utils.referenceType(definition);
                return {
                    typeClass,
                    kind: "dynamic",
                    location,
                    typeHint
                };
            }
        }
        case "array": {
            let baseDefinition = Utils.baseDefinition(definition);
            let baseType = definitionToType(baseDefinition, compilationId, compiler, forceLocation);
            let location = forceLocation || Utils.referenceType(definition);
            if (Utils.isDynamicArray(definition)) {
                if (forceLocation !== null) {
                    return {
                        typeClass,
                        baseType,
                        kind: "dynamic",
                        location,
                        typeHint
                    };
                }
                else {
                    return {
                        typeClass,
                        baseType,
                        kind: "dynamic",
                        typeHint
                    };
                }
            }
            else {
                let length = new bn_js_1.default(Utils.staticLengthAsString(definition));
                if (forceLocation !== null) {
                    return {
                        typeClass,
                        baseType,
                        kind: "static",
                        length,
                        location,
                        typeHint
                    };
                }
                else {
                    return {
                        typeClass,
                        baseType,
                        kind: "static",
                        length,
                        typeHint
                    };
                }
            }
        }
        case "mapping": {
            let keyDefinition = Utils.keyDefinition(definition);
            //note that we can skip the scopes argument here! that's only needed when
            //a general node, rather than a declaration, is being passed in
            let keyType = (definitionToType(keyDefinition, compilationId, compiler, null));
            //suppress the location on the key type (it'll be given as memory but
            //this is meaningless)
            //also, we have to tell TypeScript ourselves that this will be an elementary
            //type; it has no way of knowing that
            debug("definition: %O", definition);
            let valueDefinition = Utils.valueDefinition(definition);
            let valueType = definitionToType(valueDefinition, compilationId, compiler, forceLocation);
            if (forceLocation === null) {
                return {
                    typeClass,
                    keyType,
                    valueType
                };
            }
            return {
                typeClass,
                keyType,
                valueType,
                location: "storage"
            };
        }
        case "function": {
            //WARNING! This case will not work unless given the actual
            //definition!  It should return something *roughly* usable, though.
            let visibility = Utils.visibility(definition); //undefined if bad node
            let mutability = Utils.mutability(definition); //undefined if bad node
            let [inputParameters, outputParameters] = Utils.parameters(definition) || [[], []]; //HACK
            //note: don't force a location on these! use the listed location!
            let inputParameterTypes = inputParameters.map(parameter => definitionToType(parameter, compilationId, compiler));
            let outputParameterTypes = outputParameters.map(parameter => definitionToType(parameter, compilationId, compiler));
            switch (visibility) {
                case "internal":
                    return {
                        typeClass,
                        visibility,
                        mutability,
                        inputParameterTypes,
                        outputParameterTypes
                    };
                case "external":
                    return {
                        typeClass,
                        visibility,
                        kind: "specific",
                        mutability,
                        inputParameterTypes,
                        outputParameterTypes
                    };
            }
            break; //to satisfy typescript
        }
        case "struct": {
            let id = import_1.makeTypeId(Utils.typeId(definition), compilationId);
            let qualifiedName = Utils.typeStringWithoutLocation(definition).match(/struct (.*)/)[1];
            let definingContractName;
            let typeName;
            if (qualifiedName.includes(".")) {
                [definingContractName, typeName] = qualifiedName.split(".");
            }
            else {
                typeName = qualifiedName;
                //leave definingContractName undefined
            }
            if (forceLocation === null) {
                if (definingContractName) {
                    return {
                        typeClass,
                        kind: "local",
                        id,
                        typeName,
                        definingContractName
                    };
                }
                else {
                    return {
                        typeClass,
                        kind: "global",
                        id,
                        typeName
                    };
                }
            }
            let location = forceLocation || Utils.referenceType(definition);
            if (definingContractName) {
                return {
                    typeClass,
                    kind: "local",
                    id,
                    typeName,
                    definingContractName,
                    location
                };
            }
            else {
                return {
                    typeClass,
                    kind: "global",
                    id,
                    typeName,
                    location
                };
            }
        }
        case "enum": {
            let id = import_1.makeTypeId(Utils.typeId(definition), compilationId);
            let qualifiedName = Utils.typeStringWithoutLocation(definition).match(/enum (.*)/)[1];
            let definingContractName;
            let typeName;
            if (qualifiedName.includes(".")) {
                [definingContractName, typeName] = qualifiedName.split(".");
            }
            else {
                typeName = qualifiedName;
                //leave definingContractName undefined
            }
            if (definingContractName) {
                return {
                    typeClass,
                    kind: "local",
                    id,
                    typeName,
                    definingContractName
                };
            }
            else {
                return {
                    typeClass,
                    kind: "global",
                    id,
                    typeName
                };
            }
        }
        case "contract": {
            let id = import_1.makeTypeId(Utils.typeId(definition), compilationId);
            let typeName = Utils.typeStringWithoutLocation(definition).match(/(contract|library|interface) (.*)/)[2]; //note: we use the type string rather than the type identifier
            //in order to avoid having to deal with the underscore problem
            let contractKind = Utils.contractKind(definition);
            return {
                typeClass,
                kind: "native",
                id,
                typeName,
                contractKind
            };
        }
        case "magic": {
            let typeIdentifier = Utils.typeIdentifier(definition);
            let variable = (typeIdentifier.match(/^t_magic_(.*)$/)[1]);
            return {
                typeClass,
                variable
            };
        }
    }
}
exports.definitionToType = definitionToType;
//whereas the above takes variable definitions, this takes the actual type
//definition
function definitionToStoredType(definition, compilationId, compiler, referenceDeclarations) {
    switch (definition.nodeType) {
        case "StructDefinition": {
            let id = import_1.makeTypeId(definition.id, compilationId);
            let definingContractName;
            let typeName;
            if (definition.canonicalName.includes(".")) {
                [definingContractName, typeName] = definition.canonicalName.split(".");
            }
            else {
                typeName = definition.canonicalName;
                //leave definingContractName undefined
            }
            let memberTypes = definition.members.map(member => ({
                name: member.name,
                type: definitionToType(member, compilationId, compiler, null)
            }));
            let definingContract;
            if (referenceDeclarations) {
                let contractDefinition = Object.values(referenceDeclarations).find(node => node.nodeType === "ContractDefinition" &&
                    node.nodes.some((subNode) => import_1.makeTypeId(subNode.id, compilationId) === id));
                if (contractDefinition) {
                    definingContract = (definitionToStoredType(contractDefinition, compilationId, compiler)); //can skip reference declarations
                }
            }
            if (definingContract) {
                return {
                    typeClass: "struct",
                    kind: "local",
                    id,
                    typeName,
                    definingContractName,
                    definingContract,
                    memberTypes
                };
            }
            else {
                return {
                    typeClass: "struct",
                    kind: "global",
                    id,
                    typeName,
                    memberTypes
                };
            }
        }
        case "EnumDefinition": {
            let id = import_1.makeTypeId(definition.id, compilationId);
            let definingContractName;
            let typeName;
            debug("typeName: %s", typeName);
            if (definition.canonicalName.includes(".")) {
                [definingContractName, typeName] = definition.canonicalName.split(".");
            }
            else {
                typeName = definition.canonicalName;
                //leave definingContractName undefined
            }
            let options = definition.members.map(member => member.name);
            let definingContract;
            if (referenceDeclarations) {
                let contractDefinition = Object.values(referenceDeclarations).find(node => node.nodeType === "ContractDefinition" &&
                    node.nodes.some((subNode) => import_1.makeTypeId(subNode.id, compilationId) === id));
                if (contractDefinition) {
                    definingContract = (definitionToStoredType(contractDefinition, compilationId, compiler)); //can skip reference declarations
                    debug("contractDefinition: %o", contractDefinition);
                    debug("definingContract: %o", definingContract);
                }
            }
            if (definingContract) {
                return {
                    typeClass: "enum",
                    kind: "local",
                    id,
                    typeName,
                    definingContractName,
                    definingContract,
                    options
                };
            }
            else {
                return {
                    typeClass: "enum",
                    kind: "global",
                    id,
                    typeName,
                    options
                };
            }
        }
        case "ContractDefinition": {
            let id = import_1.makeTypeId(definition.id, compilationId);
            let typeName = definition.name;
            let contractKind = definition.contractKind;
            let payable = Utils.isContractPayable(definition);
            return {
                typeClass: "contract",
                kind: "native",
                id,
                typeName,
                contractKind,
                payable
            };
        }
    }
}
exports.definitionToStoredType = definitionToStoredType;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 114442:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Import = exports.Utils = void 0;
__exportStar(__webpack_require__(765786), exports);
const Utils = __importStar(__webpack_require__(707656));
exports.Utils = Utils;
const Import = __importStar(__webpack_require__(849965));
exports.Import = Import;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 765786:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 707656:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getterParameters = exports.definitionToAbi = exports.isContractPayable = exports.mutability = exports.functionKind = exports.parameters = exports.valueDefinition = exports.keyDefinition = exports.baseDefinition = exports.rationalValue = exports.regularizeTypeIdentifier = exports.spliceLocation = exports.isSimpleConstant = exports.stackSize = exports.contractKind = exports.referenceType = exports.isReference = exports.isEnum = exports.isMapping = exports.isStruct = exports.staticLengthAsString = exports.staticLength = exports.isDynamicArray = exports.isArray = exports.decimalPlaces = exports.specifiedSize = exports.visibility = exports.typeId = exports.typeClassLongForm = exports.typeClass = exports.typeStringWithoutLocation = exports.typeString = exports.typeIdentifier = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:ast:utils");
const Common = __importStar(__webpack_require__(299987));
const bn_js_1 = __importDefault(__webpack_require__(213550));
const lodash_clonedeep_1 = __importDefault(__webpack_require__(483465));
/** @category Definition Reading */
function typeIdentifier(definition) {
    return definition.typeDescriptions.typeIdentifier;
}
exports.typeIdentifier = typeIdentifier;
/** @category Definition Reading */
function typeString(definition) {
    return definition.typeDescriptions.typeString;
}
exports.typeString = typeString;
/**
 * Returns the type string, but with location (if any) stripped off the end
 * @category Definition Reading
 */
function typeStringWithoutLocation(definition) {
    if (definition.nodeType === "YulTypedName") {
        //for handling Yul variables
        return "bytes32";
    }
    return typeString(definition).replace(/ (storage|memory|calldata)( slice)?$/, "");
}
exports.typeStringWithoutLocation = typeStringWithoutLocation;
/**
 * returns basic type class for a variable definition node
 * e.g.:
 *  `t_uint256` becomes `uint`
 *  `t_struct$_Thing_$20_memory_ptr` becomes `struct`
 * @category Definition Reading
 */
function typeClass(definition) {
    if (definition.nodeType === "YulTypedName") {
        //for handling Yul variables
        return "bytes";
    }
    return typeIdentifier(definition).match(/t_([^$_0-9]+)/)[1];
}
exports.typeClass = typeClass;
/**
 * similar to typeClass, but includes any numeric qualifiers
 * e.g.:
 * `t_uint256` becomes `uint256`
 * @category Definition Reading
 */
function typeClassLongForm(definition) {
    return typeIdentifier(definition).match(/t_([^$_]+)/)[1];
}
exports.typeClassLongForm = typeClassLongForm;
/**
 * for user-defined types -- structs, enums, contracts
 * often you can get these from referencedDeclaration, but not
 * always
 * @category Definition Reading
 */
function typeId(definition) {
    debug("definition %O", definition);
    return parseInt(typeIdentifier(definition).match(/\$(\d+)(_(storage|memory|calldata)(_ptr(_slice)?)?)?$/)[1]);
}
exports.typeId = typeId;
/**
 * For function types; returns internal or external
 * (not for use on other types! will cause an error!)
 * should only return "internal" or "external"
 * @category Definition Reading
 */
function visibility(definition) {
    return ((definition.typeName
        ? definition.typeName.visibility
        : definition.visibility));
}
exports.visibility = visibility;
/**
 * e.g. uint48 -> 6
 * @return size in bytes for explicit type size, or `null` if not stated
 * @category Definition Reading
 */
function specifiedSize(definition) {
    if (definition.nodeType === "YulTypedName") {
        return 32; //for handling Yul variables
    }
    let specified = typeIdentifier(definition).match(/t_[a-z]+([0-9]+)/);
    if (!specified) {
        return null;
    }
    let num = parseInt(specified[1]);
    switch (typeClass(definition)) {
        case "int":
        case "uint":
        case "fixed":
        case "ufixed":
            return num / 8;
        case "bytes":
            return num;
        default:
            debug("Unknown type for size specification: %s", typeIdentifier(definition));
    }
}
exports.specifiedSize = specifiedSize;
/**
 * for fixed-point types, obviously
 * @category Definition Reading
 */
function decimalPlaces(definition) {
    return parseInt(typeIdentifier(definition).match(/t_[a-z]+[0-9]+x([0-9]+)/)[1]);
}
exports.decimalPlaces = decimalPlaces;
/** @category Definition Reading */
function isArray(definition) {
    return typeIdentifier(definition).match(/^t_array/) != null;
}
exports.isArray = isArray;
/** @category Definition Reading */
function isDynamicArray(definition) {
    return (isArray(definition) &&
        //NOTE: we do this by parsing the type identifier, rather than by just
        //checking the length field, because we might be using this on a faked-up
        //definition
        typeIdentifier(definition).match(/\$dyn_(storage|memory|calldata)(_ptr(_slice)?)?$/) != null);
}
exports.isDynamicArray = isDynamicArray;
/**
 * length of a statically sized array -- please only use for arrays
 * already verified to be static!
 * @category Definition Reading
 */
function staticLength(definition) {
    //NOTE: we do this by parsing the type identifier, rather than by just
    //checking the length field, because we might be using this on a faked-up
    //definition
    return parseInt(staticLengthAsString(definition));
}
exports.staticLength = staticLength;
/**
 * see staticLength for explanation
 * @category Definition Reading
 */
function staticLengthAsString(definition) {
    return typeIdentifier(definition).match(/\$(\d+)_(storage|memory|calldata)(_ptr(_slice)?)?$/)[1];
}
exports.staticLengthAsString = staticLengthAsString;
/** @category Definition Reading */
function isStruct(definition) {
    return typeIdentifier(definition).match(/^t_struct/) != null;
}
exports.isStruct = isStruct;
/** @category Definition Reading */
function isMapping(definition) {
    return typeIdentifier(definition).match(/^t_mapping/) != null;
}
exports.isMapping = isMapping;
/** @category Definition Reading */
function isEnum(definition) {
    return typeIdentifier(definition).match(/^t_enum/) != null;
}
exports.isEnum = isEnum;
/** @category Definition Reading */
function isReference(definition) {
    return (typeIdentifier(definition).match(/_(memory|storage|calldata)(_ptr(_slice)?)?$/) != null);
}
exports.isReference = isReference;
/**
 * note: only use this on things already verified to be references
 * @category Definition Reading
 */
function referenceType(definition) {
    return typeIdentifier(definition).match(/_([^_]+)(_ptr(_slice)?)?$/)[1];
}
exports.referenceType = referenceType;
/**
 * only for contract types, obviously! will yield nonsense otherwise!
 * @category Definition Reading
 */
function contractKind(definition) {
    return typeString(definition).split(" ")[0];
}
exports.contractKind = contractKind;
/**
 * stack size, in words, of a given type
 * @category Definition Reading
 */
function stackSize(definition) {
    if (typeClass(definition) === "function" &&
        visibility(definition) === "external") {
        return 2;
    }
    if (isReference(definition) && referenceType(definition) === "calldata") {
        if (typeClass(definition) === "string" ||
            typeClass(definition) === "bytes") {
            return 2;
        }
        if (isDynamicArray(definition)) {
            return 2;
        }
    }
    return 1;
}
exports.stackSize = stackSize;
/** @category Definition Reading */
function isSimpleConstant(definition) {
    const types = ["stringliteral", "rational"];
    return types.includes(typeClass(definition));
}
exports.isSimpleConstant = isSimpleConstant;
/**
 * definition: a storage reference definition
 * location: the location you want it to refer to instead
 * @category Definition Reading
 */
function spliceLocation(definition, location) {
    debug("definition %O", definition);
    return Object.assign(Object.assign({}, definition), { typeDescriptions: Object.assign(Object.assign({}, definition.typeDescriptions), { typeIdentifier: definition.typeDescriptions.typeIdentifier.replace(/_(storage|memory|calldata)(?=((_slice)?_ptr)?$)/, "_" + location) }) });
}
exports.spliceLocation = spliceLocation;
/**
 * adds "_ptr" on to the end of type identifiers that might need it; note that
 * this operates on identifiers, not definitions
 * @category Definition Reading
 */
function regularizeTypeIdentifier(identifier) {
    return identifier.replace(/(_(storage|memory|calldata))((_slice)?_ptr)?$/, "$1_ptr" //this used to use lookbehind for clarity, but Firefox...
    //(see: https://github.com/trufflesuite/truffle/issues/3068 )
    );
}
exports.regularizeTypeIdentifier = regularizeTypeIdentifier;
/**
 * extract the actual numerical value from a node of type rational.
 * currently assumes result will be integer (currently returns BN)
 * @category Definition Reading
 */
function rationalValue(definition) {
    let identifier = typeIdentifier(definition);
    let absoluteValue = identifier.match(/_(\d+)_by_1$/)[1];
    let isNegative = identifier.match(/_minus_/) != null;
    return isNegative ? new bn_js_1.default(absoluteValue).neg() : new bn_js_1.default(absoluteValue);
}
exports.rationalValue = rationalValue;
/** @category Definition Reading */
function baseDefinition(definition) {
    if (definition.typeName && definition.typeName.baseType) {
        return definition.typeName.baseType;
    }
    if (definition.baseType) {
        return definition.baseType;
    }
    //otherwise, we'll have to spoof it up ourselves
    let baseIdentifier = typeIdentifier(definition).match(/^t_array\$_(.*)_\$/)[1];
    //greedy match to extract everything from first to last dollar sign
    // HACK - internal types for memory or storage also seem to be pointers
    baseIdentifier = regularizeTypeIdentifier(baseIdentifier);
    // another HACK - we get away with it because we're only using that one property
    let result = lodash_clonedeep_1.default(definition);
    result.typeDescriptions.typeIdentifier = baseIdentifier;
    return result;
    //WARNING -- these hacks do *not* correctly handle all cases!
    //they do, however, handle the cases we currently need.
}
exports.baseDefinition = baseDefinition;
/**
 * for use for mappings and arrays only!
 * for arrays, fakes up a uint definition
 * @category Definition Reading
 */
function keyDefinition(definition, scopes) {
    let result;
    switch (typeClass(definition)) {
        case "mapping":
            //first: is there a key type already there? if so just use that
            if (definition.keyType) {
                return definition.keyType;
            }
            if (definition.typeName && definition.typeName.keyType) {
                return definition.typeName.keyType;
            }
            //otherwise: is there a referencedDeclaration? if so try using that
            let baseDeclarationId = definition.referencedDeclaration;
            debug("baseDeclarationId %d", baseDeclarationId);
            //if there's a referencedDeclaration, we'll use that
            if (baseDeclarationId !== undefined) {
                let baseDeclaration = scopes[baseDeclarationId].definition;
                return baseDeclaration.keyType || baseDeclaration.typeName.keyType;
            }
            //otherwise, we'll need to perform some hackery, similarly to in baseDefinition;
            //we'll have to spoof it up ourselves
            let keyIdentifier = typeIdentifier(definition).match(/^t_mapping\$_(.*?)_\$_/)[1];
            //use *non*-greedy match; note that if the key type could include
            //the sequence "_$_", this could cause a problem, but they can't; the only
            //valid key types that include dollar signs at all are user-defined types,
            //which contain both "$_" and "_$" but never "_$_".
            // HACK - internal types for memory or storage also seem to be pointers
            keyIdentifier = regularizeTypeIdentifier(keyIdentifier);
            let keyString = typeString(definition).match(/mapping\((.*?) => .*\)( storage)?$/)[1];
            //use *non*-greedy match; note that if the key type could include
            //"=>", this could cause a problem, but mappings are not allowed as key
            //types, so this can't come up
            // another HACK - we get away with it because we're only using that one property
            result = lodash_clonedeep_1.default(definition);
            result.typeDescriptions = {
                typeIdentifier: keyIdentifier,
                typeString: keyString
            };
            return result;
        case "array":
            //HACK -- again we should get away with it because for a uint256 we don't
            //really need to inspect the other properties
            result = lodash_clonedeep_1.default(definition);
            result.typeDescriptions = {
                typeIdentifier: "t_uint256",
                typeString: "uint256"
            };
            return result;
        default:
            debug("unrecognized index access!");
    }
}
exports.keyDefinition = keyDefinition;
/**
 * for use for mappings only!
 * @category Definition Reading
 */
function valueDefinition(definition, scopes) {
    let result;
    //first: is there a value type already there? if so just use that
    if (definition.valueType) {
        return definition.valueType;
    }
    if (definition.typeName && definition.typeName.valueType) {
        return definition.typeName.valueType;
    }
    //otherwise: is there a referencedDeclaration? if so try using that
    let baseDeclarationId = definition.referencedDeclaration;
    debug("baseDeclarationId %d", baseDeclarationId);
    //if there's a referencedDeclaration, we'll use that
    if (baseDeclarationId !== undefined) {
        let baseDeclaration = scopes[baseDeclarationId].definition;
        return baseDeclaration.valueType || baseDeclaration.typeName.valueType;
    }
    //otherwise, we'll need to perform some hackery, similarly to in keyDefinition;
    //we'll have to spoof it up ourselves
    let valueIdentifier = typeIdentifier(definition).match(/^t_mapping\$_.*?_\$_(.*)_\$/)[1];
    //use *non*-greedy match on the key; note that if the key type could include
    //the sequence "_$_", this could cause a problem, but they can't; the only
    //valid key types that include dollar signs at all are user-defined types,
    //which contain both "$_" and "_$" but never "_$_".
    // HACK - internal types for memory or storage also seem to be pointers
    valueIdentifier = regularizeTypeIdentifier(valueIdentifier);
    let valueString = typeString(definition).match(/mapping\(.*? => (.*)\)( storage)?$/)[1];
    //use *non*-greedy match; note that if the key type could include
    //"=>", this could cause a problem, but mappings are not allowed as key
    //types, so this can't come up
    // another HACK - we get away with it because we're only using that one property
    result = lodash_clonedeep_1.default(definition);
    result.typeDescriptions = {
        typeIdentifier: valueIdentifier,
        typeString: valueString
    };
    return result;
}
exports.valueDefinition = valueDefinition;
/**
 * returns input parameters, then output parameters
 * NOTE: ONLY FOR VARIABLE DECLARATIONS OF FUNCTION TYPE
 * NOT FOR FUNCTION DEFINITIONS
 * @category Definition Reading
 */
function parameters(definition) {
    let typeObject = definition.typeName || definition;
    if (typeObject.parameterTypes && typeObject.returnParameterTypes) {
        return [
            typeObject.parameterTypes.parameters,
            typeObject.returnParameterTypes.parameters
        ];
    }
    else {
        return undefined;
    }
}
exports.parameters = parameters;
/**
 * compatibility function, since pre-0.5.0 functions don't have node.kind
 * returns undefined if you don't put in a function node
 * @category Definition Reading
 */
function functionKind(node) {
    if (node.nodeType !== "FunctionDefinition") {
        return undefined;
    }
    if (node.kind !== undefined) {
        //if we're dealing with 0.5.x, we can just read node.kind
        return node.kind;
    }
    //otherwise, we need this little shim
    if (node.isConstructor) {
        return "constructor";
    }
    return node.name === "" ? "fallback" : "function";
}
exports.functionKind = functionKind;
/**
 * similar compatibility function for mutability for pre-0.4.16 versions
 * returns undefined if you don't give it a FunctionDefinition or
 * VariableDeclaration
 * @category Definition Reading
 */
function mutability(node) {
    node = node.typeName || node;
    if (node.nodeType !== "FunctionDefinition" &&
        node.nodeType !== "FunctionTypeName") {
        return undefined;
    }
    if (node.stateMutability !== undefined) {
        //if we're dealing with 0.4.16 or later, we can just read node.stateMutability
        return node.stateMutability;
    }
    //otherwise, we need this little shim
    if (node.payable) {
        return "payable";
    }
    if (node.constant) {
        //yes, it means "view" even if you're looking at a variable declaration!
        //old Solidity was weird!
        return "view";
    }
    return "nonpayable";
}
exports.mutability = mutability;
/**
 * takes a contract definition and asks, does it have a payable fallback
 * function?
 * @category Definition Reading
 */
function isContractPayable(definition) {
    return definition.nodes.some(node => node.nodeType === "FunctionDefinition" &&
        (functionKind(node) === "fallback" || functionKind(node) === "receive") &&
        mutability(node) === "payable");
}
exports.isContractPayable = isContractPayable;
/**
 * the main function. just does some dispatch.
 * returns undefined on bad input
 */
function definitionToAbi(node, referenceDeclarations) {
    switch (node.nodeType) {
        case "FunctionDefinition":
            if (node.visibility === "public" || node.visibility === "external") {
                return functionDefinitionToAbi(node, referenceDeclarations);
            }
            else {
                return undefined;
            }
        case "EventDefinition":
            return eventDefinitionToAbi(node, referenceDeclarations);
        case "VariableDeclaration":
            if (node.visibility === "public") {
                return getterDefinitionToAbi(node, referenceDeclarations);
            }
            else {
                return undefined;
            }
        default:
            return undefined;
    }
}
exports.definitionToAbi = definitionToAbi;
//note: not for FunctionTypeNames or VariableDeclarations
function functionDefinitionToAbi(node, referenceDeclarations) {
    let kind = functionKind(node);
    let stateMutability = mutability(node);
    let payable = stateMutability === "payable";
    let inputs;
    switch (kind) {
        case "function":
            let name = node.name;
            let outputs = parametersToAbi(node.returnParameters.parameters, referenceDeclarations);
            inputs = parametersToAbi(node.parameters.parameters, referenceDeclarations);
            return {
                type: "function",
                name,
                inputs,
                outputs,
                stateMutability
            };
        case "constructor":
            inputs = parametersToAbi(node.parameters.parameters, referenceDeclarations);
            //note: need to coerce because of mutability restrictions
            return {
                type: "constructor",
                inputs,
                stateMutability,
                payable
            };
        case "fallback":
            //note: need to coerce because of mutability restrictions
            return {
                type: "fallback",
                stateMutability,
                payable
            };
        case "receive":
            //note: need to coerce because of mutability restrictions
            return {
                type: "receive",
                stateMutability,
                payable
            };
    }
}
function eventDefinitionToAbi(node, referenceDeclarations) {
    let inputs = parametersToAbi(node.parameters.parameters, referenceDeclarations);
    let name = node.name;
    let anonymous = node.anonymous;
    return {
        type: "event",
        inputs,
        name,
        anonymous
    };
}
function parametersToAbi(nodes, referenceDeclarations) {
    return nodes.map(node => parameterToAbi(node, referenceDeclarations));
}
//NOTE: This function is only for types that could potentially go in the ABI!
//(otherwise it could, say, loop infinitely)
//currently it will only ever be called on those because it's only called from
//definitionToAbi, which filters out any definitions that are not for
//this that *actually* go in the ABI
//if you want to expand it to handle those (by throwing an exception, say),
//you'll need to give it a way to detect circularities
function parameterToAbi(node, referenceDeclarations) {
    let name = node.name; //may be the empty string... or even undefined for a base type
    let components;
    let internalType = typeStringWithoutLocation(node);
    //is this an array? if so use separate logic
    if (typeClass(node) === "array") {
        let baseType = node.typeName ? node.typeName.baseType : node.baseType;
        let baseAbi = parameterToAbi(baseType, referenceDeclarations);
        let arraySuffix = isDynamicArray(node) ? `[]` : `[${staticLength(node)}]`;
        const parameter = {
            name,
            type: baseAbi.type + arraySuffix,
            components: baseAbi.components,
            internalType
        };
        if ("indexed" in node) {
            return Object.assign(Object.assign({}, parameter), { indexed: node.indexed });
        }
        else {
            return parameter;
        }
    }
    let abiTypeString = toAbiType(node, referenceDeclarations);
    //otherwise... is it a struct? if so we need to populate components
    if (typeClass(node) === "struct") {
        let id = typeId(node);
        let referenceDeclaration = referenceDeclarations[id];
        if (referenceDeclaration === undefined) {
            let typeToDisplay = typeString(node);
            throw new Common.UnknownUserDefinedTypeError(id.toString(), typeToDisplay);
        }
        components = parametersToAbi(referenceDeclaration.members, referenceDeclarations);
    }
    const parameter = {
        name,
        type: abiTypeString,
        components,
        internalType
    };
    if ("indexed" in node) {
        return Object.assign(Object.assign({}, parameter), { indexed: node.indexed });
    }
    else {
        return parameter;
    }
}
//note: this is only meant for non-array types that can go in the ABI
//it returns how that type is notated in the ABI -- just the string,
//to be clear, not components of tuples
//again, NOT FOR ARRAYS
function toAbiType(node, referenceDeclarations) {
    let basicType = typeClassLongForm(node); //get that whole first segment!
    switch (basicType) {
        case "contract":
            return "address";
        case "struct":
            return "tuple"; //the more detailed checking will be handled elsewhere
        case "enum":
            let referenceId = typeId(node);
            let referenceDeclaration = referenceDeclarations[referenceId];
            if (referenceDeclaration === undefined) {
                let typeToDisplay = typeString(node);
                throw new Common.UnknownUserDefinedTypeError(referenceId.toString(), typeToDisplay);
            }
            let numOptions = referenceDeclaration.members.length;
            let bits = 8 * Math.ceil(Math.log2(numOptions) / 8);
            return `uint${bits}`;
        default:
            return basicType;
        //note that: int/uint/fixed/ufixed/bytes will have their size and such left on;
        //address will have "payable" left off;
        //external functions will be reduced to "function" (and internal functions shouldn't
        //be passed in!)
        //(mappings shouldn't be passed in either obviously)
        //(nor arrays :P )
    }
}
function getterDefinitionToAbi(node, referenceDeclarations) {
    debug("getter node: %O", node);
    let name = node.name;
    let { inputs, outputs } = getterParameters(node, referenceDeclarations);
    let inputsAbi = parametersToAbi(inputs, referenceDeclarations);
    let outputsAbi = parametersToAbi(outputs, referenceDeclarations);
    return {
        type: "function",
        name,
        inputs: inputsAbi,
        outputs: outputsAbi,
        stateMutability: "view"
    };
}
//how getter parameters work:
//INPUT:
//types other than arrays and mappings take no input.
//array getters take uint256 input. mapping getters take input of their key type.
//if arrays, mappings, stacked, then takes multiple inputs, in order from outside
//to in.
//These parameters are unnamed.
//OUTPUT:
//if base type (beneath mappings & arrays) is not a struct, returns that.
//(This return parameter has no name -- it is *not* named for the variable!)
//if it is a struct, returns multiple outputs, one for each member of the struct,
//*except* arrays and mappings.  (And they have names, the names of the members.)
//important note: inner structs within a struct are just returned, not
//partially destructured like the outermost struct!  Yes, this is confusing.
function getterParameters(node, referenceDeclarations) {
    let baseNode = node.typeName || node;
    let inputs = [];
    while (typeClass(baseNode) === "array" || typeClass(baseNode) === "mapping") {
        let keyNode = keyDefinition(baseNode); //note: if baseNode is an array, this spoofs up a uint256 definition
        inputs.push(Object.assign(Object.assign({}, keyNode), { name: "" })); //again, getter input params have no name
        switch (typeClass(baseNode)) {
            case "array":
                baseNode = baseNode.baseType;
                break;
            case "mapping":
                baseNode = baseNode.valueType;
                break;
        }
    }
    //at this point, baseNode should hold the base type
    //now we face the question: is it a struct?
    if (typeClass(baseNode) === "struct") {
        let id = typeId(baseNode);
        let referenceDeclaration = referenceDeclarations[id];
        if (referenceDeclaration === undefined) {
            let typeToDisplay = typeString(baseNode);
            throw new Common.UnknownUserDefinedTypeError(id.toString(), typeToDisplay);
        }
        let outputs = referenceDeclaration.members.filter(member => typeClass(member) !== "array" && typeClass(member) !== "mapping");
        return { inputs, outputs }; //no need to wash name!
    }
    else {
        //only one output; it's just the base node, with its name washed
        return { inputs, outputs: [Object.assign(Object.assign({}, baseNode), { name: "" })] };
    }
}
exports.getterParameters = getterParameters;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 849107:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.byteLength = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:basic:allocate");
const Common = __importStar(__webpack_require__(299987));
const Evm = __importStar(__webpack_require__(149218));
const Format = __importStar(__webpack_require__(429965));
//only for direct types!
function byteLength(dataType, userDefinedTypes) {
    switch (dataType.typeClass) {
        case "bool":
            return 1;
        case "address":
        case "contract":
            return Evm.Utils.ADDRESS_SIZE;
        case "int":
        case "uint":
        case "fixed":
        case "ufixed":
            return dataType.bits / 8;
        case "function":
            switch (dataType.visibility) {
                case "internal":
                    return Evm.Utils.PC_SIZE * 2;
                case "external":
                    return Evm.Utils.ADDRESS_SIZE + Evm.Utils.SELECTOR_SIZE;
            }
        case "bytes": //we assume we're in the static case
            return dataType.length;
        case "enum": //the only complex case!
            const storedType = userDefinedTypes[dataType.id];
            if (!storedType.options) {
                throw new Common.UnknownUserDefinedTypeError(dataType.id, Format.Types.typeString(dataType));
            }
            const numValues = storedType.options.length;
            return Math.ceil(Math.log2(numValues) / 8);
    }
}
exports.byteLength = byteLength;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 257939:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.checkPaddingLeft = exports.decodeInternalFunction = exports.decodeExternalFunction = exports.decodeContract = exports.decodeBasic = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:basic:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const Format = __importStar(__webpack_require__(429965));
const Contexts = __importStar(__webpack_require__(697938));
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
const allocate_1 = __webpack_require__(849107);
function* decodeBasic(dataType, pointer, info, options = {}) {
    const { state } = info;
    const { strictAbiMode: strict } = options; //if this is undefined it'll still be falsy so it's OK
    const paddingMode = options.paddingMode || "default";
    let bytes;
    let rawBytes;
    try {
        bytes = yield* read_1.default(pointer, state);
    }
    catch (error) {
        debug("segfault, pointer %o, state: %O", pointer, state);
        return errors_1.handleDecodingError(dataType, error, strict);
    }
    rawBytes = bytes;
    debug("type %O", dataType);
    debug("pointer %o", pointer);
    switch (dataType.typeClass) {
        case "bool": {
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "BoolPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            bytes = removePadding(bytes, dataType, paddingMode);
            //note: the use of the BN is a little silly here,
            //but, kind of stuck with it for now
            const numeric = Conversion.toBN(bytes);
            if (numeric.eqn(0)) {
                return {
                    type: dataType,
                    kind: "value",
                    value: { asBoolean: false }
                };
            }
            else if (numeric.eqn(1)) {
                return {
                    type: dataType,
                    kind: "value",
                    value: { asBoolean: true }
                };
            }
            else {
                let error = {
                    kind: "BoolOutOfRangeError",
                    rawAsBN: numeric
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
        }
        case "uint":
            //first, check padding (if needed)
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "UintPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            //now, truncate to appropriate length
            bytes = removePadding(bytes, dataType, paddingMode);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBN: Conversion.toBN(bytes),
                    rawAsBN: Conversion.toBN(rawBytes)
                }
            };
        case "int":
            //first, check padding (if needed)
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "IntPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            //now, truncate to appropriate length (keeping the bytes on the right)
            bytes = removePadding(bytes, dataType, paddingMode);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBN: Conversion.toSignedBN(bytes),
                    rawAsBN: Conversion.toSignedBN(rawBytes)
                }
            };
        case "address":
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "AddressPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            bytes = removePadding(bytes, dataType, paddingMode);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asAddress: Evm.Utils.toAddress(bytes),
                    rawAsHex: Conversion.toHexString(rawBytes)
                }
            };
        case "contract":
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "ContractPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            bytes = removePadding(bytes, dataType, paddingMode);
            const fullType = (Format.Types.fullType(dataType, info.userDefinedTypes));
            const contractValueInfo = yield* decodeContract(bytes, info);
            return {
                type: fullType,
                kind: "value",
                value: contractValueInfo
            };
        case "bytes":
            //NOTE: we assume this is a *static* bytestring,
            //because this is decodeBasic! dynamic ones should
            //go to decodeBytes!
            let coercedDataType = dataType;
            //first, check padding (if needed)
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "BytesPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: coercedDataType,
                    kind: "error",
                    error
                };
            }
            //now, truncate to appropriate length
            bytes = removePadding(bytes, dataType, paddingMode);
            return {
                type: coercedDataType,
                kind: "value",
                value: {
                    asHex: Conversion.toHexString(bytes),
                    rawAsHex: Conversion.toHexString(rawBytes)
                }
            };
        case "function":
            switch (dataType.visibility) {
                case "external":
                    if (!checkPadding(bytes, dataType, paddingMode)) {
                        let error = {
                            kind: "FunctionExternalNonStackPaddingError",
                            paddingType: getPaddingType(dataType, paddingMode),
                            raw: Conversion.toHexString(bytes)
                        };
                        if (strict) {
                            throw new errors_1.StopDecodingError(error);
                        }
                        return {
                            type: dataType,
                            kind: "error",
                            error
                        };
                    }
                    bytes = removePadding(bytes, dataType, paddingMode);
                    const address = bytes.slice(0, Evm.Utils.ADDRESS_SIZE);
                    const selector = bytes.slice(Evm.Utils.ADDRESS_SIZE, Evm.Utils.ADDRESS_SIZE + Evm.Utils.SELECTOR_SIZE);
                    return {
                        type: dataType,
                        kind: "value",
                        value: yield* decodeExternalFunction(address, selector, info)
                    };
                case "internal":
                    if (strict) {
                        //internal functions don't go in the ABI!
                        //this should never happen, but just to be sure...
                        throw new errors_1.StopDecodingError({
                            kind: "InternalFunctionInABIError"
                        });
                    }
                    if (!checkPadding(bytes, dataType, paddingMode)) {
                        return {
                            type: dataType,
                            kind: "error",
                            error: {
                                kind: "FunctionInternalPaddingError",
                                paddingType: getPaddingType(dataType, paddingMode),
                                raw: Conversion.toHexString(bytes)
                            }
                        };
                    }
                    bytes = removePadding(bytes, dataType, paddingMode);
                    const deployedPc = bytes.slice(-Evm.Utils.PC_SIZE);
                    const constructorPc = bytes.slice(-Evm.Utils.PC_SIZE * 2, -Evm.Utils.PC_SIZE);
                    return decodeInternalFunction(dataType, deployedPc, constructorPc, info);
            }
            break; //to satisfy TypeScript
        case "enum": {
            let numeric = Conversion.toBN(bytes);
            const fullType = (Format.Types.fullType(dataType, info.userDefinedTypes));
            if (!fullType.options) {
                let error = {
                    kind: "EnumNotFoundDecodingError",
                    type: fullType,
                    rawAsBN: numeric
                };
                if (strict || options.allowRetry) {
                    throw new errors_1.StopDecodingError(error, true);
                    //note that we allow a retry if we couldn't locate the enum type!
                }
                return {
                    type: fullType,
                    kind: "error",
                    error
                };
            }
            //note: I'm doing the padding checks a little more manually on this one
            //so that we can have the right type of error
            const numOptions = fullType.options.length;
            const numBytes = Math.ceil(Math.log2(numOptions) / 8);
            const paddingType = getPaddingType(dataType, paddingMode);
            if (!checkPaddingDirect(bytes, numBytes, paddingType)) {
                let error = {
                    kind: "EnumPaddingError",
                    type: fullType,
                    paddingType,
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            bytes = removePaddingDirect(bytes, numBytes, paddingType);
            numeric = Conversion.toBN(bytes); //alter numeric!
            if (numeric.ltn(numOptions)) {
                const name = fullType.options[numeric.toNumber()];
                //NOTE: despite the use of toNumber(), I'm NOT catching exceptions here and returning an
                //error value like elsewhere; I'm just letting this one fail.  Why?  Because if we have
                //an enum with that many options in the first place, we have bigger problems!
                return {
                    type: fullType,
                    kind: "value",
                    value: {
                        name,
                        numericAsBN: numeric
                    }
                };
            }
            else {
                let error = {
                    kind: "EnumOutOfRangeError",
                    type: fullType,
                    rawAsBN: numeric
                };
                if (strict) {
                    //note:
                    //if the enum is merely out of range rather than out of the ABI range,
                    //we do NOT throw an error here!  instead we simply return an error value,
                    //which we normally avoid doing in strict mode.  (the error will be caught
                    //later at the re-encoding step instead.)  why?  because we might be running
                    //in ABI mode, so we may need to abify this "value" rather than just throwing
                    //it out.
                    throw new errors_1.StopDecodingError(error);
                    //note that we do NOT allow a retry here!
                    //if we *can* find the enum type but the value is out of range,
                    //we *know* that it is invalid!
                }
                return {
                    type: fullType,
                    kind: "error",
                    error
                };
            }
        }
        case "fixed": {
            //first, check padding (if needed)
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "FixedPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            //now, truncate to appropriate length (keeping the bytes on the right)
            bytes = removePadding(bytes, dataType, paddingMode);
            let asBN = Conversion.toSignedBN(bytes);
            let rawAsBN = Conversion.toSignedBN(rawBytes);
            let asBig = Conversion.shiftBigDown(Conversion.toBig(asBN), dataType.places);
            let rawAsBig = Conversion.shiftBigDown(Conversion.toBig(rawAsBN), dataType.places);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBig,
                    rawAsBig
                }
            };
        }
        case "ufixed": {
            //first, check padding (if needed)
            if (!checkPadding(bytes, dataType, paddingMode)) {
                let error = {
                    kind: "UfixedPaddingError",
                    paddingType: getPaddingType(dataType, paddingMode),
                    raw: Conversion.toHexString(bytes)
                };
                if (strict) {
                    throw new errors_1.StopDecodingError(error);
                }
                return {
                    type: dataType,
                    kind: "error",
                    error
                };
            }
            //now, truncate to appropriate length (keeping the bytes on the right)
            bytes = removePadding(bytes, dataType, paddingMode);
            let asBN = Conversion.toBN(bytes);
            let rawAsBN = Conversion.toBN(rawBytes);
            let asBig = Conversion.shiftBigDown(Conversion.toBig(asBN), dataType.places);
            let rawAsBig = Conversion.shiftBigDown(Conversion.toBig(rawAsBN), dataType.places);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBig,
                    rawAsBig
                }
            };
        }
    }
}
exports.decodeBasic = decodeBasic;
//NOTE that this function returns a ContractValueInfo, not a ContractResult
function* decodeContract(addressBytes, info) {
    return (yield* decodeContractAndContext(addressBytes, info)).contractInfo;
}
exports.decodeContract = decodeContract;
function* decodeContractAndContext(addressBytes, info) {
    let address = Evm.Utils.toAddress(addressBytes);
    let rawAddress = Conversion.toHexString(addressBytes);
    let codeBytes = yield {
        type: "code",
        address
    };
    let code = Conversion.toHexString(codeBytes);
    let context = Contexts.Utils.findContext(info.contexts, code);
    if (context !== null) {
        return {
            context,
            contractInfo: {
                kind: "known",
                address,
                rawAddress,
                class: Contexts.Import.contextToType(context)
            }
        };
    }
    else {
        return {
            context,
            contractInfo: {
                kind: "unknown",
                address,
                rawAddress
            }
        };
    }
}
//note: address can have extra zeroes on the left like elsewhere, but selector should be exactly 4 bytes
//NOTE this again returns a FunctionExternalValueInfo, not a FunctionExternalResult
function* decodeExternalFunction(addressBytes, selectorBytes, info) {
    let { contractInfo: contract, context } = yield* decodeContractAndContext(addressBytes, info);
    let selector = Conversion.toHexString(selectorBytes);
    if (contract.kind === "unknown") {
        return {
            kind: "unknown",
            contract,
            selector
        };
    }
    let abiEntry = context.abi !== undefined ? context.abi[selector] : undefined;
    if (abiEntry === undefined) {
        return {
            kind: "invalid",
            contract,
            selector
        };
    }
    return {
        kind: "known",
        contract,
        selector,
        abi: abiEntry
    };
}
exports.decodeExternalFunction = decodeExternalFunction;
//this one works a bit differently -- in order to handle errors, it *does* return a FunctionInternalResult
//also note, I haven't put the same sort of error-handling in this one since it's only intended to run with full info (for now, anyway)
function decodeInternalFunction(dataType, deployedPcBytes, constructorPcBytes, info) {
    let deployedPc = Conversion.toBN(deployedPcBytes).toNumber();
    let constructorPc = Conversion.toBN(constructorPcBytes).toNumber();
    let context = Contexts.Import.contextToType(info.currentContext);
    //before anything else: do we even have an internal functions table?
    //if not, we'll just return the info we have without really attemting to decode
    if (!info.internalFunctionsTable) {
        return {
            type: dataType,
            kind: "value",
            value: {
                kind: "unknown",
                context,
                deployedProgramCounter: deployedPc,
                constructorProgramCounter: constructorPc
            }
        };
    }
    //also before we continue: is the PC zero? if so let's just return that
    if (deployedPc === 0 && constructorPc === 0) {
        return {
            type: dataType,
            kind: "value",
            value: {
                kind: "exception",
                context,
                deployedProgramCounter: deployedPc,
                constructorProgramCounter: constructorPc
            }
        };
    }
    //another check: is only the deployed PC zero?
    if (deployedPc === 0 && constructorPc !== 0) {
        return {
            type: dataType,
            kind: "error",
            error: {
                kind: "MalformedInternalFunctionError",
                context,
                deployedProgramCounter: 0,
                constructorProgramCounter: constructorPc
            }
        };
    }
    //one last pre-check: is this a deployed-format pointer in a constructor?
    if (info.currentContext.isConstructor && constructorPc === 0) {
        return {
            type: dataType,
            kind: "error",
            error: {
                kind: "DeployedFunctionInConstructorError",
                context,
                deployedProgramCounter: deployedPc,
                constructorProgramCounter: 0
            }
        };
    }
    //otherwise, we get our function
    let pc = info.currentContext.isConstructor ? constructorPc : deployedPc;
    let functionEntry = info.internalFunctionsTable[pc];
    if (!functionEntry) {
        //if it's not zero and there's no entry... error!
        return {
            type: dataType,
            kind: "error",
            error: {
                kind: "NoSuchInternalFunctionError",
                context,
                deployedProgramCounter: deployedPc,
                constructorProgramCounter: constructorPc
            }
        };
    }
    if (functionEntry.isDesignatedInvalid) {
        return {
            type: dataType,
            kind: "value",
            value: {
                kind: "exception",
                context,
                deployedProgramCounter: deployedPc,
                constructorProgramCounter: constructorPc
            }
        };
    }
    let name = functionEntry.name;
    let mutability = functionEntry.mutability;
    let definedIn = Evm.Import.functionTableEntryToType(functionEntry); //may be null
    let id = Evm.Import.makeInternalFunctionId(functionEntry);
    return {
        type: dataType,
        kind: "value",
        value: {
            kind: "function",
            context,
            deployedProgramCounter: deployedPc,
            constructorProgramCounter: constructorPc,
            name,
            id,
            definedIn,
            mutability
        }
    };
}
exports.decodeInternalFunction = decodeInternalFunction;
function checkPadding(bytes, dataType, paddingMode, userDefinedTypes) {
    const length = allocate_1.byteLength(dataType, userDefinedTypes);
    let paddingType = getPaddingType(dataType, paddingMode);
    if (paddingMode === "permissive") {
        switch (dataType.typeClass) {
            case "bool":
            case "enum":
            case "function":
                //these three types are checked even in permissive mode
                return checkPaddingDirect(bytes, length, paddingType);
            default:
                return true;
        }
    }
    else {
        return checkPaddingDirect(bytes, length, paddingType);
    }
}
function removePadding(bytes, dataType, paddingMode, userDefinedTypes) {
    const length = allocate_1.byteLength(dataType, userDefinedTypes);
    const paddingType = getPaddingType(dataType, paddingMode);
    return removePaddingDirect(bytes, length, paddingType);
}
function removePaddingDirect(bytes, length, paddingType) {
    switch (paddingType) {
        case "left":
        case "signed":
            return bytes.slice(-length);
        case "right":
            return bytes.slice(0, length);
    }
}
function checkPaddingDirect(bytes, length, paddingType) {
    switch (paddingType) {
        case "left":
            return checkPaddingLeft(bytes, length);
        case "right":
            return checkPaddingRight(bytes, length);
        case "signed":
            return checkPaddingSigned(bytes, length);
    }
}
function getPaddingType(dataType, paddingMode) {
    switch (paddingMode) {
        case "right":
            return "right";
        case "default":
        case "permissive":
            return defaultPaddingType(dataType);
        case "zero":
            let defaultType = defaultPaddingType(dataType);
            return defaultType === "signed" ? "left" : defaultType;
    }
}
function defaultPaddingType(dataType) {
    switch (dataType.typeClass) {
        case "bytes":
            return "right";
        case "int":
        case "fixed":
            return "signed";
        case "function":
            if (dataType.visibility === "external") {
                return "right";
            }
        //otherwise, fall through to default
        default:
            return "left";
    }
}
function checkPaddingRight(bytes, length) {
    let padding = bytes.slice(length); //cut off the first length bytes
    return padding.every(paddingByte => paddingByte === 0);
}
//exporting this one for use in stack.ts
function checkPaddingLeft(bytes, length) {
    let padding = bytes.slice(0, -length); //cut off the last length bytes
    return padding.every(paddingByte => paddingByte === 0);
}
exports.checkPaddingLeft = checkPaddingLeft;
function checkPaddingSigned(bytes, length) {
    let padding = bytes.slice(0, -length); //padding is all but the last length bytes
    let value = bytes.slice(-length); //meanwhile the actual value is those last length bytes
    let signByte = value[0] & 0x80 ? 0xff : 0x00;
    return padding.every(paddingByte => paddingByte === signByte);
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 151561:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.encodeBasic = void 0;
const Conversion = __importStar(__webpack_require__(152714));
const Evm = __importStar(__webpack_require__(149218));
//UGH -- it turns out TypeScript can't handle nested tagged unions
//see: https://github.com/microsoft/TypeScript/issues/18758
//so, I'm just going to have to throw in a bunch of type coercions >_>
/**
 * Handles encoding of basic types; yes the input type is broader than
 * it should be but it's hard to fix this without causing other problems,
 * sorry!
 * @Category Encoding (low-level)
 */
function encodeBasic(input) {
    let bytes;
    switch (input.type.typeClass) {
        case "uint":
        case "int":
            return Conversion.toBytes(input.value.asBN, Evm.Utils.WORD_SIZE);
        case "enum":
            return Conversion.toBytes(input.value.numericAsBN, Evm.Utils.WORD_SIZE);
        case "bool": {
            bytes = new Uint8Array(Evm.Utils.WORD_SIZE); //is initialized to zeroes
            if (input.value.asBoolean) {
                bytes[Evm.Utils.WORD_SIZE - 1] = 1;
            }
            return bytes;
        }
        case "bytes":
            switch (input.type.kind) {
                //deliberately not handling dynamic case!
                case "static":
                    bytes = Conversion.toBytes(input.value.asHex);
                    let padded = new Uint8Array(Evm.Utils.WORD_SIZE); //initialized to zeroes
                    padded.set(bytes);
                    return padded;
            }
        case "address":
            return Conversion.toBytes(input.value.asAddress, Evm.Utils.WORD_SIZE);
        case "contract":
            return Conversion.toBytes(input.value.address, Evm.Utils.WORD_SIZE);
        case "function": {
            switch (input.type.visibility) {
                //for our purposes here, we will NOT count internal functions as a
                //basic type!  so no handling of internal case
                case "external":
                    let coercedInput = input;
                    let encoded = new Uint8Array(Evm.Utils.WORD_SIZE); //starts filled w/0s
                    let addressBytes = Conversion.toBytes(coercedInput.value.contract.address); //should already be correct length
                    let selectorBytes = Conversion.toBytes(coercedInput.value.selector); //should already be correct length
                    encoded.set(addressBytes);
                    encoded.set(selectorBytes, Evm.Utils.ADDRESS_SIZE); //set it after the address
                    return encoded;
            }
            break; //to satisfy TS
        }
        case "fixed":
        case "ufixed":
            let bigValue = (input).value.asBig;
            let shiftedValue = Conversion.shiftBigUp(bigValue, input.type.places);
            return Conversion.toBytes(shiftedValue, Evm.Utils.WORD_SIZE);
    }
}
exports.encodeBasic = encodeBasic;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 553928:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Allocate = exports.Encode = exports.Decode = void 0;
const Decode = __importStar(__webpack_require__(257939));
exports.Decode = Decode;
const Encode = __importStar(__webpack_require__(151561));
exports.Encode = Encode;
const Allocate = __importStar(__webpack_require__(849107));
exports.Allocate = Allocate;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 59495:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeString = exports.decodeBytes = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:bytes:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const errors_1 = __webpack_require__(672325);
const utf8_1 = __importDefault(__webpack_require__(957458));
function* decodeBytes(dataType, pointer, info, options = {}) {
    const { state } = info;
    const { strictAbiMode: strict } = options; //if this is undefined it'll still be falsy so OK
    let bytes;
    try {
        bytes = yield* read_1.default(pointer, state);
    }
    catch (error) {
        debug("segfault, pointer %o, state: %O", pointer, state);
        return errors_1.handleDecodingError(dataType, error, strict);
    }
    debug("type %O", dataType);
    debug("pointer %o", pointer);
    //note: this function does not check padding
    switch (dataType.typeClass) {
        case "bytes":
            //we assume this is a dynamic bytestring!
            //static ones should go to decodeBasic!
            return {
                type: dataType,
                kind: "value",
                value: {
                    asHex: Conversion.toHexString(bytes)
                }
            };
        case "string":
            return {
                type: dataType,
                kind: "value",
                value: decodeString(bytes)
            };
    }
}
exports.decodeBytes = decodeBytes;
function decodeString(bytes) {
    //the following line takes our UTF-8 string... and interprets each byte
    //as a UTF-16 bytepair.  Yikes!  Fortunately, we have a library to repair that.
    let badlyEncodedString = String.fromCharCode.apply(undefined, bytes);
    try {
        //this will throw an error if we have malformed UTF-8
        let correctlyEncodedString = utf8_1.default.decode(badlyEncodedString);
        //NOTE: we don't use node's builtin Buffer class to do the UTF-8 decoding
        //here, because that handles malformed UTF-8 by means of replacement characters
        //(U+FFFD).  That loses information.  So we use the utf8 package instead,
        //and... well, see the catch block below.
        return {
            kind: "valid",
            asString: correctlyEncodedString
        };
    }
    catch (_a) {
        //we're going to ignore the precise error and just assume it's because
        //the string was malformed (what else could it be?)
        let hexString = Conversion.toHexString(bytes);
        return {
            kind: "malformed",
            asHex: hexString
        };
    }
}
exports.decodeString = decodeString;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 553951:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.encodeBytes = void 0;
const Conversion = __importStar(__webpack_require__(152714));
const utf8_1 = __importDefault(__webpack_require__(957458));
//UGH -- it turns out TypeScript can't handle nested tagged unions
//see: https://github.com/microsoft/TypeScript/issues/18758
//so, I'm just going to have to throw in a bunch of type coercions >_>
/**
 * Encodes without padding, length, etc!
 *
 * @Category Encoding (low-level)
 */
function encodeBytes(input) {
    switch (input.type.typeClass) {
        case "bytes":
            return Conversion.toBytes(input.value.asHex);
        case "string": {
            let coercedInput = (input);
            switch (coercedInput.value.kind) {
                case "valid":
                    return stringToBytes(coercedInput.value.asString);
                case "malformed":
                    return Conversion.toBytes(coercedInput.value.asHex);
            }
        }
    }
}
exports.encodeBytes = encodeBytes;
/**
 * @Category Encoding (low-level)
 */
function stringToBytes(input) {
    input = utf8_1.default.encode(input);
    let bytes = new Uint8Array(input.length);
    for (let i = 0; i < input.length; i++) {
        bytes[i] = input.charCodeAt(i);
    }
    return bytes;
    //NOTE: this will throw an error if the string contained malformed UTF-16!
    //but, well, it shouldn't contain that...
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 767689:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Encode = exports.Decode = exports.Read = void 0;
const Read = __importStar(__webpack_require__(720281));
exports.Read = Read;
const Decode = __importStar(__webpack_require__(59495));
exports.Decode = Decode;
const Encode = __importStar(__webpack_require__(553951));
exports.Encode = Encode;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 720281:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readBytes = exports.readCode = void 0;
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
function* readCode(pointer, state) {
    let code = state.code;
    if (!code) {
        code = yield {
            type: "code",
            address: Evm.Utils.toAddress(state.specials.this)
        };
    }
    return readBytes(pointer, Object.assign(Object.assign({}, state), { code }));
}
exports.readCode = readCode;
function readBytes(pointer, state) {
    let sourceBytes = state[pointer.location];
    const { start: offset, length } = pointer;
    if (!Number.isSafeInteger(offset + length)) {
        throw new errors_1.DecodingError({
            kind: "ReadErrorBytes",
            location: pointer.location,
            start: offset,
            length
        });
    }
    // grab `length` bytes no matter what, here fill this array
    var bytes = new Uint8Array(length);
    bytes.fill(0); //fill it wil zeroes to start
    //if the start is beyond the end of the source, just return those 0s
    if (offset >= sourceBytes.length) {
        return bytes;
    }
    // if we're reading past the end of the source, truncate the length to read
    let excess = offset + length - sourceBytes.length;
    let readLength;
    if (excess > 0) {
        readLength = sourceBytes.length - offset;
    }
    else {
        readLength = length;
    }
    //get the (truncated) bytes
    let existing = new Uint8Array(sourceBytes.buffer, offset, readLength);
    //copy it into our buffer
    bytes.set(existing);
    return bytes;
}
exports.readBytes = readBytes;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 299987:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__webpack_require__(299147), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 299147:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.UnknownUserDefinedTypeError = void 0;
/**
 * This error indicates that the decoder was unable to locate a user-defined
 * type (struct, enum, or contract type) via its ID.  Unfortunately, we can't
 * always avoid this at the moment; we're hoping to make this more robust in
 * the future with Truffle DB.  In the meantime, it is at least worth noting that
 * you should not encounter this error if your entire project was written in
 * Solidity and all compiled at once.  Sorry.
 *
 * @Category Errors
 */
class UnknownUserDefinedTypeError extends Error {
    constructor(id, typeString) {
        const message = `Cannot locate definition for ${typeString} (ID ${id})`;
        super(message);
        this.name = "UnknownUserDefinedTypeError";
        this.id = id;
        this.typeString = typeString;
    }
}
exports.UnknownUserDefinedTypeError = UnknownUserDefinedTypeError;
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 89752:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = void 0;
__exportStar(__webpack_require__(309612), exports);
const Utils = __importStar(__webpack_require__(372972));
exports.Utils = Utils;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 309612:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 372972:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.simpleShimSourceMap = exports.getContractNode = exports.shimContracts = exports.shimArtifacts = exports.shimCompilation = exports.shimCompilations = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:compilations:utils");
function shimCompilations(inputCompilations, shimmedCompilationIdPrefix = "shimmedcompilation") {
    return inputCompilations.map((compilation, compilationIndex) => shimCompilation(compilation, `${shimmedCompilationIdPrefix}Number(${compilationIndex})`));
}
exports.shimCompilations = shimCompilations;
function shimCompilation(inputCompilation, shimmedCompilationId = "shimmedcompilation") {
    return Object.assign(Object.assign({}, shimContracts(inputCompilation.contracts, {
        files: inputCompilation.sourceIndexes,
        sources: inputCompilation.sources,
        shimmedCompilationId,
        compiler: inputCompilation.compiler
    })), { compiler: inputCompilation.compiler });
}
exports.shimCompilation = shimCompilation;
/**
 * wrapper around shimContracts that just returns
 * the result in a one-element array (keeping the old name
 * shimArtifacts for compatibility)
 */
function shimArtifacts(artifacts, files, shimmedCompilationId = "shimmedcompilation") {
    return [shimContracts(artifacts, { files, shimmedCompilationId })];
}
exports.shimArtifacts = shimArtifacts;
/**
 * shims a bunch of contracts ("artifacts", though not necessarily)
 * to a compilation.  usually used via one of the above functions.
 * Note: if you pass in options.sources, options.files will be ignored.
 * Note: if you pass in options.sources, sources will not have
 * compiler set unless you also pass in options.compiler; in this case
 * you should set that up separately, as in shimCompilation().
 */
function shimContracts(artifacts, options = {}) {
    const { files, sources: inputSources } = options;
    const shimmedCompilationId = options.shimmedCompilationId || "shimmedcompilation";
    let contracts = [];
    let sources = [];
    let unreliableSourceOrder = false;
    for (let artifact of artifacts) {
        let { contractName, bytecode, sourceMap, deployedBytecode, deployedSourceMap, immutableReferences, sourcePath, source, ast, abi, compiler, generatedSources, deployedGeneratedSources } = artifact;
        if (artifact.contract_name) {
            //just in case
            contractName = artifact.contract_name;
            //dunno what's up w/ the type of contract_name, but it needs coercing
        }
        debug("contractName: %s", contractName);
        let contractObject = {
            contractName,
            bytecode,
            sourceMap,
            deployedBytecode,
            deployedSourceMap,
            immutableReferences,
            abi,
            generatedSources: normalizeGeneratedSources(generatedSources, compiler),
            deployedGeneratedSources: normalizeGeneratedSources(deployedGeneratedSources, compiler),
            compiler
        };
        let sourceObject = {
            sourcePath,
            source,
            ast: ast,
            compiler,
            language: inferLanguage(ast, compiler, sourcePath)
        };
        //ast needs to be coerced because schema doesn't quite match our types here...
        //if files or sources was passed, trust that to determine the source index
        if (files || inputSources) {
            //note: we never set the unreliableSourceOrder flag in this branch;
            //we just trust files/sources.  If this info is bad, then, uh, too bad.
            const index = inputSources
                ? inputSources.findIndex(source => source.sourcePath === sourcePath)
                : files.indexOf(sourcePath);
            if (!inputSources) {
                //if inputSources was passed, we'll handle this separately below
                sourceObject.id = index.toString(); //HACK
                sources[index] = sourceObject;
            }
            contractObject.primarySourceId = index.toString(); //HACK
        }
        else {
            //if neither was passed, attempt to determine it from the ast
            let index;
            if (sourceObject.ast) {
                //note: this works for both Solidity and Vyper
                index = sourceIndexForAst(sourceObject.ast); //sourceObject.ast for typing reasons
            }
            else if (compiler && compiler.name === "vyper") {
                index = 0; //if it's Vyper but there's no AST, we can
                //assume that it was compiled alone and therefore has index 0
            }
            //if that didn't work, try the source map
            if (index === undefined && (sourceMap || deployedSourceMap)) {
                const sourceMapString = simpleShimSourceMap(deployedSourceMap || sourceMap);
                index = extractPrimarySource(sourceMapString);
            }
            //else leave undefined for now
            ({ index, unreliableSourceOrder } = getIndexToAddAt(sourceObject, index, sources, unreliableSourceOrder));
            if (index !== null) {
                //if we're in this case, inputSources was not passed
                sourceObject.id = index.toString(); //HACK
                sources[index] = sourceObject;
                contractObject.primarySourceId = index.toString();
            }
        }
        contracts.push(contractObject);
    }
    //now: check for id overlap with internal sources
    //(don't bother if inputSources or files was passed)
    if (!inputSources && !files) {
        for (let contract of contracts) {
            const { generatedSources, deployedGeneratedSources } = contract;
            for (let index in generatedSources) {
                if (index in sources) {
                    unreliableSourceOrder = true;
                }
            }
            for (let index in deployedGeneratedSources) {
                if (index in sources) {
                    unreliableSourceOrder = true;
                }
            }
        }
    }
    let compiler;
    if (options.compiler) {
        compiler = options.compiler;
    }
    else if (!unreliableSourceOrder && contracts.length > 0) {
        //if things were actually compiled together, we should just be able
        //to pick an arbitrary one
        compiler = contracts[0].compiler;
    }
    //if input sources was passed, set up the sources object directly :)
    if (inputSources) {
        sources = inputSources.map(({ sourcePath, contents: source, ast, language }, index) => ({
            sourcePath,
            source,
            ast: ast,
            language,
            id: index.toString(),
            compiler //redundant but let's include it
        }));
    }
    return {
        id: shimmedCompilationId,
        unreliableSourceOrder,
        sources,
        contracts,
        compiler
    };
}
exports.shimContracts = shimContracts;
//note: this works for Vyper too!
function sourceIndexForAst(ast) {
    if (Array.isArray(ast)) {
        //special handling for old Vyper versions
        ast = ast[0];
    }
    if (!ast) {
        return undefined;
    }
    return parseInt(ast.src.split(":")[2]);
    //src is given as start:length:file.
    //we want just the file.
}
function getContractNode(contract, compilation) {
    const { contractName, sourceMap, deployedSourceMap, primarySourceId } = contract;
    const { unreliableSourceOrder, sources } = compilation;
    let sourcesToCheck;
    //we will attempt to locate the primary source;
    //if we can't find it, we'll just check every source in this
    //compilation.
    if (primarySourceId !== undefined) {
        sourcesToCheck = [
            sources.find(source => source && source.id === primarySourceId)
        ];
    }
    else if (!unreliableSourceOrder && (deployedSourceMap || sourceMap)) {
        const sourceMapString = simpleShimSourceMap(deployedSourceMap || sourceMap);
        let sourceId = extractPrimarySource(sourceMapString);
        sourcesToCheck = [sources[sourceId]];
    }
    else {
        //WARNING: if we end up in this case, we could get the wrong contract!
        //(but we shouldn't end up here)
        sourcesToCheck = sources;
    }
    return sourcesToCheck.reduce((foundNode, source) => {
        if (foundNode || !source) {
            return foundNode;
        }
        if (!source.ast || source.language !== "Solidity") {
            //ignore non-Solidity ASTs for now, we don't support them yet
            return undefined;
        }
        return source.ast.nodes.find(node => node.nodeType === "ContractDefinition" && node.name === contractName);
    }, undefined);
}
exports.getContractNode = getContractNode;
/**
 * extract the primary source from a source map
 * (i.e., the source for the first instruction, found
 * between the second and third colons)
 */
function extractPrimarySource(sourceMap) {
    if (!sourceMap) {
        //HACK?
        return 0; //in this case (e.g. a Vyper contract with an old-style
        //source map) we infer that it was compiled by itself
    }
    return parseInt(sourceMap.match(/^[^:]*:[^:]*:([^:]*):/)[1] || "0");
}
function normalizeGeneratedSources(generatedSources, compiler) {
    if (!generatedSources) {
        return [];
    }
    if (!isGeneratedSources(generatedSources)) {
        return generatedSources; //if already normalizeed, leave alone
    }
    let sources = []; //output
    for (let source of generatedSources) {
        sources[source.id] = {
            id: source.id.toString(),
            sourcePath: source.name,
            source: source.contents,
            //ast needs to be coerced because schema doesn't quite match our types here...
            ast: source.ast,
            compiler: compiler,
            language: source.language
        };
    }
    return sources;
}
//HACK
function isGeneratedSources(sources) {
    //note: for some reason arr.includes(undefined) returns true on sparse arrays
    //if sources.length === 0, it's ambiguous; we'll exclude it as not needing normalization
    return (sources.length > 0 &&
        !sources.includes(undefined) &&
        (sources[0].contents !== undefined ||
            sources[0].name !== undefined));
}
//HACK, maybe?
function inferLanguage(ast, compiler, sourcePath) {
    if (ast) {
        if (ast.nodeType === "SourceUnit") {
            return "Solidity";
        }
        else if (ast.nodeType && ast.nodeType.startsWith("Yul")) {
            //Every Yul source I've seen has YulBlock as the root, but
            //I'm not sure that that's *always* the case
            return "Yul";
        }
        else if (Array.isArray(ast) || ast.ast_type === "Module") {
            return "Vyper";
        }
    }
    else if (compiler) {
        if (compiler.name === "vyper") {
            return "Vyper";
        }
        else if (compiler.name === "solc") {
            if (sourcePath.endsWith(".yul")) {
                return "Yul";
            }
            else {
                return "Solidity";
            }
        }
        else {
            return undefined;
        }
    }
    else {
        return undefined;
    }
}
function getIndexToAddAt(sourceObject, index, sources, unreliableSourceOrder) {
    //first: is this already there? only add it if it's not.
    //(we determine this by sourcePath if present, and the actual source
    //contents if not)
    debug("sourcePath: %s", sourceObject.sourcePath);
    debug("given index: %d", index);
    debug("sources: %o", sources.map(source => source.sourcePath));
    if (sources.every(existingSource => existingSource.sourcePath !== sourceObject.sourcePath ||
        (!sourceObject.sourcePath &&
            !existingSource.sourcePath &&
            existingSource.source !== sourceObject.source))) {
        if (unreliableSourceOrder || index === undefined || index in sources) {
            //if we can't add it at the correct spot, set the
            //unreliable source order flag
            debug("collision!");
            unreliableSourceOrder = true;
        }
        //otherwise, just leave things alone
        if (unreliableSourceOrder) {
            //in case of unreliable source order, we'll ignore what indices
            //things are *supposed* to have and just append things to the end
            index = sources.length;
        }
        return {
            index,
            unreliableSourceOrder
        };
    }
    else {
        //return index: null indicates don't add this because it's
        //already present
        debug("already present, not adding");
        return {
            index: null,
            unreliableSourceOrder
        };
    }
}
/**
 * convert Vyper source maps to solidity ones
 * (note we won't bother handling the case where the compressed
 * version doesn't exist; that will have to wait for a later version)
 */
function simpleShimSourceMap(sourceMap) {
    if (sourceMap === undefined) {
        return undefined; //undefined case
    }
    else if (typeof sourceMap === "object") {
        return sourceMap.pc_pos_map_compressed; //Vyper object case
    }
    else {
        try {
            return JSON.parse(sourceMap).pc_pos_map_compressed; //Vyper JSON case
        }
        catch (_) {
            return sourceMap; //Solidity case
        }
    }
}
exports.simpleShimSourceMap = simpleShimSourceMap;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 884159:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = void 0;
__exportStar(__webpack_require__(716041), exports);
const Utils = __importStar(__webpack_require__(919228));
exports.Utils = Utils;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 716041:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 919228:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.solidityFamily = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:compiler:utils");
const semver_1 = __importDefault(__webpack_require__(266781));
function solidityFamily(compiler) {
    if (!compiler || compiler.name !== "solc") {
        return "unknown";
    }
    if (semver_1.default.satisfies(compiler.version, "~0.8 || >=0.8.0", {
        includePrerelease: true
    })) {
        //see comment below about the weird-looking condition
        return "0.8.x";
    }
    else if (semver_1.default.satisfies(compiler.version, "~0.5 || >=0.5.0", {
        includePrerelease: true
    })) {
        //what's with this weird-looking condition?  Well, I want to be sure to include
        //prerelease versions of 0.5.0.  But isn't that what the includePrerelease option
        //does?  No!  That just makes it so that prerelease versions can be included at
        //all; without that, all prereleases of *any* version of Solidity can be excluded.
        //A prerelease version of 0.5.0 still wouldn't satisfy >=0.5.0, so I added in ~0.5
        //as well, which they do satisfy.
        return "0.5.x";
    }
    else {
        return "pre-0.5.0";
    }
}
exports.solidityFamily = solidityFamily;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 560013:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.makeTypeId = exports.contextToType = void 0;
function contextToType(context) {
    if (context.contractId !== undefined) {
        return {
            typeClass: "contract",
            kind: "native",
            id: makeTypeId(context.contractId, context.compilationId),
            typeName: context.contractName,
            contractKind: context.contractKind,
            payable: context.payable
        };
    }
    else {
        return {
            typeClass: "contract",
            kind: "foreign",
            typeName: context.contractName,
            contractKind: context.contractKind,
            payable: context.payable
        };
    }
}
exports.contextToType = contextToType;
//NOTE: I am exporting this for use in other import functions, but please don't
//use this elsewhere!
//If you have to make a type ID, instead make the type and then
//take its ID.
function makeTypeId(astId, compilationId) {
    return `${compilationId}:${astId}`;
}
exports.makeTypeId = makeTypeId;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 697938:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = exports.Import = void 0;
__exportStar(__webpack_require__(642986), exports);
const Import = __importStar(__webpack_require__(560013));
exports.Import = Import;
const Utils = __importStar(__webpack_require__(381099));
exports.Utils = Utils;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 642986:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 381099:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.normalizeContexts = exports.matchContext = exports.findContext = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:contexts:utils");
const Evm = __importStar(__webpack_require__(149218));
const lodash_escaperegexp_1 = __importDefault(__webpack_require__(91658));
const cbor = __importStar(__webpack_require__(82141));
function findContext(contexts, binary) {
    const matchingContexts = Object.values(contexts).filter(context => matchContext(context, binary));
    //rather than just pick an arbitrary matching context, we're going
    //to pick one that isn't a descendant of any of the others.
    //(if there are multiple of *those*, then yeah it's arbitrary.)
    const context = matchingContexts.find(descendant => !matchingContexts.some(ancestor => descendant.compilationId === ancestor.compilationId &&
        descendant.linearizedBaseContracts &&
        ancestor.contractId !== undefined &&
        descendant.linearizedBaseContracts
            .slice(1)
            .includes(ancestor.contractId)
    //we do slice one because everything is an an ancestor of itself; we only
    //care about *proper* ancestors
    ));
    return context || null;
}
exports.findContext = findContext;
function matchContext(context, givenBinary) {
    let { binary, isConstructor } = context;
    let lengthDifference = givenBinary.length - binary.length;
    //first: if it's not a constructor, they'd better be equal in length.
    //if it is a constructor, the given binary must be at least as long,
    //and the difference must be a multiple of 64
    if ((!isConstructor && lengthDifference !== 0) ||
        lengthDifference < 0 ||
        lengthDifference % (2 * Evm.Utils.WORD_SIZE) !== 0) {
        return false;
    }
    for (let i = 0; i < binary.length; i++) {
        //note: using strings like arrays is kind of dangerous in general in JS,
        //but everything here is ASCII so it's fine
        //note that we need to compare case-insensitive, since Solidity will
        //put addresses in checksum case in the compiled source
        //(we don't actually need that second toLowerCase(), but whatever)
        if (binary[i] !== "." &&
            binary[i].toLowerCase() !== givenBinary[i].toLowerCase()) {
            return false;
        }
    }
    return true;
}
exports.matchContext = matchContext;
function normalizeContexts(contexts) {
    //unfortunately, due to our current link references format, we can't
    //really use the binary from the artifact directly -- neither for purposes
    //of matching, nor for purposes of decoding internal functions.  So, we
    //need to perform this normalization step on our contexts before using
    //them.  Once we have truffle-db, this step should largely go away.
    debug("normalizing contexts");
    //first, let's clone the input
    //(let's do a 2-deep clone because we'll be altering binary)
    let newContexts = Object.assign({}, ...Object.entries(contexts).map(([contextHash, context]) => ({
        [contextHash]: Object.assign({}, context)
    })));
    debug("contexts cloned");
    //next, we get all the library names and sort them descending by length.
    //We're going to want to go in descending order of length so that we
    //don't run into problems when one name is a substring of another.
    //For simplicity, we'll exclude names of length <38, because we can
    //handle these with our more general check for link references at the end
    const fillerLength = 2 * Evm.Utils.ADDRESS_SIZE;
    let names = Object.values(newContexts)
        .filter(context => context.contractKind === "library")
        .map(context => context.contractName)
        .filter(name => name.length >= fillerLength - 3)
        //the -3 is for 2 leading underscores and 1 trailing
        .sort((name1, name2) => name2.length - name1.length);
    debug("names sorted");
    //now, we need to turn all these names into regular expressions, because,
    //unfortunately, str.replace() will only replace all if you use a /g regexp;
    //note that because names may contain '$', we need to escape them
    //(also we prepend "__" because that's the placeholder format)
    let regexps = names.map(name => new RegExp(lodash_escaperegexp_1.default("__" + name), "g"));
    debug("regexps prepared");
    //having done so, we can do the replace for these names!
    const replacement = ".".repeat(fillerLength);
    for (let regexp of regexps) {
        for (let context of Object.values(newContexts)) {
            context.binary = context.binary.replace(regexp, replacement);
        }
    }
    debug("long replacements complete");
    //now we can do a generic replace that will catch all names of length
    //<40, while also catching the Solidity compiler's link reference format
    //as well as Truffle's.  Hooray!
    const genericRegexp = new RegExp("_.{" + (fillerLength - 2) + "}_", "g");
    //we're constructing the regexp /_.{38}_/g, but I didn't want to use a
    //literal 38 :P
    for (let context of Object.values(newContexts)) {
        context.binary = context.binary.replace(genericRegexp, replacement);
    }
    debug("short replacements complete");
    //now we must handle the delegatecall guard -- libraries' deployedBytecode will include
    //0s in place of their own address instead of a link reference at the
    //beginning, so we need to account for that too
    const pushAddressInstruction = (0x60 + Evm.Utils.ADDRESS_SIZE - 1).toString(16); //"73"
    for (let context of Object.values(newContexts)) {
        if (context.contractKind === "library" && !context.isConstructor) {
            context.binary = context.binary.replace("0x" + pushAddressInstruction + "00".repeat(Evm.Utils.ADDRESS_SIZE), "0x" + pushAddressInstruction + replacement);
        }
    }
    debug("extra library replacements complete");
    //now let's handle immutable references
    //(these are much nicer than link references due to not having to deal with the old format)
    for (let context of Object.values(newContexts)) {
        if (context.immutableReferences) {
            for (let variable of Object.values(context.immutableReferences)) {
                for (let { start, length } of (variable)) {
                    //Goddammit TS
                    let lowerStringIndex = 2 + 2 * start;
                    let upperStringIndex = 2 + 2 * (start + length);
                    context.binary =
                        context.binary.slice(0, lowerStringIndex) +
                            "..".repeat(length) +
                            context.binary.slice(upperStringIndex);
                }
            }
        }
    }
    debug("immutables complete");
    //one last step: where there's CBOR with a metadata hash, we'll allow the
    //CBOR to vary, aside from the length (note: ideally here we would *only*
    //dot-out the metadata hash part of the CBOR, but, well, it's not worth the
    //trouble to detect that; doing that could potentially get pretty involved)
    //note that if the code isn't Solidity, that's fine -- we just won't get
    //valid CBOR and will not end up adding to our list of regular expressions
    const externalCborInfo = Object.values(newContexts)
        .map(context => extractCborInfo(context.binary))
        .filter(cborSegment => cborSegment !== null && isCborWithHash(cborSegment.cbor));
    const cborRegexps = externalCborInfo.map(cborInfo => ({
        input: new RegExp(cborInfo.cborSegment, "g"),
        output: "..".repeat(cborInfo.cborLength) + cborInfo.cborLengthHex
    }));
    //HACK: we will replace *every* occurrence of *every* external CBOR occurring
    //in *every* context, in order to cover created contracts (including if there
    //are multiple or recursive ones)
    for (let context of Object.values(newContexts)) {
        for (let { input, output } of cborRegexps) {
            context.binary = context.binary.replace(input, output);
        }
    }
    debug("external wildcards complete");
    //finally, return this mess!
    return newContexts;
}
exports.normalizeContexts = normalizeContexts;
function extractCborInfo(binary) {
    debug("extracting cbor segement of %s", binary);
    const lastTwoBytes = binary.slice(2).slice(-2 * 2); //2 bytes * 2 for hex
    //the slice(2) there may seem unnecessary; it's to handle the possibility that the contract
    //has less than two bytes in its bytecode (that won't happen with Solidity, but let's be
    //certain)
    if (lastTwoBytes.length < 2 * 2) {
        return null; //don't try to handle this case!
    }
    const cborLength = parseInt(lastTwoBytes, 16);
    const cborEnd = binary.length - 2 * 2;
    const cborStart = cborEnd - cborLength * 2;
    //sanity check
    if (cborStart < 2) {
        //"0x"
        return null; //don't try to handle this case!
    }
    const cbor = binary.slice(cborStart, cborEnd);
    return {
        cborStart,
        cborLength,
        cborEnd,
        cborLengthHex: lastTwoBytes,
        cbor,
        cborSegment: cbor + lastTwoBytes
    };
}
function isCborWithHash(encoded) {
    debug("checking cbor, encoed: %s", encoded);
    let decoded;
    try {
        //note this *will* throw if there's data left over,
        //which is what we want it to do
        decoded = cbor.decodeFirstSync(encoded);
    }
    catch (_a) {
        debug("invalid cbor!");
        return false;
    }
    debug("decoded: %O", decoded);
    if (typeof decoded !== "object") {
        return false;
    }
    //borc sometimes returns maps and sometimes objects,
    //so let's make things consistent by converting to a map
    if (!(decoded instanceof Map)) {
        decoded = new Map(Object.entries(decoded));
    }
    const hashKeys = ["bzzr0", "bzzr1", "ipfs"];
    return hashKeys.some(key => decoded.has(key));
}
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 152714:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cleanBool = exports.countDecimalPlaces = exports.shiftBigDown = exports.shiftBigUp = exports.toBytes = exports.toHexString = exports.toBig = exports.toBigInt = exports.toSignedBN = exports.toBN = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:conversion");
const bn_js_1 = __importDefault(__webpack_require__(213550));
const big_js_1 = __importDefault(__webpack_require__(351888));
/**
 * @param bytes - undefined | string | number | BN | Uint8Array | Big
 * @return {BN}
 */
function toBN(bytes) {
    if (bytes === undefined) {
        return undefined;
    }
    else if (typeof bytes == "string") {
        return new bn_js_1.default(bytes, 16);
    }
    else if (typeof bytes == "number" || bn_js_1.default.isBN(bytes)) {
        return new bn_js_1.default(bytes);
    }
    else if (bytes instanceof big_js_1.default) {
        return new bn_js_1.default(bytes.toFixed()); //warning, better hope input is integer!
        //note: going through string may seem silly but it's actually not terrible here,
        //since BN is binary-based and Big is decimal-based
        //[toFixed is like toString except it guarantees scientific notation is not used]
    }
    else if (typeof bytes.reduce === "function") {
        return bytes.reduce((num, byte) => num.shln(8).addn(byte), new bn_js_1.default(0));
    }
}
exports.toBN = toBN;
/**
 * @param bytes - Uint8Array
 * @return {BN}
 */
function toSignedBN(bytes) {
    if (bytes[0] < 0x80) {
        // if first bit is 0
        return toBN(bytes);
    }
    else {
        return toBN(bytes.map(b => 0xff - b))
            .addn(1)
            .neg();
    }
}
exports.toSignedBN = toSignedBN;
function toBigInt(value) {
    //BN is binary-based, so we convert by means of a hex string in order
    //to avoid having to do a binary-decimal conversion and back :P
    return !value.isNeg()
        ? BigInt("0x" + value.toString(16))
        : -BigInt("0x" + value.neg().toString(16)); //can't directly make negative BigInt from hex string
}
exports.toBigInt = toBigInt;
function toBig(value) {
    //note: going through string may seem silly but it's actually not terrible here,
    //since BN (& number) is binary-based and Big is decimal-based
    return new big_js_1.default(value.toString());
}
exports.toBig = toBig;
/**
 * @param bytes - Uint8Array | BN
 * @param padLength - number - minimum desired byte length (left-pad with zeroes)
 * @return {string}
 */
function toHexString(bytes, padLength = 0) {
    if (bn_js_1.default.isBN(bytes)) {
        bytes = toBytes(bytes);
    }
    const pad = (s) => `${"00".slice(0, 2 - s.length)}${s}`;
    //                                          0  1  2  3  4
    //                                 0  1  2  3  4  5  6  7
    // bytes.length:        5  -  0x(          e5 c2 aa 09 11 )
    // length (preferred):  8  -  0x( 00 00 00 e5 c2 aa 09 11 )
    //                                `--.---'
    //                                     offset 3
    if (bytes.length < padLength) {
        let prior = bytes;
        bytes = new Uint8Array(padLength);
        bytes.set(prior, padLength - prior.length);
    }
    debug("bytes: %o", bytes);
    let string = bytes.reduce((str, byte) => `${str}${pad(byte.toString(16))}`, "");
    return `0x${string}`;
}
exports.toHexString = toHexString;
function toBytes(data, length = 0) {
    //note that length is a minimum output length
    //strings will be 0-padded on left
    //numbers/BNs will be sign-padded on left
    //NOTE: if a number/BN is passed in that is too big for the given length,
    //you will get an error!
    //(note that strings passed in should be hex strings; this is not for converting
    //generic strings to hex)
    if (typeof data === "string") {
        let hex = data; //renaming for clarity
        if (hex.startsWith("0x")) {
            hex = hex.slice(2);
        }
        if (hex === "") {
            //this special case is necessary because the match below will return null,
            //not an empty array, when given an empty string
            return new Uint8Array(0);
        }
        if (hex.length % 2 == 1) {
            hex = `0${hex}`;
        }
        let bytes = new Uint8Array(hex.match(/.{2}/g).map(byte => parseInt(byte, 16)));
        if (bytes.length < length) {
            let prior = bytes;
            bytes = new Uint8Array(length);
            bytes.set(prior, length - prior.length);
        }
        return bytes;
    }
    else {
        // BN/Big/number case
        if (typeof data === "number") {
            data = new bn_js_1.default(data);
        }
        else if (data instanceof big_js_1.default) {
            //note: going through string may seem silly but it's actually not terrible here,
            //since BN is binary-based and Big is decimal-based
            data = new bn_js_1.default(data.toFixed());
            //[toFixed is like toString except it guarantees scientific notation is not used]
        }
        //note that the argument for toTwos is given in bits
        return data.toTwos(length * 8).toArrayLike(Uint8Array, "be", length);
        //big-endian
    }
}
exports.toBytes = toBytes;
//computes value * 10**decimalPlaces
function shiftBigUp(value, decimalPlaces) {
    let newValue = new big_js_1.default(value);
    newValue.e += decimalPlaces;
    return newValue;
}
exports.shiftBigUp = shiftBigUp;
//computes value * 10**-decimalPlaces
function shiftBigDown(value, decimalPlaces) {
    let newValue = new big_js_1.default(value);
    newValue.e -= decimalPlaces;
    return newValue;
}
exports.shiftBigDown = shiftBigDown;
//we don't need this yet, but we will eventually
function countDecimalPlaces(value) {
    return Math.max(0, value.c.length - value.e - 1);
}
exports.countDecimalPlaces = countDecimalPlaces;
//converts out of range booleans to true; something of a HACK
//NOTE: does NOT do this recursively inside structs, arrays, etc!
//I mean, those aren't elementary and therefore aren't in the domain
//anyway, but still
function cleanBool(result) {
    switch (result.kind) {
        case "value":
            return result;
        case "error":
            switch (result.error.kind) {
                case "BoolOutOfRangeError":
                    //return true
                    return {
                        type: result.type,
                        kind: "value",
                        value: {
                            asBoolean: true
                        }
                    };
                default:
                    return result;
            }
    }
}
exports.cleanBool = cleanBool;
//# sourceMappingURL=conversion.js.map

/***/ }),

/***/ 632561:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeRevert = exports.decodeReturndata = exports.decodeEvent = exports.decodeCalldata = exports.decodeVariable = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:core");
const Ast = __importStar(__webpack_require__(114442));
const AbiData = __importStar(__webpack_require__(20907));
const Topic = __importStar(__webpack_require__(963196));
const Evm = __importStar(__webpack_require__(149218));
const Contexts = __importStar(__webpack_require__(697938));
const abify_1 = __webpack_require__(57320);
const Conversion = __importStar(__webpack_require__(152714));
const errors_1 = __webpack_require__(672325);
const read_1 = __importDefault(__webpack_require__(887534));
const decode_1 = __importDefault(__webpack_require__(237478));
// untyped import since no @types/web3-utils exists
const Web3Utils = __webpack_require__(118269);
/**
 * @Category Decoding
 */
function* decodeVariable(definition, pointer, info, compilationId) {
    let compiler = info.currentContext.compiler;
    let dataType = Ast.Import.definitionToType(definition, compilationId, compiler);
    return yield* decode_1.default(dataType, pointer, info); //no need to pass an offset
}
exports.decodeVariable = decodeVariable;
/**
 * @Category Decoding
 */
function* decodeCalldata(info, isConstructor //ignored if context! trust context instead if have
) {
    const context = info.currentContext;
    if (context === null) {
        //if we don't know the contract ID, we can't decode
        if (isConstructor) {
            return {
                kind: "create",
                decodingMode: "full",
                bytecode: Conversion.toHexString(info.state.calldata)
            };
        }
        else {
            return {
                kind: "unknown",
                decodingMode: "full",
                data: Conversion.toHexString(info.state.calldata)
            };
        }
    }
    const contextHash = context.context;
    const contractType = Contexts.Import.contextToType(context);
    isConstructor = context.isConstructor;
    const allocations = info.allocations.calldata;
    let allocation;
    let selector;
    //first: is this a creation call?
    if (isConstructor) {
        allocation = (allocations.constructorAllocations[contextHash] || { input: undefined }).input;
    }
    else {
        //skipping any error-handling on this read, as a calldata read can't throw anyway
        let rawSelector = yield* read_1.default({
            location: "calldata",
            start: 0,
            length: Evm.Utils.SELECTOR_SIZE
        }, info.state);
        selector = Conversion.toHexString(rawSelector);
        allocation = ((allocations.functionAllocations[contextHash] || {})[selector] || {
            input: undefined
        }).input;
    }
    if (allocation === undefined) {
        let abiEntry = null;
        if (info.state.calldata.length === 0) {
            //to hell with reads, let's just be direct
            abiEntry = context.fallbackAbi.receive || context.fallbackAbi.fallback;
        }
        else {
            abiEntry = context.fallbackAbi.fallback;
        }
        return {
            kind: "message",
            class: contractType,
            abi: abiEntry,
            data: Conversion.toHexString(info.state.calldata),
            decodingMode: "full"
        };
    }
    let decodingMode = allocation.allocationMode; //starts out this way, degrades to ABI if necessary
    debug("calldata decoding mode: %s", decodingMode);
    //you can't map with a generator, so we have to do this map manually
    let decodedArguments = [];
    for (const argumentAllocation of allocation.arguments) {
        let value;
        let dataType = decodingMode === "full"
            ? argumentAllocation.type
            : abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes);
        try {
            value = yield* decode_1.default(dataType, argumentAllocation.pointer, info, {
                abiPointerBase: allocation.offset,
                allowRetry: decodingMode === "full"
            });
        }
        catch (error) {
            if (error instanceof errors_1.StopDecodingError &&
                error.allowRetry &&
                decodingMode === "full") {
                debug("problem! retrying as ABI");
                debug("error: %O", error);
                //if a retry happens, we've got to do several things in order to switch to ABI mode:
                //1. mark that we're switching to ABI mode;
                decodingMode = "abi";
                //2. abify all previously decoded values;
                decodedArguments = decodedArguments.map(argumentDecoding => (Object.assign(Object.assign({}, argumentDecoding), { value: abify_1.abifyResult(argumentDecoding.value, info.userDefinedTypes) })));
                //3. retry this particular decode in ABI mode.
                //(no try/catch on this one because we can't actually handle errors here!
                //not that they should be occurring)
                value = yield* decode_1.default(abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes), //type is now abified!
                argumentAllocation.pointer, info, {
                    abiPointerBase: allocation.offset
                });
                //4. the remaining parameters will then automatically be decoded in ABI mode due to (1),
                //so we don't need to do anything special there.
            }
            else {
                //we shouldn't be getting other exceptions, but if we do, we don't know
                //how to handle them, so uhhhh just rethrow I guess??
                throw error;
            }
        }
        const name = argumentAllocation.name;
        decodedArguments.push(name //deliberate general falsiness test
            ? { name, value }
            : { value });
    }
    if (isConstructor) {
        return {
            kind: "constructor",
            class: contractType,
            arguments: decodedArguments,
            abi: allocation.abi,
            bytecode: Conversion.toHexString(info.state.calldata.slice(0, allocation.offset)),
            decodingMode
        };
    }
    else {
        return {
            kind: "function",
            class: contractType,
            abi: allocation.abi,
            arguments: decodedArguments,
            selector,
            decodingMode
        };
    }
}
exports.decodeCalldata = decodeCalldata;
/**
 * @Category Decoding
 */
function* decodeEvent(info, address, options = {}) {
    const allocations = info.allocations.event;
    const extras = options.extras || "off";
    let rawSelector;
    let selector;
    let contractAllocations; //for non-anonymous events
    let libraryAllocations; //similar
    let contractAnonymousAllocations;
    let libraryAnonymousAllocations;
    const topicsCount = info.state.eventtopics.length;
    //yeah, it's not great to read directly from the state like this (bypassing read), but what are you gonna do?
    if (allocations[topicsCount]) {
        if (topicsCount > 0) {
            rawSelector = yield* read_1.default({
                location: "eventtopic",
                topic: 0
            }, info.state);
            selector = Conversion.toHexString(rawSelector);
            if (allocations[topicsCount].bySelector[selector]) {
                ({
                    contract: contractAllocations,
                    library: libraryAllocations
                } = allocations[topicsCount].bySelector[selector]);
            }
            else {
                debug("no allocations for that selector!");
                contractAllocations = {};
                libraryAllocations = {};
            }
        }
        else {
            //if we don't have a selector, it means we don't have any non-anonymous events
            contractAllocations = {};
            libraryAllocations = {};
        }
        //now: let's get our allocations for anonymous events
        ({
            contract: contractAnonymousAllocations,
            library: libraryAnonymousAllocations
        } = allocations[topicsCount].anonymous);
    }
    else {
        //if there's not even an allocation for the topics count, we can't
        //decode; we could do this the honest way of setting all four allocation
        //objects to {}, but let's just short circuit
        debug("no allocations for that topic count!");
        return [];
    }
    //now: what contract are we (probably) dealing with? let's get its code to find out
    const codeBytes = yield {
        type: "code",
        address
    };
    const codeAsHex = Conversion.toHexString(codeBytes);
    const contractContext = Contexts.Utils.findContext(info.contexts, codeAsHex);
    let possibleContractAllocations; //excludes anonymous events
    let possibleContractAnonymousAllocations;
    let possibleExtraAllocations; //excludes anonymous events
    let possibleExtraAnonymousAllocations;
    const emittingContextHash = (contractContext || { context: undefined })
        .context;
    if (emittingContextHash) {
        //if we found the contract, maybe it's from that contract
        const contractAllocation = contractAllocations[emittingContextHash];
        const contractAnonymousAllocation = contractAnonymousAllocations[emittingContextHash];
        possibleContractAllocations = contractAllocation || [];
        possibleContractAnonymousAllocations = contractAnonymousAllocation || [];
        //also, we need to set up the extras (everything that's from a
        //non-library contract but *not* this one)
        possibleExtraAllocations = [].concat(...Object.entries(contractAllocations)
            .filter(([key, _]) => key !== emittingContextHash)
            .map(([_, value]) => value));
        possibleExtraAnonymousAllocations = [].concat(...Object.entries(contractAnonymousAllocations)
            .filter(([key, _]) => key !== emittingContextHash)
            .map(([_, value]) => value));
    }
    else {
        //if we couldn't determine the contract, well, we have to assume it's from a library
        debug("couldn't find context");
        possibleContractAllocations = [];
        possibleContractAnonymousAllocations = [];
        //or it's an extra, which could be any of the contracts
        possibleExtraAllocations = [].concat(...Object.values(contractAllocations));
        possibleExtraAnonymousAllocations = [].concat(...Object.values(contractAnonymousAllocations));
    }
    //now we get all the library allocations!
    const possibleLibraryAllocations = [].concat(...Object.values(libraryAllocations));
    const possibleLibraryAnonymousAllocations = [].concat(...Object.values(libraryAnonymousAllocations));
    //now we put it all together!
    const possibleAllocations = possibleContractAllocations.concat(possibleLibraryAllocations);
    const possibleAnonymousAllocations = possibleContractAnonymousAllocations.concat(possibleLibraryAnonymousAllocations);
    const possibleAllocationsTotalMinusExtras = possibleAllocations.concat(possibleAnonymousAllocations);
    //...and also there's the extras
    const possibleExtraAllocationsTotal = possibleExtraAllocations.concat(possibleExtraAnonymousAllocations);
    const possibleAllocationsTotal = possibleAllocationsTotalMinusExtras.concat([null], //HACK: add sentinel value before the extras
    possibleExtraAllocationsTotal);
    //whew!
    let decodings = [];
    allocationAttempts: for (const allocation of possibleAllocationsTotal) {
        debug("trying allocation: %O", allocation);
        //first: check for our sentinel value for extras (yeah, kind of HACKy)
        if (allocation === null) {
            switch (extras) {
                case "on":
                    continue allocationAttempts; //ignore the sentinel and continue
                case "off":
                    break allocationAttempts; //don't include extras; stop here
                case "necessary":
                    //stop on the sentinel and exclude extras *unless* there are no decodings yet
                    if (decodings.length > 0) {
                        break allocationAttempts;
                    }
                    else {
                        continue allocationAttempts;
                    }
            }
        }
        //second: do a name check so we can skip decoding if name is wrong
        //(this will likely be a more detailed check in the future)
        if (options.name !== undefined && allocation.abi.name !== options.name) {
            continue;
        }
        //now: the main part!
        let decodingMode = allocation.allocationMode; //starts out here; degrades to abi if necessary
        const contextHash = allocation.contextHash;
        const attemptContext = info.contexts[contextHash];
        const emittingContractType = Contexts.Import.contextToType(attemptContext);
        const contractType = allocation.definedIn;
        //you can't map with a generator, so we have to do this map manually
        let decodedArguments = [];
        for (const argumentAllocation of allocation.arguments) {
            let value;
            //if in full mode, use the allocation's listed data type.
            //if in ABI mode, abify it before use.
            let dataType = decodingMode === "full"
                ? argumentAllocation.type
                : abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes);
            try {
                value = yield* decode_1.default(dataType, argumentAllocation.pointer, info, {
                    strictAbiMode: true,
                    allowRetry: decodingMode === "full" //this option is unnecessary but including for clarity
                });
            }
            catch (error) {
                if (error instanceof errors_1.StopDecodingError &&
                    error.allowRetry &&
                    decodingMode === "full") {
                    //if a retry happens, we've got to do several things in order to switch to ABI mode:
                    //1. mark that we're switching to ABI mode;
                    decodingMode = "abi";
                    //2. abify all previously decoded values;
                    decodedArguments = decodedArguments.map(argumentDecoding => (Object.assign(Object.assign({}, argumentDecoding), { value: abify_1.abifyResult(argumentDecoding.value, info.userDefinedTypes) })));
                    //3. retry this particular decode in ABI mode.
                    try {
                        value = yield* decode_1.default(abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes), //type is now abified!
                        argumentAllocation.pointer, info, {
                            strictAbiMode: true //turns on STRICT MODE to cause more errors to be thrown
                            //retries no longer allowed, not that this has an effect
                        });
                    }
                    catch (_) {
                        //if an error occurred on the retry, this isn't a valid decoding!
                        debug("rejected due to exception on retry");
                        continue allocationAttempts;
                    }
                    //4. the remaining parameters will then automatically be decoded in ABI mode due to (1),
                    //so we don't need to do anything special there.
                }
                else {
                    //if any other sort of error occurred, this isn't a valid decoding!
                    debug("rejected due to exception on first try: %O", error);
                    continue allocationAttempts;
                }
            }
            const name = argumentAllocation.name;
            const indexed = argumentAllocation.pointer.location === "eventtopic";
            decodedArguments.push(name //deliberate general falsiness test
                ? { name, indexed, value }
                : { indexed, value });
        }
        //OK, so, having decoded the result, the question is: does it reencode to the original?
        //first, we have to filter out the indexed arguments, and also get rid of the name information
        const nonIndexedValues = decodedArguments
            .filter(argument => !argument.indexed)
            .map(argument => argument.value);
        //now, we can encode!
        const reEncodedData = AbiData.Encode.encodeTupleAbi(nonIndexedValues, info.allocations.abi);
        const encodedData = info.state.eventdata; //again, not great to read this directly, but oh well
        //are they equal?
        if (!Evm.Utils.equalData(reEncodedData, encodedData)) {
            //if not, this allocation doesn't work
            debug("rejected due to [non-indexed] mismatch");
            continue;
        }
        //one last check -- let's check that the indexed arguments match up, too
        const indexedValues = decodedArguments
            .filter(argument => argument.indexed)
            .map(argument => argument.value);
        const reEncodedTopics = indexedValues.map(Topic.Encode.encodeTopic);
        const encodedTopics = info.state.eventtopics;
        //now: do *these* match?
        const selectorAdjustment = allocation.anonymous ? 0 : 1;
        for (let i = 0; i < reEncodedTopics.length; i++) {
            if (!Evm.Utils.equalData(reEncodedTopics[i], encodedTopics[i + selectorAdjustment])) {
                debug("rejected due to indexed mismatch");
                continue allocationAttempts;
            }
        }
        //if we've made it here, the allocation works!  hooray!
        debug("allocation accepted!");
        if (allocation.abi.anonymous) {
            decodings.push({
                kind: "anonymous",
                definedIn: contractType,
                class: emittingContractType,
                abi: allocation.abi,
                arguments: decodedArguments,
                decodingMode
            });
        }
        else {
            decodings.push({
                kind: "event",
                definedIn: contractType,
                class: emittingContractType,
                abi: allocation.abi,
                arguments: decodedArguments,
                selector,
                decodingMode
            });
        }
    }
    return decodings;
}
exports.decodeEvent = decodeEvent;
const errorSelector = Conversion.toBytes(Web3Utils.soliditySha3({
    type: "string",
    value: "Error(string)"
})).subarray(0, Evm.Utils.SELECTOR_SIZE);
const panicSelector = Conversion.toBytes(Web3Utils.soliditySha3({
    type: "string",
    value: "Panic(uint256)"
})).subarray(0, Evm.Utils.SELECTOR_SIZE);
const defaultReturnAllocationsHighPriority = [
    {
        kind: "revert",
        allocationMode: "full",
        selector: errorSelector,
        abi: {
            name: "Error",
            type: "error",
            inputs: [
                {
                    name: "",
                    type: "string",
                    internalType: "string"
                }
            ]
        },
        arguments: [
            {
                name: "",
                pointer: {
                    location: "returndata",
                    start: errorSelector.length,
                    length: Evm.Utils.WORD_SIZE
                },
                type: {
                    typeClass: "string",
                    typeHint: "string"
                }
            }
        ]
    },
    {
        kind: "revert",
        allocationMode: "full",
        selector: panicSelector,
        abi: {
            name: "Panic",
            type: "error",
            inputs: [
                {
                    name: "",
                    type: "uint256",
                    internalType: "uint256"
                }
            ]
        },
        arguments: [
            {
                name: "",
                pointer: {
                    location: "returndata",
                    start: panicSelector.length,
                    length: Evm.Utils.WORD_SIZE
                },
                type: {
                    typeClass: "uint",
                    bits: Evm.Utils.WORD_SIZE * 8,
                    typeHint: "uint256"
                }
            }
        ]
    }
];
const defaultReturnAllocationsLowPriority = [
    {
        kind: "failure",
        allocationMode: "full",
        selector: new Uint8Array(),
        arguments: []
    },
    {
        kind: "selfdestruct",
        allocationMode: "full",
        selector: new Uint8Array(),
        arguments: []
    }
];
const defaultReturnAllocations = [
    ...defaultReturnAllocationsHighPriority,
    ...defaultReturnAllocationsLowPriority
];
/**
 * If there are multiple possibilities, they're always returned in
 * the order: return, revert, returnmessage, failure, empty, bytecode, unknownbytecode
 * @Category Decoding
 */
function* decodeReturndata(info, successAllocation, //null here must be explicit
status //you can pass this to indicate that you know the status
) {
    let possibleAllocations;
    if (successAllocation === null) {
        possibleAllocations = defaultReturnAllocations;
    }
    else {
        switch (successAllocation.kind) {
            case "return":
                possibleAllocations = [successAllocation, ...defaultReturnAllocations];
                break;
            case "bytecode":
                possibleAllocations = [...defaultReturnAllocations, successAllocation];
                break;
            case "returnmessage":
                possibleAllocations = [
                    ...defaultReturnAllocationsHighPriority,
                    successAllocation,
                    ...defaultReturnAllocationsLowPriority
                ];
                break;
            //Other cases shouldn't happen so I'm leaving them to cause errors!
        }
    }
    let decodings = [];
    allocationAttempts: for (const allocation of possibleAllocations) {
        debug("trying allocation: %O", allocation);
        //before we attempt to use this allocation, we check: does the selector match?
        let encodedData = info.state.returndata; //again, not great to read this directly, but oh well
        const encodedPrefix = encodedData.subarray(0, allocation.selector.length);
        if (!Evm.Utils.equalData(encodedPrefix, allocation.selector)) {
            continue;
        }
        encodedData = encodedData.subarray(allocation.selector.length); //slice off the selector for later
        //also we check, does the status match?
        if (status !== undefined) {
            const successKinds = [
                "return",
                "selfdestruct",
                "bytecode",
                "returnmessage"
            ];
            const failKinds = ["failure", "revert"];
            if (status) {
                if (!successKinds.includes(allocation.kind)) {
                    continue;
                }
            }
            else {
                if (!failKinds.includes(allocation.kind)) {
                    continue;
                }
            }
        }
        if (allocation.kind === "bytecode") {
            //bytecode is special and can't really be integrated with the other cases.
            //so it gets its own function.
            const decoding = yield* decodeBytecode(info);
            if (decoding) {
                decodings.push(decoding);
            }
            continue;
        }
        if (allocation.kind === "returnmessage") {
            //this kind is also special, though thankfully it's easier
            const decoding = {
                kind: "returnmessage",
                status: true,
                data: Conversion.toHexString(info.state.returndata),
                decodingMode: allocation.allocationMode
            };
            decodings.push(decoding);
            continue;
        }
        let decodingMode = allocation.allocationMode; //starts out here; degrades to abi if necessary
        //you can't map with a generator, so we have to do this map manually
        let decodedArguments = [];
        for (const argumentAllocation of allocation.arguments) {
            let value;
            //if in full mode, use the allocation's listed data type.
            //if in ABI mode, abify it before use.
            let dataType = decodingMode === "full"
                ? argumentAllocation.type
                : abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes);
            //now, let's decode!
            try {
                value = yield* decode_1.default(dataType, argumentAllocation.pointer, info, {
                    abiPointerBase: allocation.selector.length,
                    strictAbiMode: true,
                    allowRetry: decodingMode === "full" //this option is unnecessary but including for clarity
                });
                debug("value on first try: %O", value);
            }
            catch (error) {
                if (error instanceof errors_1.StopDecodingError &&
                    error.allowRetry &&
                    decodingMode === "full") {
                    debug("retry!");
                    //if a retry happens, we've got to do several things in order to switch to ABI mode:
                    //1. mark that we're switching to ABI mode;
                    decodingMode = "abi";
                    //2. abify all previously decoded values;
                    decodedArguments = decodedArguments.map(argumentDecoding => (Object.assign(Object.assign({}, argumentDecoding), { value: abify_1.abifyResult(argumentDecoding.value, info.userDefinedTypes) })));
                    //3. retry this particular decode in ABI mode.
                    try {
                        value = yield* decode_1.default(abify_1.abifyType(argumentAllocation.type, info.userDefinedTypes), //type is now abified!
                        argumentAllocation.pointer, info, {
                            abiPointerBase: allocation.selector.length,
                            strictAbiMode: true //turns on STRICT MODE to cause more errors to be thrown
                            //retries no longer allowed, not that this has an effect
                        });
                        debug("value on retry: %O", value);
                    }
                    catch (_) {
                        //if an error occurred on the retry, this isn't a valid decoding!
                        debug("rejected due to exception on retry");
                        continue allocationAttempts;
                    }
                    //4. the remaining parameters will then automatically be decoded in ABI mode due to (1),
                    //so we don't need to do anything special there.
                }
                else {
                    //if any other sort of error occurred, this isn't a valid decoding!
                    debug("rejected due to exception on first try: %O", error);
                    continue allocationAttempts;
                }
            }
            const name = argumentAllocation.name;
            decodedArguments.push(name //deliberate general falsiness test
                ? { name, value }
                : { value });
        }
        //OK, so, having decoded the result, the question is: does it reencode to the original?
        //first, we have to filter out the indexed arguments, and also get rid of the name information
        debug("decodedArguments: %O", decodedArguments);
        const decodedArgumentValues = decodedArguments.map(argument => argument.value);
        const reEncodedData = AbiData.Encode.encodeTupleAbi(decodedArgumentValues, info.allocations.abi);
        //are they equal? note the selector has been stripped off encodedData!
        if (!Evm.Utils.equalData(reEncodedData, encodedData)) {
            //if not, this allocation doesn't work
            debug("rejected due to mismatch");
            continue;
        }
        //if we've made it here, the allocation works!  hooray!
        debug("allocation accepted!");
        let decoding;
        let kind = allocation.kind;
        switch (kind) {
            case "return":
                decoding = {
                    kind,
                    status: true,
                    arguments: decodedArguments,
                    decodingMode
                };
                break;
            case "revert":
                decoding = {
                    kind,
                    abi: allocation.abi,
                    status: false,
                    arguments: decodedArguments,
                    decodingMode
                };
                break;
            case "selfdestruct":
                decoding = {
                    kind,
                    status: true,
                    decodingMode
                };
                break;
            case "failure":
                decoding = {
                    kind,
                    status: false,
                    decodingMode
                };
                break;
        }
        decodings.push(decoding);
    }
    return decodings;
}
exports.decodeReturndata = decodeReturndata;
//note: requires the bytecode to be in returndata, not code
function* decodeBytecode(info) {
    let decodingMode = "full"; //as always, degrade as necessary
    const bytecode = Conversion.toHexString(info.state.returndata);
    const context = Contexts.Utils.findContext(info.contexts, bytecode);
    if (!context) {
        return {
            kind: "unknownbytecode",
            status: true,
            decodingMode: "full",
            bytecode
        };
    }
    const contractType = Contexts.Import.contextToType(context);
    //now: ignore original allocation (which we didn't even pass :) )
    //and lookup allocation by context
    const allocation = (info.allocations.calldata.constructorAllocations[context.context].output);
    debug("bytecode allocation: %O", allocation);
    //now: add immutables if applicable
    let immutables;
    if (allocation.immutables) {
        immutables = [];
        //NOTE: if we're in here, we can assume decodingMode === "full"
        for (const variable of allocation.immutables) {
            const dataType = variable.type; //we don't conditioning on decodingMode here because we know it
            let value;
            try {
                value = yield* decode_1.default(dataType, variable.pointer, info, {
                    allowRetry: true,
                    strictAbiMode: true,
                    paddingMode: "zero" //force zero-padding!
                });
            }
            catch (error) {
                if (error instanceof errors_1.StopDecodingError && error.allowRetry) {
                    //we "retry" by... not bothering with immutables :P
                    //(but we do set the mode to ABI)
                    decodingMode = "abi";
                    immutables = undefined;
                    break;
                }
                else {
                    //otherwise, this isn't a valid decoding I guess
                    return null;
                }
            }
            immutables.push({
                name: variable.name,
                class: variable.definedIn,
                value
            });
        }
    }
    let decoding = {
        kind: "bytecode",
        status: true,
        decodingMode,
        bytecode,
        immutables,
        class: contractType
    };
    //finally: add address if applicable
    if (allocation.delegatecallGuard) {
        decoding.address = Web3Utils.toChecksumAddress(bytecode.slice(4, 4 + 2 * Evm.Utils.ADDRESS_SIZE) //4 = "0x73".length
        );
    }
    return decoding;
}
/**
 * Decodes the return data from a failed call.
 *
 * @param returndata The returned data, as a Uint8Array.
 * @return An array of possible decodings.  At the moment it's
 *   impossible for there to be more than one.  (If the call didn't actually
 *   fail, or failed in a nonstandard way, you may get no decodings at all, though!)
 *
 *   Decodings can either be decodings of revert messages, or decodings
 *   indicating that there was no revert message.  If somehow both were to be
 *   possible, they'd go in that order, although as mentioned, there (at least
 *   currently) isn't any way for that to occur.
 * @Category Decoding convenience
 */
function decodeRevert(returndata) {
    //coercing because TS doesn't know it'll finish in one go
    return decodeReturndata({
        allocations: {},
        state: {
            storage: {},
            returndata
        }
    }, null, false).next().value;
}
exports.decodeRevert = decodeRevert;
//# sourceMappingURL=core.js.map

/***/ }),

/***/ 237478:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:decode");
const AstConstant = __importStar(__webpack_require__(488132));
const AbiData = __importStar(__webpack_require__(20907));
const Format = __importStar(__webpack_require__(429965));
const Basic = __importStar(__webpack_require__(553928));
const Memory = __importStar(__webpack_require__(635035));
const Special = __importStar(__webpack_require__(97859));
const Stack = __importStar(__webpack_require__(915385));
const Storage = __importStar(__webpack_require__(781037));
const Topic = __importStar(__webpack_require__(963196));
function* decode(dataType, pointer, info, options = {}) {
    return Format.Utils.Circularity.tie(yield* decodeDispatch(dataType, pointer, info, options));
}
exports.default = decode;
function* decodeDispatch(dataType, pointer, info, options = {}) {
    debug("type %O", dataType);
    debug("pointer %O", pointer);
    switch (pointer.location) {
        case "storage":
            return yield* Storage.Decode.decodeStorage(dataType, pointer, info);
        case "stack":
            return yield* Stack.Decode.decodeStack(dataType, pointer, info);
        case "stackliteral":
            return yield* Stack.Decode.decodeLiteral(dataType, pointer, info);
        case "definition":
            return yield* AstConstant.Decode.decodeConstant(dataType, pointer, info);
        case "special":
            return yield* Special.Decode.decodeSpecial(dataType, pointer, info);
        case "calldata":
        case "eventdata":
        case "returndata":
            return yield* AbiData.Decode.decodeAbi(dataType, pointer, info, options);
        case "eventtopic":
            return yield* Topic.Decode.decodeTopic(dataType, pointer, info, options);
        case "code":
        case "nowhere":
            //currently only basic types can go in code, so we'll dispatch directly to decodeBasic
            //(if it's a nowhere pointer, this will return an error result, of course)
            //also: we force zero-padding!
            return yield* Basic.Decode.decodeBasic(dataType, pointer, info, Object.assign(Object.assign({}, options), { paddingMode: "zero" }));
        case "memory":
            //this case -- decoding something that resides *directly* in memory,
            //rather than located via a pointer -- only comes up when decoding immutables
            //in a constructor.  thus, we turn on the forceRightPadding option.
            return yield* Memory.Decode.decodeMemory(dataType, pointer, info, Object.assign(Object.assign({}, options), { paddingMode: "right" }));
    }
}
//# sourceMappingURL=decode.js.map

/***/ }),

/***/ 672325:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.handleDecodingError = exports.StopDecodingError = exports.DecodingError = void 0;
const Format = __importStar(__webpack_require__(429965));
//For when we need to throw an error, here's a wrapper class that extends Error.
//Apologies about the confusing name, but I wanted something that would make
//sense should it not be caught and thus accidentally exposed to the outside.
/**
 * @hidden
 */
class DecodingError extends Error {
    constructor(error) {
        super(Format.Utils.Exception.message(error));
        this.error = error;
        this.name = "DecodingError";
    }
}
exports.DecodingError = DecodingError;
//used to stop decoding; like DecodingError, but used in contexts
//where I don't expect it to be caught
//NOTE: currently we don't actually check the type of a thrown error,
//we just rely on context.  still, I think it makes sense to be a separate
//type.
/**
 * @hidden
 */
class StopDecodingError extends Error {
    //when decoding in full mode, we allow an ABI-mode retry.  (if we were already in
    //ABI mode, we give up.)
    constructor(error, allowRetry) {
        const message = `Stopping decoding: ${error.kind}`; //sorry about the bare-bones message,
        //but again, users shouldn't actually see this, so I think this should suffice for now
        super(message);
        this.error = error;
        this.allowRetry = Boolean(allowRetry);
    }
}
exports.StopDecodingError = StopDecodingError;
/**
 * @hidden
 */
function handleDecodingError(dataType, error, strict = false) {
    if (error instanceof DecodingError) {
        //expected error
        if (strict) {
            //strict mode -- stop decoding on errors
            throw new StopDecodingError(error.error);
        }
        else {
            //nonstrict mode -- return an error result
            return {
                //I don't know why TS's inference is failing here and needs the coercion
                type: dataType,
                kind: "error",
                error: error.error
            };
        }
    }
    else {
        //if it's *not* an expected error, we better not swallow it -- rethrow!
        throw error;
    }
}
exports.handleDecodingError = handleDecodingError;
//# sourceMappingURL=errors.js.map

/***/ }),

/***/ 427634:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.makeInternalFunctionId = exports.functionTableEntryToType = void 0;
const import_1 = __webpack_require__(560013);
//creates a type object for the contract the function was defined in
function functionTableEntryToType(functionEntry) {
    if (functionEntry.contractNode === null) {
        //for free functions
        return null;
    }
    return {
        typeClass: "contract",
        kind: "native",
        id: import_1.makeTypeId(functionEntry.contractId, functionEntry.compilationId),
        typeName: functionEntry.contractName,
        contractKind: functionEntry.contractKind,
        payable: functionEntry.contractPayable
    };
}
exports.functionTableEntryToType = functionTableEntryToType;
function makeInternalFunctionId(functionEntry) {
    return `${functionEntry.compilationId}:${functionEntry.id}`;
}
exports.makeInternalFunctionId = makeInternalFunctionId;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 149218:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Import = exports.Utils = void 0;
__exportStar(__webpack_require__(393311), exports);
const Utils = __importStar(__webpack_require__(559901));
exports.Utils = Utils;
const Import = __importStar(__webpack_require__(427634));
exports.Import = Import;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 393311:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 559901:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toAddress = exports.equalData = exports.keccak256 = exports.ZERO_ADDRESS = exports.MAX_WORD = exports.PC_SIZE = exports.SELECTOR_SIZE = exports.ADDRESS_SIZE = exports.WORD_SIZE = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:evm:utils");
const bn_js_1 = __importDefault(__webpack_require__(213550));
// untyped import since no @types/web3-utils exists
const Web3Utils = __webpack_require__(118269);
const Conversion = __importStar(__webpack_require__(152714));
exports.WORD_SIZE = 0x20;
exports.ADDRESS_SIZE = 20;
exports.SELECTOR_SIZE = 4; //function selectors, not event selectors
exports.PC_SIZE = 4;
exports.MAX_WORD = new bn_js_1.default(-1).toTwos(exports.WORD_SIZE * 8);
exports.ZERO_ADDRESS = "0x" + "00".repeat(exports.ADDRESS_SIZE);
//beware of using this for generic strings! (it's fine for bytestrings, or
//strings representing numbers) if you want to use this on a generic string,
//you should pass in {type: "string", value: theString} instead of the string
//itself.
//(maybe I should add a rawKeccak256 function, using sha3 instead of
//soliditysha3?  not seeing the need atm though)
function keccak256(...args) {
    // debug("args %o", args);
    const rawSha = Web3Utils.soliditySha3(...args);
    debug("rawSha %o", rawSha);
    let sha;
    if (rawSha === null) {
        sha = ""; //HACK, I guess?
    }
    else {
        sha = rawSha.replace(/0x/, "");
    }
    return Conversion.toBN(sha);
}
exports.keccak256 = keccak256;
//checks if two bytearrays (which may be undefined) are equal.
//does not consider undefined to be equal to itself.
function equalData(bytes1, bytes2) {
    if (!bytes1 || !bytes2) {
        return false;
    }
    if (bytes1.length !== bytes2.length) {
        return false;
    }
    for (let i = 0; i < bytes1.length; i++) {
        if (bytes1[i] !== bytes2[i]) {
            return false;
        }
    }
    return true;
}
exports.equalData = equalData;
function toAddress(bytes) {
    if (typeof bytes === "string") {
        //in this case, we can do some simple string manipulation and
        //then pass to web3
        let hex = bytes; //just renaming for clarity
        if (hex.startsWith("0x")) {
            hex = hex.slice(2);
        }
        if (hex.length < 2 * exports.ADDRESS_SIZE) {
            hex = hex.padStart(2 * exports.ADDRESS_SIZE, "0");
        }
        if (hex.length > 2 * exports.ADDRESS_SIZE) {
            hex = "0x" + hex.slice(hex.length - 2 * exports.ADDRESS_SIZE);
        }
        return Web3Utils.toChecksumAddress(hex);
    }
    //otherwise, we're in the Uint8Array case, which we can't fully handle ourself
    //truncate *on left* to 20 bytes
    if (bytes.length > exports.ADDRESS_SIZE) {
        bytes = bytes.slice(bytes.length - exports.ADDRESS_SIZE, bytes.length);
    }
    //now, convert to hex string and apply checksum case that second argument
    //(which ensures it's padded to 20 bytes) shouldn't actually ever be
    //needed, but I'll be safe and include it
    return Web3Utils.toChecksumAddress(Conversion.toHexString(bytes, exports.ADDRESS_SIZE));
}
exports.toAddress = toAddress;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 915103:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.nativizeEventArgs = exports.nativizeReturn = exports.nativize = exports.unsafeNativize = exports.ResultInspector = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:export");
const Conversion = __importStar(__webpack_require__(152714));
const inspect_1 = __webpack_require__(749290);
Object.defineProperty(exports, "ResultInspector", ({ enumerable: true, get: function () { return inspect_1.ResultInspector; } }));
Object.defineProperty(exports, "unsafeNativize", ({ enumerable: true, get: function () { return inspect_1.unsafeNativize; } }));
/**
 * This function is similar to
 * [[Format.Utils.Inspect.unsafeNativize|unsafeNativize]], but is intended to
 * be safe, and also allows for different output formats.  The only currently
 * supported format is "ethers", which is intended to match the way that
 * Truffle Contract currently returns values (based on the Ethers decoder).  As
 * such, it only handles ABI types, and in addition does not handle the types
 * fixed, ufixed, or function.  Note that in these cases it returns `undefined`
 * rather than throwing, as we want this function to be used in contexts where
 * it had better not throw.  It also does not handle circularities, for similar
 * reasons.
 *
 * To handle numeric types, this function takes an optional numberFormatter
 * option that tells it how to handle numbers; this function should take a
 * BigInt as input.  By default, this function will be the identity, and so
 * numbers will be represented as BigInts.
 *
 * Note that this function begins by calling abify, so out-of-range enums (that
 * aren't so out-of-range as to be padding errors) will not return `undefined`.
 * Out-of-range booleans similarly will return true rather than `undefined`.
 * However, other range errors may return `undefined`; this may technically be a
 * slight incompatibility with existing behavior, but should not be relevant
 * except in quite unusual cases.
 *
 * In order to match the behavior for tuples, tuples will be transformed into
 * arrays, but named entries will additionally be keyed by name.  Moreover,
 * indexed variables of reference type will be nativized to an undecoded hex
 * string.
 */
function nativize(result, options = {}) {
    const numberFormatter = options.numberFormatter || (x => x);
    const format = options.format || "ethers";
    switch (format) {
        case "ethers":
            return ethersCompatibleNativize(result, numberFormatter);
    }
}
exports.nativize = nativize;
function ethersCompatibleNativize(result, numberFormatter = x => x) {
    //note: the original version of this function began by calling abify,
    //but we don't do that here because abify requires a userDefinedTypes
    //parameter and we don't want that.
    //However, it only needs that to handle getting the types right.  Since
    //we don't care about that here, we instead do away with abify and handle
    //such matters ourselves (which is less convenient, yeah).
    switch (result.kind) {
        case "error":
            switch (result.error.kind) {
                case "IndexedReferenceTypeError":
                    //strictly speaking for arrays ethers will fail to decode
                    //rather than do this, but, eh
                    return result.error.raw;
                case "EnumOutOfRangeError":
                    return numberFormatter(Conversion.toBigInt(result.error.rawAsBN));
                default:
                    return undefined;
            }
        case "value":
            switch (result.type.typeClass) {
                case "uint":
                case "int":
                    const asBN = (result).value.asBN;
                    return numberFormatter(Conversion.toBigInt(asBN));
                case "enum":
                    const numericAsBN = (result).value.numericAsBN;
                    return numberFormatter(Conversion.toBigInt(numericAsBN));
                case "bool":
                    return result.value.asBoolean;
                case "bytes":
                    return result.value.asHex;
                case "address":
                    return result.value.asAddress;
                case "contract":
                    return result.value.address;
                case "string": {
                    const coercedResult = result;
                    switch (coercedResult.value.kind) {
                        case "valid":
                            return coercedResult.value.asString;
                        case "malformed":
                            // this will turn malformed utf-8 into replacement characters (U+FFFD) (WARNING)
                            // note we need to cut off the 0x prefix
                            return Buffer.from(coercedResult.value.asHex.slice(2), "hex").toString();
                    }
                }
                case "array":
                    return result.value.map(value => ethersCompatibleNativize(value, numberFormatter));
                case "tuple":
                case "struct":
                    //in this case, we need the result to be an array, but also
                    //to have the field names (where extant) as keys
                    const nativized = [];
                    const pairs = result.value;
                    for (const { name, value } of pairs) {
                        const nativizedValue = ethersCompatibleNativize(value, numberFormatter);
                        nativized.push(nativizedValue);
                        if (name) {
                            nativized[name] = nativizedValue;
                        }
                    }
                    return nativized;
                case "function":
                    switch (result.type.visibility) {
                        case "external":
                            const coercedResult = result;
                            //ethers per se doesn't handle this, but web3's hacked version will
                            //sometimes decode these as just a bytes24, so let's do that
                            return coercedResult.value.contract.address.toLowerCase() +
                                coercedResult.value.selector.slice(2);
                        case "internal":
                            return undefined;
                    }
                case "fixed":
                case "ufixed":
                default:
                    return undefined;
            }
    }
}
/**
 * This function is similar to [[nativize]], but takes
 * a [[ReturndataDecoding]].  If there's only one returned value, it
 * will be run through compatibleNativize but otherwise unaltered;
 * otherwise the results will be put in an object.
 *
 * Note that if the ReturndataDecoding is not a [[ReturnDecoding]],
 * this will just return `undefined`.
 */
function nativizeReturn(decoding, options = {}) {
    const numberFormatter = options.numberFormatter || (x => x);
    const format = options.format || "ethers";
    switch (format) {
        case "ethers":
            return ethersCompatibleNativizeReturn(decoding, numberFormatter);
    }
}
exports.nativizeReturn = nativizeReturn;
function ethersCompatibleNativizeReturn(decoding, numberFormatter = x => x) {
    if (decoding.kind !== "return") {
        return undefined;
    }
    if (decoding.arguments.length === 1) {
        return ethersCompatibleNativize(decoding.arguments[0].value, numberFormatter);
    }
    const result = {};
    for (let i = 0; i < decoding.arguments.length; i++) {
        const { name, value } = decoding.arguments[i];
        const nativized = ethersCompatibleNativize(value, numberFormatter);
        result[i] = nativized;
        if (name) {
            result[name] = nativized;
        }
    }
    return result;
}
/**
 * This function is similar to [[compatibleNativize]], but takes
 * a [[LogDecoding]], and puts the results in an object.  Note
 * that this does not return the entire event info, but just the
 * `args` for the event.
 */
function nativizeEventArgs(decoding, options = {}) {
    const numberFormatter = options.numberFormatter || (x => x);
    const format = options.format || "ethers";
    switch (format) {
        case "ethers":
            return ethersCompatibleNativizeEventArgs(decoding, numberFormatter);
    }
}
exports.nativizeEventArgs = nativizeEventArgs;
function ethersCompatibleNativizeEventArgs(decoding, numberFormatter = x => x) {
    const result = {};
    for (let i = 0; i < decoding.arguments.length; i++) {
        const { name, value } = decoding.arguments[i];
        const nativized = ethersCompatibleNativize(value, numberFormatter);
        result[i] = nativized;
        if (name) {
            result[name] = nativized;
        }
    }
    //note: if you have an argument named __length__, what ethers
    //actually does is... weird.  we're just going to do this instead,
    //which is simpler and probably more useful, even if it's not strictly
    //the same (I *seriously* doubt anyone was relying on the old behavior,
    //because it's, uh, not very useful)
    result.__length__ = decoding.arguments.length;
    return result;
}
//# sourceMappingURL=export.js.map

/***/ }),

/***/ 573440:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Errors = exports.Values = exports.Types = void 0;
const Types = __importStar(__webpack_require__(154075));
exports.Types = Types;
const Values = __importStar(__webpack_require__(465718));
exports.Values = Values;
const Errors = __importStar(__webpack_require__(537745));
exports.Errors = Errors;
//# sourceMappingURL=common.js.map

/***/ }),

/***/ 448251:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=elementary.js.map

/***/ }),

/***/ 537745:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:errors");
//# sourceMappingURL=errors.js.map

/***/ }),

/***/ 429965:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Utils = exports.Errors = exports.Values = exports.Types = void 0;
const common_1 = __webpack_require__(573440);
Object.defineProperty(exports, "Types", ({ enumerable: true, get: function () { return common_1.Types; } }));
Object.defineProperty(exports, "Values", ({ enumerable: true, get: function () { return common_1.Values; } }));
Object.defineProperty(exports, "Errors", ({ enumerable: true, get: function () { return common_1.Errors; } }));
const Utils = __importStar(__webpack_require__(446776));
exports.Utils = Utils;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 154075:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isContractDefinedType = exports.typeStringWithoutLocation = exports.typeString = exports.specifyLocation = exports.fullType = exports.isReferenceType = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:types");
function isUserDefinedType(anyType) {
    const userDefinedTypes = ["contract", "enum", "struct"];
    return userDefinedTypes.includes(anyType.typeClass);
}
function isReferenceType(anyType) {
    const alwaysReferenceTypes = ["array", "mapping", "struct", "string"];
    if (alwaysReferenceTypes.includes(anyType.typeClass)) {
        return true;
    }
    else if (anyType.typeClass === "bytes") {
        return anyType.kind === "dynamic";
    }
    else {
        return false;
    }
}
exports.isReferenceType = isReferenceType;
//one could define a counterpart function that stripped all unnecessary information
//from the type object, but at the moment I see no need for that
function fullType(basicType, userDefinedTypes) {
    if (!isUserDefinedType(basicType)) {
        return basicType;
    }
    let id = basicType.id;
    let storedType = userDefinedTypes[id];
    if (!storedType) {
        return basicType;
    }
    let returnType = Object.assign(Object.assign({}, basicType), storedType);
    if (isReferenceType(basicType) && basicType.location !== undefined) {
        returnType = specifyLocation(returnType, basicType.location);
    }
    return returnType;
}
exports.fullType = fullType;
//the location argument here always forces, so passing undefined *will* force undefined
function specifyLocation(dataType, location) {
    if (isReferenceType(dataType)) {
        switch (dataType.typeClass) {
            case "string":
            case "bytes":
                return Object.assign(Object.assign({}, dataType), { location });
            case "array":
                return Object.assign(Object.assign({}, dataType), { location, baseType: specifyLocation(dataType.baseType, location) });
            case "mapping":
                let newLocation = location === "storage" ? "storage" : undefined;
                return Object.assign(Object.assign({}, dataType), { location: newLocation, valueType: specifyLocation(dataType.valueType, newLocation) });
            case "struct":
                let returnType = Object.assign(Object.assign({}, dataType), { location });
                if (returnType.memberTypes) {
                    returnType.memberTypes = returnType.memberTypes.map(({ name: memberName, type: memberType }) => ({
                        name: memberName,
                        type: specifyLocation(memberType, location)
                    }));
                }
                return returnType;
        }
    }
    else {
        return dataType;
    }
}
exports.specifyLocation = specifyLocation;
//NOTE: the following two functions might not be exactly right for weird internal stuff,
//or for ABI-only stuff.  (E.g. for internal stuff sometimes it records whether things
//are pointers or not??  we don't track that so we can't recreate that)
//But what can you do.
function typeString(dataType) {
    let baseString = typeStringWithoutLocation(dataType);
    if (isReferenceType(dataType) && dataType.location) {
        return baseString + " " + dataType.location;
    }
    else {
        return baseString;
    }
}
exports.typeString = typeString;
function typeStringWithoutLocation(dataType) {
    switch (dataType.typeClass) {
        case "uint":
            return dataType.typeHint || `uint${dataType.bits}`;
        case "int":
            return dataType.typeHint || `int${dataType.bits}`;
        case "bool":
            return dataType.typeHint || "bool";
        case "bytes":
            if (dataType.typeHint) {
                return dataType.typeHint;
            }
            switch (dataType.kind) {
                case "dynamic":
                    return "bytes";
                case "static":
                    return `bytes${dataType.length}`;
            }
        case "address":
            switch (dataType.kind) {
                case "general":
                    return dataType.typeHint || "address"; //I guess?
                case "specific":
                    return dataType.payable ? "address payable" : "address";
            }
        case "string":
            return dataType.typeHint || "string";
        case "fixed":
            return dataType.typeHint || `fixed${dataType.bits}x${dataType.places}`;
        case "ufixed":
            return dataType.typeHint || `ufixed${dataType.bits}x${dataType.places}`;
        case "array":
            if (dataType.typeHint) {
                return dataType.typeHint;
            }
            switch (dataType.kind) {
                case "dynamic":
                    return `${typeStringWithoutLocation(dataType.baseType)}[]`;
                case "static":
                    return `${typeStringWithoutLocation(dataType.baseType)}[${dataType.length}]`;
            }
        case "mapping":
            return `mapping(${typeStringWithoutLocation(dataType.keyType)} => ${typeStringWithoutLocation(dataType.valueType)})`;
        case "struct":
        case "enum":
            //combining these cases for simplicity
            switch (dataType.kind) {
                case "local":
                    return `${dataType.typeClass} ${dataType.definingContractName}.${dataType.typeName}`;
                case "global":
                    return `${dataType.typeClass} ${dataType.typeName}`;
            }
        case "tuple":
            return (dataType.typeHint ||
                "tuple(" +
                    dataType.memberTypes
                        .map(memberType => typeString(memberType.type))
                        .join(",") +
                    ")"); //note that we do include location and do not put spaces
        case "contract":
            return dataType.contractKind + " " + dataType.typeName;
        case "magic":
            //no, this is not transposed!
            const variableNames = {
                message: "msg",
                transaction: "tx",
                block: "block"
            };
            return variableNames[dataType.variable];
        case "type":
            return `type(${typeString(dataType.type)})`;
        case "function":
            let visibilityString;
            switch (dataType.visibility) {
                case "external":
                    if (dataType.kind === "general") {
                        if (dataType.typeHint) {
                            return dataType.typeHint;
                        }
                        else {
                            return "function external"; //I guess???
                        }
                    }
                    visibilityString = " external"; //note the deliberate space!
                    break;
                case "internal":
                    visibilityString = "";
                    break;
            }
            let mutabilityString = dataType.mutability === "nonpayable" ? "" : " " + dataType.mutability; //again, note the deliberate space
            let inputList = dataType.inputParameterTypes.map(typeString).join(","); //note that we do include location, and do not put spaces
            let outputList = dataType.outputParameterTypes.map(typeString).join(",");
            let inputString = `function(${inputList})`;
            let outputString = outputList === "" ? "" : ` returns (${outputList})`; //again, note the deliberate space
            return inputString + mutabilityString + visibilityString + outputString;
    }
}
exports.typeStringWithoutLocation = typeStringWithoutLocation;
function isContractDefinedType(anyType) {
    const contractDefinedTypes = ["enum", "struct"];
    return contractDefinedTypes.includes(anyType.typeClass);
}
exports.isContractDefinedType = isContractDefinedType;
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 809898:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.tie = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:utils:circularity");
function tie(untied) {
    return tieWithTable(untied, []);
}
exports.tie = tie;
function tieWithTable(untied, seenSoFar) {
    if (untied.kind === "error") {
        return untied;
    }
    let reference;
    switch (untied.type.typeClass) {
        case "array":
            let untiedAsArray = untied; //dammit TS
            reference = untiedAsArray.reference;
            if (reference === undefined) {
                //we need to do some pointer stuff here, so let's first create our new
                //object we'll be pointing to
                //[we don't want to alter the original accidentally so let's clone a bit]
                let tied = Object.assign(Object.assign({}, untiedAsArray), { value: [...untiedAsArray.value] });
                //now, we can't use a map here, or we'll screw things up!
                //we want to *mutate* value, not replace it with a new object
                for (let index in tied.value) {
                    tied.value[index] = tieWithTable(tied.value[index], [
                        tied,
                        ...seenSoFar
                    ]);
                }
                return tied;
            }
            else {
                return Object.assign(Object.assign({}, seenSoFar[reference - 1]), { reference });
            }
        case "struct":
            let untiedAsStruct = untied; //dammit TS
            reference = untiedAsStruct.reference;
            if (reference === undefined) {
                //we need to do some pointer stuff here, so let's first create our new
                //object we'll be pointing to
                //[we don't want to alter the original accidentally so let's clone a bit]
                let tied = Object.assign(Object.assign({}, untiedAsStruct), { value: untiedAsStruct.value.map(component => (Object.assign({}, component))) });
                //now, we can't use a map here, or we'll screw things up!
                //we want to *mutate* value, not replace it with a new object
                for (let index in tied.value) {
                    tied.value[index] = Object.assign(Object.assign({}, tied.value[index]), { value: tieWithTable(tied.value[index].value, [tied, ...seenSoFar]) });
                }
                return tied;
            }
            else {
                return Object.assign(Object.assign({}, seenSoFar[reference - 1]), { reference });
            }
        case "tuple": //currently there are no memory tuples, but may as well
            //can't be circular, just recurse
            //note we can just recurse with a straight tie here; don't need tieWithTable
            let untiedAsTuple = untied; //dammit TS
            //we need to do some pointer stuff here, so let's first create our new
            //object we'll be pointing to
            let tied = Object.assign({}, untiedAsTuple);
            tied.value = tied.value.map(component => (Object.assign(Object.assign({}, component), { value: tie(component.value) })));
            return tied;
        default:
            //other types either:
            //1. aren't containers and so need no recursion
            //2. are containers but can't go in or contain memory things
            //and so still need no recursion
            //(or, in the case of mappings, can't contain *nontrivial* memory
            //things)
            return untied;
    }
}
//# sourceMappingURL=circularity.js.map

/***/ }),

/***/ 965086:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.message = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:utils:exception");
const Format = __importStar(__webpack_require__(573440));
const Ast = __importStar(__webpack_require__(114442));
//this function gives an error message
//for those errors that are meant to possibly
//be wrapped in a DecodingError and thrown
function message(error) {
    switch (error.kind) {
        case "UserDefinedTypeNotFoundError":
            let typeName = Format.Types.isContractDefinedType(error.type)
                ? error.type.definingContractName + "." + error.type.typeName
                : error.type.typeName;
            return `Unknown ${error.type.typeClass} type ${typeName} of id ${error.type.id}`;
        case "UnsupportedConstantError":
            return `Unsupported constant type ${Ast.Utils.typeClass(error.definition)}`;
        case "UnusedImmutableError":
            return "Cannot read unused immutable";
        case "ReadErrorStack":
            return `Can't read stack from position ${error.from} to ${error.to}`;
        case "ReadErrorBytes":
            return `Can't read ${error.length} bytes from ${error.location} starting at ${error.start}`;
        case "ReadErrorStorage":
            if (error.range.length) {
                return `Can't read ${error.range.length} bytes from storage starting at index ${error.range.from.index} in ${slotAddressPrintout(error.range.from.slot)}`;
            }
            else {
                return `Can't read storage from index ${error.range.from.index} in ${slotAddressPrintout(error.range.from.slot)} to index ${error.range.to.index} in ${slotAddressPrintout(error.range.to.slot)}`;
            }
    }
}
exports.message = message;
function slotAddressPrintout(slot) {
    if (slot.key !== undefined && slot.path !== undefined) {
        // mapping reference
        let { type: keyEncoding, value: keyValue } = keyInfoForPrinting(slot.key);
        return ("keccak(" +
            keyValue +
            " as " +
            keyEncoding +
            ", " +
            slotAddressPrintout(slot.path) +
            ") + " +
            slot.offset.toString());
    }
    else if (slot.path !== undefined) {
        const pathAddressPrintout = slotAddressPrintout(slot.path);
        return slot.hashPath
            ? "keccak(" + pathAddressPrintout + ")" + slot.offset.toString()
            : pathAddressPrintout + slot.offset.toString();
    }
    else {
        return slot.offset.toString();
    }
}
//this is like the old toSoliditySha3Input, but for debugging purposes ONLY
//it will NOT produce correct input to soliditySha3
//please use mappingKeyAsHex instead if you wish to encode a mapping key.
function keyInfoForPrinting(input) {
    switch (input.type.typeClass) {
        case "uint":
            return {
                type: "uint",
                value: input.value.asBN.toString()
            };
        case "int":
            return {
                type: "int",
                value: input.value.asBN.toString()
            };
        case "fixed":
            return {
                type: `fixed256x${input.type.places}`,
                value: input.value.asBig.toString()
            };
        case "ufixed":
            return {
                type: `ufixed256x${input.type.places}`,
                value: input.value.asBig.toString()
            };
        case "bool":
            //this is the case that won't work as valid input to soliditySha3 :)
            return {
                type: "uint",
                value: input.value.asBoolean.toString()
            };
        case "bytes":
            switch (input.type.kind) {
                case "static":
                    return {
                        type: "bytes32",
                        value: input.value.asHex
                    };
                case "dynamic":
                    return {
                        type: "bytes",
                        value: input.value.asHex
                    };
            }
        case "address":
            return {
                type: "address",
                value: input.value.asAddress
            };
        case "string":
            let coercedInput = (input);
            switch (coercedInput.value.kind) {
                case "valid":
                    return {
                        type: "string",
                        value: coercedInput.value.asString
                    };
                case "malformed":
                    return {
                        type: "bytes",
                        value: coercedInput.value.asHex
                    };
            }
        //fixed and ufixed are skipped for now
    }
}
//# sourceMappingURL=exception.js.map

/***/ }),

/***/ 446776:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Circularity = exports.Inspect = exports.Exception = void 0;
const Exception = __importStar(__webpack_require__(965086));
exports.Exception = Exception;
const Inspect = __importStar(__webpack_require__(749290));
exports.Inspect = Inspect;
const Circularity = __importStar(__webpack_require__(809898));
exports.Circularity = Circularity;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 749290:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unsafeNativize = exports.unsafeNativizeVariables = exports.ResultInspector = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:utils:inspect");
const util_1 = __importDefault(__webpack_require__(431669));
const Exception = __importStar(__webpack_require__(965086));
//HACK -- inspect options are ridiculous, I swear >_>
function cleanStylize(options) {
    return Object.assign({}, ...Object.entries(options).map(([key, value]) => key === "stylize" ? {} : { [key]: value }));
}
/**
 * This class is meant to be used with Node's
 * [util.inspect()](https://nodejs.org/api/util.html#util_util_inspect_object_options)
 * function.  Given a [[Format.Values.Result]] `value`, one can use
 * `new ResultInspector(value)` to create a ResultInspector for that value,
 * which can be used with util.inspect() to create a human-readable string
 * representing the value.
 *
 * @example
 * Suppose `value` is a Result.  In Node, the following would print to the
 * console a human-readable representation of `value`, with colors enabled,
 * no maximum depth, and no maximum array length, and lines (usually) no
 * longer than 80 characters:
 * ```javascript
 * console.log(
 *   util.inspect(
 *     new ResultInspector(value),
 *     {
 *       colors: true,
 *       depth: null,
 *       maxArrayLength: null,
 *       breakLength: 80
 *     }
 *   )
 * );
 * ```
 * Of course, there are many other ways to use util.inspect; see Node's
 * documentation, linked above, for more.
 */
class ResultInspector {
    constructor(result) {
        this.result = result;
    }
    [util_1.default.inspect.custom](depth, options) {
        switch (this.result.kind) {
            case "value":
                switch (this.result.type.typeClass) {
                    case "uint":
                    case "int":
                        return options.stylize((this.result).value.asBN.toString(), "number");
                    case "fixed":
                    case "ufixed":
                        //note: because this is just for display, we don't bother adjusting the magic values Big.NE or Big.PE;
                        //we'll trust those to their defaults
                        return options.stylize((this.result).value.asBig.toString(), "number");
                    case "bool":
                        return util_1.default.inspect(this.result.value.asBoolean, options);
                    case "bytes":
                        let hex = this.result.value.asHex;
                        switch (this.result.type.kind) {
                            case "static":
                                return options.stylize(hex, "number");
                            case "dynamic":
                                return options.stylize(`hex'${hex.slice(2)}'`, "string");
                        }
                    case "address":
                        return options.stylize(this.result.value.asAddress, "number");
                    case "string": {
                        let coercedResult = this.result;
                        switch (coercedResult.value.kind) {
                            case "valid":
                                return util_1.default.inspect(coercedResult.value.asString, options);
                            case "malformed":
                                //note: this will turn malformed utf-8 into replacement characters (U+FFFD)
                                //note we need to cut off the 0x prefix
                                return util_1.default.inspect(Buffer.from(coercedResult.value.asHex.slice(2), "hex").toString());
                        }
                    }
                    case "array": {
                        let coercedResult = this.result;
                        if (coercedResult.reference !== undefined) {
                            return formatCircular(coercedResult.reference, options);
                        }
                        return util_1.default.inspect(coercedResult.value.map(element => new ResultInspector(element)), options);
                    }
                    case "mapping":
                        return util_1.default.inspect(new Map((this.result).value.map(({ key, value }) => [
                            new ResultInspector(key),
                            new ResultInspector(value)
                        ])), options);
                    case "struct": {
                        let coercedResult = this.result;
                        if (coercedResult.reference !== undefined) {
                            return formatCircular(coercedResult.reference, options);
                        }
                        return util_1.default.inspect(Object.assign({}, ...coercedResult.value.map(({ name, value }) => ({
                            [name]: new ResultInspector(value)
                        }))), options);
                    }
                    case "tuple": {
                        let coercedResult = this.result;
                        //if everything is named, do same as with struct.
                        //if not, just do an array.
                        //(good behavior in the mixed case is hard, unfortunately)
                        if (coercedResult.value.every(({ name }) => name)) {
                            return util_1.default.inspect(Object.assign({}, ...coercedResult.value.map(({ name, value }) => ({
                                [name]: new ResultInspector(value)
                            }))), options);
                        }
                        else {
                            return util_1.default.inspect(coercedResult.value.map(({ value }) => new ResultInspector(value)), options);
                        }
                    }
                    case "type": {
                        switch (this.result.type.type.typeClass) {
                            case "contract":
                                //same as struct case but w/o circularity check
                                return util_1.default.inspect(Object.assign({}, ...this.result.value.map(({ name, value }) => ({
                                    [name]: new ResultInspector(value)
                                }))), options);
                            case "enum": {
                                return enumTypeName(this.result.type.type);
                            }
                        }
                    }
                    case "magic":
                        return util_1.default.inspect(Object.assign({}, ...Object.entries(this.result.value).map(([key, value]) => ({ [key]: new ResultInspector(value) }))), options);
                    case "enum": {
                        return enumFullName(this.result); //not stylized
                    }
                    case "contract": {
                        return util_1.default.inspect(new ContractInfoInspector(this.result.value), options);
                    }
                    case "function":
                        switch (this.result.type.visibility) {
                            case "external": {
                                let coercedResult = (this.result);
                                let contractString = util_1.default.inspect(new ContractInfoInspector(coercedResult.value.contract), Object.assign(Object.assign({}, cleanStylize(options)), { colors: false }));
                                let firstLine;
                                switch (coercedResult.value.kind) {
                                    case "known":
                                        firstLine = `[Function: ${coercedResult.value.abi.name} of`;
                                        break;
                                    case "invalid":
                                    case "unknown":
                                        firstLine = `[Function: Unknown selector ${coercedResult.value.selector} of`;
                                        break;
                                }
                                let secondLine = `${contractString}]`;
                                let breakingSpace = firstLine.length + secondLine.length + 1 > options.breakLength
                                    ? "\n"
                                    : " ";
                                //now, put it together
                                return options.stylize(firstLine + breakingSpace + secondLine, "special");
                            }
                            case "internal": {
                                let coercedResult = (this.result);
                                switch (coercedResult.value.kind) {
                                    case "function":
                                        if (coercedResult.value.definedIn) {
                                            return options.stylize(`[Function: ${coercedResult.value.definedIn.typeName}.${coercedResult.value.name}]`, "special");
                                        }
                                        else {
                                            return options.stylize(`[Function: ${coercedResult.value.name}]`, "special");
                                        }
                                    case "exception":
                                        return coercedResult.value.deployedProgramCounter === 0
                                            ? options.stylize(`[Function: <zero>]`, "special")
                                            : options.stylize(`[Function: <uninitialized>]`, "special");
                                    case "unknown":
                                        let firstLine = `[Function: decoding not supported (raw info:`;
                                        let secondLine = `deployed PC=${coercedResult.value.deployedProgramCounter}, constructor PC=${coercedResult.value.constructorProgramCounter})]`;
                                        let breakingSpace = firstLine.length + secondLine.length + 1 >
                                            options.breakLength
                                            ? "\n"
                                            : " ";
                                        //now, put it together
                                        return options.stylize(firstLine + breakingSpace + secondLine, "special");
                                }
                            }
                        }
                }
            case "error": {
                debug("this.result: %O", this.result);
                let errorResult = this.result; //the hell?? why couldn't it make this inference??
                switch (errorResult.error.kind) {
                    case "UintPaddingError":
                        return `Uint has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "IntPaddingError":
                        return `Int has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "UintPaddingError":
                        return `Ufixed has (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "FixedPaddingError":
                        return `Fixed has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "BoolOutOfRangeError":
                        return `Invalid boolean (numeric value ${errorResult.error.rawAsBN.toString()})`;
                    case "BoolPaddingError":
                        return `Boolean has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "BytesPaddingError":
                        return `Bytestring has extra trailing bytes (padding error) (raw value ${errorResult.error.raw})`;
                    case "AddressPaddingError":
                        return `Address has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "EnumOutOfRangeError":
                        return `Invalid ${enumTypeName(errorResult.error.type)} (numeric value ${errorResult.error.rawAsBN.toString()})`;
                    case "EnumPaddingError":
                        return `Enum ${enumTypeName(errorResult.error.type)} has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "EnumNotFoundDecodingError":
                        return `Unknown enum type ${enumTypeName(errorResult.error.type)} of id ${errorResult.error.type.id} (numeric value ${errorResult.error.rawAsBN.toString()})`;
                    case "ContractPaddingError":
                        return `Contract address has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "FunctionExternalNonStackPaddingError":
                        return `External function has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "FunctionExternalStackPaddingError":
                        return `External function address or selector has extra leading bytes (padding error) (raw address ${errorResult.error.rawAddress}, raw selector ${errorResult.error.rawSelector})`;
                    case "FunctionInternalPaddingError":
                        return `Internal function has incorrect padding (expected padding: ${errorResult.error.paddingType}) (raw value ${errorResult.error.raw})`;
                    case "NoSuchInternalFunctionError":
                        return `Invalid function (Deployed PC=${errorResult.error.deployedProgramCounter}, constructor PC=${errorResult.error.constructorProgramCounter}) of contract ${errorResult.error.context.typeName}`;
                    case "DeployedFunctionInConstructorError":
                        return `Deployed-style function (PC=${errorResult.error.deployedProgramCounter}) in constructor`;
                    case "MalformedInternalFunctionError":
                        return `Malformed internal function w/constructor PC only (value: ${errorResult.error.constructorProgramCounter})`;
                    case "IndexedReferenceTypeError": //for this one we'll bother with some line-wrapping
                        let firstLine = `Cannot decode indexed parameter of reference type ${errorResult.error.type.typeClass}`;
                        let secondLine = `(raw value ${errorResult.error.raw})`;
                        let breakingSpace = firstLine.length + secondLine.length + 1 > options.breakLength
                            ? "\n"
                            : " ";
                        return firstLine + breakingSpace + secondLine;
                    case "OverlongArraysAndStringsNotImplementedError":
                        return `Array or string is too long (length ${errorResult.error.lengthAsBN.toString()}); decoding is not supported`;
                    case "OverlargePointersNotImplementedError":
                        return `Pointer is too large (value ${errorResult.error.pointerAsBN.toString()}); decoding is not supported`;
                    case "UserDefinedTypeNotFoundError":
                    case "UnsupportedConstantError":
                    case "UnusedImmutableError":
                    case "ReadErrorStack":
                    case "ReadErrorStorage":
                    case "ReadErrorBytes":
                        return Exception.message(errorResult.error); //yay, these five are already defined!
                }
            }
        }
    }
}
exports.ResultInspector = ResultInspector;
//these get their own class to deal with a minor complication
class ContractInfoInspector {
    constructor(value) {
        this.value = value;
    }
    [util_1.default.inspect.custom](depth, options) {
        switch (this.value.kind) {
            case "known":
                return (options.stylize(this.value.address, "number") +
                    ` (${this.value.class.typeName})`);
            case "unknown":
                return (options.stylize(this.value.address, "number") + " of unknown class");
        }
    }
}
function enumTypeName(enumType) {
    return ((enumType.kind === "local" ? enumType.definingContractName + "." : "") +
        enumType.typeName);
}
//this function will be used in the future for displaying circular
//structures
function formatCircular(loopLength, options) {
    return options.stylize(`[Circular (=up ${loopLength})]`, "special");
}
function enumFullName(value) {
    switch (value.type.kind) {
        case "local":
            return `${value.type.definingContractName}.${value.type.typeName}.${value.value.name}`;
        case "global":
            return `${value.type.typeName}.${value.value.name}`;
    }
}
/**
 * WARNING! Do NOT use this function in real code unless you
 * absolutely have to!  Using it in controlled tests is fine,
 * but do NOT use it in real code if you have any better option!
 * See [[unsafeNativize]] for why!
 */
function unsafeNativizeVariables(variables) {
    return Object.assign({}, ...Object.entries(variables).map(([name, value]) => {
        try {
            return { [name]: unsafeNativize(value) };
        }
        catch (_) {
            return undefined; //I guess??
        }
    }));
}
exports.unsafeNativizeVariables = unsafeNativizeVariables;
//HACK! Avoid using!
/**
 * WARNING! Do NOT use this function in real code unless you absolutely have
 * to!  Using it in controlled tests is fine, but do NOT use it in real code if
 * you have any better option!
 *
 * This function is a giant hack.  It will throw exceptions on numbers that
 * don't fit in a Javascript number.  It loses various information.  It was
 * only ever written to support our hacked-together watch expression system,
 * and later repurposed to make testing easier.
 *
 * If you are not doing something as horrible as evaluating user-inputted
 * Javascript expressions meant to operate upon Solidity variables, then you
 * probably have a better option than using this in real code!
 *
 * (For instance, if you just want to nicely print individual values, without
 * attempting to first operate on them via Javascript expressions, we have the
 * [[ResultInspector]] class, which can be used with Node's
 * [util.inspect()](https://nodejs.org/api/util.html#util_util_inspect_object_options)
 * to do exactly that.)
 *
 * Remember, the decoder output format was made to be machine-readable.  It
 * shouldn't be too hard for you to process.  If it comes to it, copy-paste
 * this code and dehackify it for your use case, which hopefully is more
 * manageable than the one that caused us to write this.
 */
function unsafeNativize(result) {
    return unsafeNativizeWithTable(result, []);
}
exports.unsafeNativize = unsafeNativize;
function unsafeNativizeWithTable(result, seenSoFar) {
    if (result.kind === "error") {
        debug("ErrorResult: %O", result);
        switch (result.error.kind) {
            case "BoolOutOfRangeError":
                return true;
            default:
                return undefined;
        }
    }
    //NOTE: for simplicity, only arrays & structs will call unsafeNativizeWithTable;
    //other containers will just call unsafeNativize because they can get away with it
    //(only things that can *be* circular need unsafeNativizeWithTable, not things that
    //can merely *contain* circularities)
    switch (result.type.typeClass) {
        case "uint":
        case "int":
            return (result).value.asBN.toNumber(); //WARNING
        case "bool":
            return result.value.asBoolean;
        case "bytes":
            return result.value.asHex;
        case "address":
            return result.value.asAddress;
        case "string": {
            let coercedResult = result;
            switch (coercedResult.value.kind) {
                case "valid":
                    return coercedResult.value.asString;
                case "malformed":
                    // this will turn malformed utf-8 into replacement characters (U+FFFD) (WARNING)
                    // note we need to cut off the 0x prefix
                    return Buffer.from(coercedResult.value.asHex.slice(2), "hex").toString();
            }
        }
        case "fixed":
        case "ufixed":
            //HACK: Big doesn't have a toNumber() method, so we convert to string and then parse with Number
            //NOTE: we don't bother setting the magic variables Big.NE or Big.PE first, as the choice of
            //notation shouldn't affect the result (can you believe I have to write this? @_@)
            return Number((result).value.asBig.toString()); //WARNING
        case "array": {
            let coercedResult = result;
            if (coercedResult.reference === undefined) {
                //we need to do some pointer stuff here, so let's first create our new
                //object we'll be pointing to
                //[we don't want to alter the original accidentally so let's clone a bit]
                let output = [...coercedResult.value];
                //now, we can't use a map here, or we'll screw things up!
                //we want to *mutate* output, not replace it with a new object
                for (let index in output) {
                    output[index] = unsafeNativizeWithTable(output[index], [
                        output,
                        ...seenSoFar
                    ]);
                }
                return output;
            }
            else {
                return seenSoFar[coercedResult.reference - 1];
            }
        }
        case "mapping":
            return Object.assign({}, ...result.value.map(({ key, value }) => ({
                [unsafeNativize(key).toString()]: unsafeNativize(value)
            })));
        case "struct": {
            let coercedResult = result;
            if (coercedResult.reference === undefined) {
                //we need to do some pointer stuff here, so let's first create our new
                //object we'll be pointing to
                let output = Object.assign({}, ...result.value.map(({ name, value }) => ({
                    [name]: value //we *don't* nativize yet!
                })));
                //now, we can't use a map here, or we'll screw things up!
                //we want to *mutate* output, not replace it with a new object
                for (let name in output) {
                    output[name] = unsafeNativizeWithTable(output[name], [
                        output,
                        ...seenSoFar
                    ]);
                }
                return output;
            }
            else {
                return seenSoFar[coercedResult.reference - 1];
            }
        }
        case "type":
            switch (result.type.type.typeClass) {
                case "contract":
                    return Object.assign({}, ...result.value.map(({ name, value }) => ({
                        [name]: unsafeNativize(value)
                    })));
                case "enum":
                    return Object.assign({}, ...result.value.map(enumValue => ({
                        [enumValue.value.name]: unsafeNativize(enumValue)
                    })));
            }
        case "tuple":
            return result.value.map(({ value }) => unsafeNativize(value));
        case "magic":
            return Object.assign({}, ...Object.entries(result.value).map(([key, value]) => ({ [key]: unsafeNativize(value) })));
        case "enum":
            return enumFullName(result);
        case "contract":
            return result.value.address; //we no longer include additional info
        case "function":
            switch (result.type.visibility) {
                case "external": {
                    let coercedResult = result;
                    switch (coercedResult.value.kind) {
                        case "known":
                            return `${coercedResult.value.contract.class.typeName}(${coercedResult.value.contract.address}).${coercedResult.value.abi.name}`;
                        case "invalid":
                            return `${coercedResult.value.contract.class.typeName}(${coercedResult.value.contract.address}).call(${coercedResult.value.selector}...)`;
                        case "unknown":
                            return `${coercedResult.value.contract.address}.call(${coercedResult.value.selector}...)`;
                    }
                }
                case "internal": {
                    let coercedResult = result;
                    switch (coercedResult.value.kind) {
                        case "function":
                            if (coercedResult.value.definedIn) {
                                return `${coercedResult.value.definedIn.typeName}.${coercedResult.value.name}`;
                            }
                            else {
                                return coercedResult.value.name;
                            }
                        case "exception":
                            return coercedResult.value.deployedProgramCounter === 0
                                ? `<zero>`
                                : `<uninitialized>`;
                        case "unknown":
                            return `<decoding not supported>`;
                    }
                }
            }
    }
}
//# sourceMappingURL=inspect.js.map

/***/ }),

/***/ 465718:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:format:values");
__exportStar(__webpack_require__(448251), exports);
//# sourceMappingURL=values.js.map

/***/ }),

/***/ 20102:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/**
 * # Truffle Codec
 *
 * This module provides low-level decoding and encoding functionality for
 * Solidity and the Solidity ABI.  Many parts of this module are intended
 * primarily for internal use by Truffle and so remain largely undocumented,
 * but some of its types are also output by @truffle/decoder, which provides
 * a higher-level interface to much of this module's functionality.
 *
 * ## If you're here from Truffle Decoder
 *
 * If you're coming here from [[@truffle/decoder]], you probably just want to
 * know about the parts that are relevant to you.  These are:
 *
 * * The "data" category (specifically [[Format]])
 * * The "output" and "enumerations" categories ([[CalldataDecoding]], [[LogDecoding]], et al., see below)
 * * The "errors" category (specifically [[UnknownUserDefinedTypeError]])
 *
 * Note that the data category is largely scarce in
 * documentation, although that's because it's largely self-explanatory.
 *
 * If you're not just here from Truffle Decoder, but are actually
 * interested in the lower-level workings, read on.
 *
 * ## How this module differs from Truffle Decoder
 *
 * Unlike Truffle Decoder, this library makes no network connections
 * and avoids dependencies that do.  Instead, its decoding functionality
 * is generator-based; calling one of the decoding functions returns a
 * generator.  This generator's `next()` function may return a finished
 * result, or it may return a request for more information.  It is up to
 * the caller to fulfill these requests -- say, by making a network
 * connection of its own.  This is how @truffle/decoder works; @truffle/codec
 * makes requests, and @truffle/decoder fulfills them by
 * looking up the necessary information on the blockchain.
 *
 * This library also provides additional functionality beyond what's used by
 * Truffle Decoder.  In particular, this library also exists to support Truffle
 * Debugger, and so it provides encoding functionality not just for
 * transactions, logs, and state variables, but also for Solidity variables
 * during transaction execution, including circularity detection for memroy
 * structures.  It includes functionality for decoding Solidity's internal
 * function pointers, which the debugger uses, but which Truffle Decoder
 * currently does not (although this is planned for the future).
 *
 * There is also functionality for decoding return values and revert messages
 * that goes beyond what's currently available in @truffle/decoder; this may get
 * a better interface in the future.
 *
 * ## How to use
 *
 * You should probably use [[@truffle/decoder]] instead, if your use case doesn't
 * preclude it.  This module has little documentation, where it has any at all,
 * and it's likely that parts of its interface may change (particularly
 * regarding allocation).  That said, if you truly need the functionality here,
 * Truffle Decoder can perhaps serve as something of a reference implementation
 * (and perhaps Truffle Debugger as well, though that code is much harder to
 * read or copy).
 *
 * @module @truffle/codec
 */ /** */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Export = exports.Evm = exports.Pointer = exports.Conversion = exports.Contexts = exports.Compilations = exports.Compiler = exports.Ast = exports.AstConstant = exports.Storage = exports.Stack = exports.Special = exports.Memory = exports.MappingKey = exports.Topic = exports.AbiData = exports.Bytes = exports.Basic = exports.abifyReturndataDecoding = exports.abifyLogDecoding = exports.abifyCalldataDecoding = exports.StopDecodingError = exports.DecodingError = exports.decodeRevert = exports.decodeReturndata = exports.decodeCalldata = exports.decodeEvent = exports.decodeVariable = exports.Format = void 0;
//So, what shall codec export...?
//First: export the data format
const Format = __importStar(__webpack_require__(429965));
exports.Format = Format;
//now... various low-level stuff we want to export!
//the actual decoding functions and related errors
var core_1 = __webpack_require__(632561);
Object.defineProperty(exports, "decodeVariable", ({ enumerable: true, get: function () { return core_1.decodeVariable; } }));
Object.defineProperty(exports, "decodeEvent", ({ enumerable: true, get: function () { return core_1.decodeEvent; } }));
Object.defineProperty(exports, "decodeCalldata", ({ enumerable: true, get: function () { return core_1.decodeCalldata; } }));
Object.defineProperty(exports, "decodeReturndata", ({ enumerable: true, get: function () { return core_1.decodeReturndata; } }));
Object.defineProperty(exports, "decodeRevert", ({ enumerable: true, get: function () { return core_1.decodeRevert; } }));
var errors_1 = __webpack_require__(672325);
Object.defineProperty(exports, "DecodingError", ({ enumerable: true, get: function () { return errors_1.DecodingError; } }));
Object.defineProperty(exports, "StopDecodingError", ({ enumerable: true, get: function () { return errors_1.StopDecodingError; } }));
__exportStar(__webpack_require__(299987), exports);
var abify_1 = __webpack_require__(57320);
Object.defineProperty(exports, "abifyCalldataDecoding", ({ enumerable: true, get: function () { return abify_1.abifyCalldataDecoding; } }));
Object.defineProperty(exports, "abifyLogDecoding", ({ enumerable: true, get: function () { return abify_1.abifyLogDecoding; } }));
Object.defineProperty(exports, "abifyReturndataDecoding", ({ enumerable: true, get: function () { return abify_1.abifyReturndataDecoding; } }));
// data locations - common
const Basic = __importStar(__webpack_require__(553928));
exports.Basic = Basic;
const Bytes = __importStar(__webpack_require__(767689));
exports.Bytes = Bytes;
// data locations - abi
const AbiData = __importStar(__webpack_require__(20907));
exports.AbiData = AbiData;
const Topic = __importStar(__webpack_require__(963196));
exports.Topic = Topic;
// data locations - solidity
const MappingKey = __importStar(__webpack_require__(514817));
exports.MappingKey = MappingKey;
const Memory = __importStar(__webpack_require__(635035));
exports.Memory = Memory;
const Special = __importStar(__webpack_require__(97859));
exports.Special = Special;
const Stack = __importStar(__webpack_require__(915385));
exports.Stack = Stack;
const Storage = __importStar(__webpack_require__(781037));
exports.Storage = Storage;
const AstConstant = __importStar(__webpack_require__(488132));
exports.AstConstant = AstConstant;
const Ast = __importStar(__webpack_require__(114442));
exports.Ast = Ast;
const Compiler = __importStar(__webpack_require__(884159));
exports.Compiler = Compiler;
const Compilations = __importStar(__webpack_require__(89752));
exports.Compilations = Compilations;
const Contexts = __importStar(__webpack_require__(697938));
exports.Contexts = Contexts;
const Conversion = __importStar(__webpack_require__(152714));
exports.Conversion = Conversion;
const Pointer = __importStar(__webpack_require__(560528));
exports.Pointer = Pointer;
const Evm = __importStar(__webpack_require__(149218));
exports.Evm = Evm;
const Export = __importStar(__webpack_require__(915103));
exports.Export = Export;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 210245:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mappingKeyAsHex = exports.encodeMappingKey = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:mapping-key:encode");
const Conversion = __importStar(__webpack_require__(152714));
const BasicEncode = __importStar(__webpack_require__(151561));
const BytesEncode = __importStar(__webpack_require__(553951));
//UGH -- it turns out TypeScript can't handle nested tagged unions
//see: https://github.com/microsoft/TypeScript/issues/18758
//so, I'm just going to have to throw in a bunch of type coercions >_>
/**
 * @Category Encoding (low-level)
 */
function encodeMappingKey(input) {
    if (input.type.typeClass === "string" ||
        (input.type.typeClass === "bytes" && input.type.kind === "dynamic")) {
        return BytesEncode.encodeBytes(input);
    }
    else {
        return BasicEncode.encodeBasic(input);
    }
}
exports.encodeMappingKey = encodeMappingKey;
/**
 * @Category Encoding (low-level)
 */
function mappingKeyAsHex(input) {
    return Conversion.toHexString(encodeMappingKey(input));
}
exports.mappingKeyAsHex = mappingKeyAsHex;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 514817:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Encode = void 0;
const Encode = __importStar(__webpack_require__(210245));
exports.Encode = Encode;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 359046:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isSkippedInMemoryStructs = exports.getMemoryAllocations = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:memory:allocate");
const Evm = __importStar(__webpack_require__(149218));
function getMemoryAllocations(userDefinedTypes) {
    let allocations = {};
    for (const dataType of Object.values(userDefinedTypes)) {
        if (dataType.typeClass === "struct") {
            allocations[dataType.id] = allocateStruct(dataType);
        }
    }
    return allocations;
}
exports.getMemoryAllocations = getMemoryAllocations;
function isSkippedInMemoryStructs(dataType) {
    if (dataType.typeClass === "mapping") {
        return true;
    }
    else if (dataType.typeClass === "array") {
        return isSkippedInMemoryStructs(dataType.baseType);
    }
    else {
        return false;
    }
}
exports.isSkippedInMemoryStructs = isSkippedInMemoryStructs;
//unlike in storage and calldata, we'll just return the one allocation, nothing fancy
//that's because allocating one struct can never necessitate allocating another
function allocateStruct(dataType) {
    let memberAllocations = [];
    let position = 0;
    for (const { name, type: memberType } of dataType.memberTypes) {
        const length = isSkippedInMemoryStructs(memberType)
            ? 0
            : Evm.Utils.WORD_SIZE;
        memberAllocations.push({
            name,
            type: memberType,
            pointer: {
                location: "memory",
                start: position,
                length
            }
        });
        position += length;
    }
    return {
        members: memberAllocations
    };
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 663540:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeMemoryReferenceByAddress = exports.decodeMemory = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:memory:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const Format = __importStar(__webpack_require__(429965));
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Evm = __importStar(__webpack_require__(149218));
const allocate_1 = __webpack_require__(359046);
const errors_1 = __webpack_require__(672325);
function* decodeMemory(dataType, pointer, info, options = {}) {
    if (Format.Types.isReferenceType(dataType)) {
        if (allocate_1.isSkippedInMemoryStructs(dataType)) {
            //special case; these types are always empty in memory
            return decodeMemorySkippedType(dataType);
        }
        else {
            return yield* decodeMemoryReferenceByAddress(dataType, pointer, info, options);
        }
    }
    else {
        return yield* Basic.Decode.decodeBasic(dataType, pointer, info, options);
    }
}
exports.decodeMemory = decodeMemory;
function decodeMemorySkippedType(dataType) {
    switch (dataType.typeClass) {
        case "mapping":
            return {
                type: dataType,
                kind: "value",
                value: []
            };
        case "array":
            return {
                type: dataType,
                kind: "value",
                value: []
            };
        //other cases should not arise!
    }
}
function* decodeMemoryReferenceByAddress(dataType, pointer, info, options = {}) {
    const { state } = info;
    const memoryVisited = options.memoryVisited || [];
    debug("pointer %o", pointer);
    let rawValue;
    try {
        rawValue = yield* read_1.default(pointer, state);
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error);
    }
    let startPositionAsBN = Conversion.toBN(rawValue);
    let startPosition;
    try {
        startPosition = startPositionAsBN.toNumber();
    }
    catch (_a) {
        return {
            //again with the TS failures...
            type: dataType,
            kind: "error",
            error: {
                kind: "OverlargePointersNotImplementedError",
                pointerAsBN: startPositionAsBN
            }
        };
    }
    //startPosition may get modified later, so let's save the current
    //value for circularity detection purposes
    const objectPosition = startPosition;
    let rawLength;
    let lengthAsBN;
    let length;
    let seenPreviously;
    switch (dataType.typeClass) {
        case "bytes":
        case "string":
            //initial word contains length
            try {
                rawLength = yield* read_1.default({
                    location: "memory",
                    start: startPosition,
                    length: Evm.Utils.WORD_SIZE
                }, state);
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error);
            }
            lengthAsBN = Conversion.toBN(rawLength);
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_b) {
                return {
                    //again with the TS failures...
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "OverlongArraysAndStringsNotImplementedError",
                        lengthAsBN
                    }
                };
            }
            let childPointer = {
                location: "memory",
                start: startPosition + Evm.Utils.WORD_SIZE,
                length
            };
            return yield* Bytes.Decode.decodeBytes(dataType, childPointer, info);
        case "array": {
            //first: circularity check!
            seenPreviously = memoryVisited.indexOf(objectPosition);
            if (seenPreviously !== -1) {
                return {
                    type: dataType,
                    kind: "value",
                    reference: seenPreviously + 1,
                    value: [] //will be fixed later by the tie function
                };
            }
            //otherwise, decode as normal
            if (dataType.kind === "dynamic") {
                //initial word contains array length
                try {
                    rawLength = yield* read_1.default({
                        location: "memory",
                        start: startPosition,
                        length: Evm.Utils.WORD_SIZE
                    }, state);
                }
                catch (error) {
                    return errors_1.handleDecodingError(dataType, error);
                }
                lengthAsBN = Conversion.toBN(rawLength);
                startPosition += Evm.Utils.WORD_SIZE; //increment startPosition
                //to next word, as first word was used for length
            }
            else {
                lengthAsBN = dataType.length;
            }
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_c) {
                return {
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "OverlongArraysAndStringsNotImplementedError",
                        lengthAsBN
                    }
                };
            }
            let memoryNowVisited = [objectPosition, ...memoryVisited];
            let baseType = dataType.baseType;
            let decodedChildren = [];
            for (let index = 0; index < length; index++) {
                decodedChildren.push(yield* decodeMemory(baseType, {
                    location: "memory",
                    start: startPosition + index * Evm.Utils.WORD_SIZE,
                    length: Evm.Utils.WORD_SIZE
                }, info, { memoryVisited: memoryNowVisited }));
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedChildren
            };
        }
        case "struct": {
            //first: circularity check!
            seenPreviously = memoryVisited.indexOf(objectPosition);
            if (seenPreviously !== -1) {
                return {
                    type: dataType,
                    kind: "value",
                    reference: seenPreviously + 1,
                    value: [] //will be fixed later by the tie function
                };
            }
            //otherwise, decode as normal
            const { allocations: { memory: allocations } } = info;
            const typeId = dataType.id;
            const structAllocation = allocations[typeId];
            if (!structAllocation) {
                return {
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "UserDefinedTypeNotFoundError",
                        type: dataType
                    }
                };
            }
            debug("structAllocation %O", structAllocation);
            let memoryNowVisited = [objectPosition, ...memoryVisited];
            let decodedMembers = [];
            for (let index = 0; index < structAllocation.members.length; index++) {
                const memberAllocation = structAllocation.members[index];
                const memberPointer = memberAllocation.pointer;
                const childPointer = {
                    location: "memory",
                    start: startPosition + memberPointer.start,
                    length: memberPointer.length //always equals WORD_SIZE or 0
                };
                let memberName = memberAllocation.name;
                let memberType = Format.Types.specifyLocation(memberAllocation.type, "memory");
                decodedMembers.push({
                    name: memberName,
                    value: yield* decodeMemory(memberType, childPointer, info, {
                        memoryVisited: memoryNowVisited
                    })
                });
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedMembers
            };
        }
    }
}
exports.decodeMemoryReferenceByAddress = decodeMemoryReferenceByAddress;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 635035:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Decode = exports.Allocate = void 0;
const Allocate = __importStar(__webpack_require__(359046));
exports.Allocate = Allocate;
const Decode = __importStar(__webpack_require__(663540));
exports.Decode = Decode;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 560528:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
__exportStar(__webpack_require__(110315), exports);
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 110315:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 887534:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const StorageRead = __importStar(__webpack_require__(165135));
const StackRead = __importStar(__webpack_require__(709940));
const BytesRead = __importStar(__webpack_require__(720281));
const AstConstantRead = __importStar(__webpack_require__(538130));
const TopicRead = __importStar(__webpack_require__(61352));
const SpecialRead = __importStar(__webpack_require__(595884));
const errors_1 = __webpack_require__(672325);
function* read(pointer, state) {
    switch (pointer.location) {
        case "stack":
            return StackRead.readStack(pointer, state);
        case "storage":
            return yield* StorageRead.readStorage(pointer, state);
        case "memory":
        case "calldata":
        case "eventdata":
        case "returndata":
            return BytesRead.readBytes(pointer, state);
        case "code":
            //keeping this separate
            return yield* BytesRead.readCode(pointer, state);
        case "stackliteral":
            return StackRead.readStackLiteral(pointer);
        case "definition":
            return AstConstantRead.readDefinition(pointer);
        case "special":
            return SpecialRead.readSpecial(pointer, state);
        case "eventtopic":
            return TopicRead.readTopic(pointer, state);
        case "nowhere":
            throw new errors_1.DecodingError({
                kind: "UnusedImmutableError"
            });
    }
}
exports.default = read;
//# sourceMappingURL=read.js.map

/***/ }),

/***/ 311002:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeMagic = exports.decodeSpecial = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:special:decode");
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Compiler = __importStar(__webpack_require__(884159));
const Evm = __importStar(__webpack_require__(149218));
function* decodeSpecial(dataType, pointer, info) {
    if (dataType.typeClass === "magic") {
        return yield* decodeMagic(dataType, pointer, info);
    }
    else {
        return yield* Basic.Decode.decodeBasic(dataType, pointer, info);
    }
}
exports.decodeSpecial = decodeSpecial;
function* decodeMagic(dataType, pointer, info) {
    let { state } = info;
    switch (pointer.special) {
        case "msg":
            return {
                type: dataType,
                kind: "value",
                value: {
                    data: yield* Bytes.Decode.decodeBytes({
                        typeClass: "bytes",
                        kind: "dynamic",
                        location: "calldata"
                    }, {
                        location: "calldata",
                        start: 0,
                        length: state.calldata.length
                    }, info),
                    sig: yield* Basic.Decode.decodeBasic({
                        typeClass: "bytes",
                        kind: "static",
                        length: Evm.Utils.SELECTOR_SIZE
                    }, {
                        location: "calldata",
                        start: 0,
                        length: Evm.Utils.SELECTOR_SIZE
                    }, info),
                    sender: yield* Basic.Decode.decodeBasic(senderType(info.currentContext.compiler), { location: "special", special: "sender" }, info),
                    value: yield* Basic.Decode.decodeBasic({
                        typeClass: "uint",
                        bits: 256
                    }, { location: "special", special: "value" }, info)
                }
            };
        case "tx":
            return {
                type: dataType,
                kind: "value",
                value: {
                    origin: yield* Basic.Decode.decodeBasic(senderType(info.currentContext.compiler), { location: "special", special: "origin" }, info),
                    gasprice: yield* Basic.Decode.decodeBasic({
                        typeClass: "uint",
                        bits: 256
                    }, { location: "special", special: "gasprice" }, info)
                }
            };
        case "block":
            let block = {
                coinbase: yield* Basic.Decode.decodeBasic(coinbaseType(info.currentContext.compiler), { location: "special", special: "coinbase" }, info)
            };
            //the other ones are all uint's, so let's handle them all at once; due to
            //the lack of generator arrow functions, we do it by mutating block
            const variables = ["difficulty", "gaslimit", "number", "timestamp"];
            if (solidityVersionHasChainId(info.currentContext.compiler)) {
                variables.push("chainid");
            }
            for (let variable of variables) {
                block[variable] = yield* Basic.Decode.decodeBasic({
                    typeClass: "uint",
                    bits: 256
                }, { location: "special", special: variable }, info);
            }
            return {
                type: dataType,
                kind: "value",
                value: block
            };
    }
}
exports.decodeMagic = decodeMagic;
function senderType(compiler) {
    switch (Compiler.Utils.solidityFamily(compiler)) {
        case "unknown":
        case "pre-0.5.0":
            return {
                typeClass: "address",
                kind: "general"
            };
        case "0.5.x":
            return {
                typeClass: "address",
                kind: "specific",
                payable: true
            };
        case "0.8.x":
            return {
                typeClass: "address",
                kind: "specific",
                payable: false
            };
    }
}
function coinbaseType(compiler) {
    switch (Compiler.Utils.solidityFamily(compiler)) {
        case "unknown":
        case "pre-0.5.0":
            return {
                typeClass: "address",
                kind: "general"
            };
        case "0.5.x":
        case "0.8.x":
            return {
                typeClass: "address",
                kind: "specific",
                payable: true
            };
    }
}
function solidityVersionHasChainId(compiler) {
    switch (Compiler.Utils.solidityFamily(compiler)) {
        case "unknown":
        case "pre-0.5.0":
        case "0.5.x":
            return false;
        case "0.8.x":
            return true;
    }
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 97859:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Read = exports.Decode = void 0;
const Decode = __importStar(__webpack_require__(311002));
exports.Decode = Decode;
const Read = __importStar(__webpack_require__(595884));
exports.Read = Read;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 595884:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readSpecial = void 0;
function readSpecial(pointer, state) {
    //not bothering with error handling on this one as I don't expect errors
    return state.specials[pointer.special];
}
exports.readSpecial = readSpecial;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 671013:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeLiteral = exports.decodeStack = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:stack:decode");
const AbiData = __importStar(__webpack_require__(20907));
const Conversion = __importStar(__webpack_require__(152714));
const Format = __importStar(__webpack_require__(429965));
const read_1 = __importDefault(__webpack_require__(887534));
const Basic = __importStar(__webpack_require__(553928));
const Memory = __importStar(__webpack_require__(635035));
const Storage = __importStar(__webpack_require__(781037));
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
function* decodeStack(dataType, pointer, info) {
    let rawValue;
    try {
        rawValue = yield* read_1.default(pointer, info.state);
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error);
    }
    const literalPointer = {
        location: "stackliteral",
        literal: rawValue
    };
    return yield* decodeLiteral(dataType, literalPointer, info);
}
exports.decodeStack = decodeStack;
function* decodeLiteral(dataType, pointer, info) {
    debug("type %O", dataType);
    debug("pointer %o", pointer);
    if (Format.Types.isReferenceType(dataType)) {
        switch (dataType.location) {
            case "memory":
                //first: do we have a memory pointer? if so we can just dispatch to
                //decodeMemoryReference
                return yield* Memory.Decode.decodeMemoryReferenceByAddress(dataType, pointer, info);
            case "storage":
                //next: do we have a storage pointer (which may be a mapping)? if so, we can
                //we dispatch to decodeStorageByAddress
                return yield* Storage.Decode.decodeStorageReferenceByAddress(dataType, pointer, info);
            case "calldata":
                //next: do we have a calldata pointer?
                //if it's a lookup type, it'll need special handling
                if (dataType.typeClass === "bytes" ||
                    dataType.typeClass === "string" ||
                    (dataType.typeClass === "array" && dataType.kind === "dynamic")) {
                    const lengthAsBN = Conversion.toBN(pointer.literal.slice(Evm.Utils.WORD_SIZE));
                    const locationOnly = pointer.literal.slice(0, Evm.Utils.WORD_SIZE);
                    return yield* AbiData.Decode.decodeAbiReferenceByAddress(dataType, { location: "stackliteral", literal: locationOnly }, info, {
                        abiPointerBase: 0,
                        lengthOverride: lengthAsBN
                    });
                }
                else {
                    //multivalue case -- this case is straightforward
                    return yield* AbiData.Decode.decodeAbiReferenceByAddress(dataType, pointer, info, {
                        abiPointerBase: 0 //let's be explicit
                    });
                }
        }
    }
    //next: do we have an external function?  these work differently on the stack
    //than elsewhere, so we can't just pass it on to decodeBasic.
    if (dataType.typeClass === "function" && dataType.visibility === "external") {
        let address = pointer.literal.slice(0, Evm.Utils.WORD_SIZE);
        let selectorWord = pointer.literal.slice(-Evm.Utils.WORD_SIZE);
        if (!Basic.Decode.checkPaddingLeft(address, Evm.Utils.ADDRESS_SIZE) ||
            !Basic.Decode.checkPaddingLeft(selectorWord, Evm.Utils.SELECTOR_SIZE)) {
            return {
                type: dataType,
                kind: "error",
                error: {
                    kind: "FunctionExternalStackPaddingError",
                    rawAddress: Conversion.toHexString(address),
                    rawSelector: Conversion.toHexString(selectorWord)
                }
            };
        }
        let selector = selectorWord.slice(-Evm.Utils.SELECTOR_SIZE);
        return {
            type: dataType,
            kind: "value",
            value: yield* Basic.Decode.decodeExternalFunction(address, selector, info)
        };
    }
    //finally, if none of the above hold, we can just dispatch to decodeBasic.
    //however, note that because we're on the stack, we use the permissive padding
    //option so that errors won't result due to values with bad padding
    //(of numeric or bytesN type, anyway)
    return yield* Basic.Decode.decodeBasic(dataType, pointer, info, {
        paddingMode: "permissive"
    });
}
exports.decodeLiteral = decodeLiteral;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 915385:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Read = exports.Decode = void 0;
const Decode = __importStar(__webpack_require__(671013));
exports.Decode = Decode;
const Read = __importStar(__webpack_require__(709940));
exports.Read = Read;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 709940:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readStackLiteral = exports.readStack = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:stack:read");
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
function readStack(pointer, state) {
    let { from, to } = pointer;
    let { stack } = state;
    if (from < 0 || to >= stack.length) {
        throw new errors_1.DecodingError({
            kind: "ReadErrorStack",
            from,
            to
        });
    }
    //unforunately, Uint8Arrays don't support concat; if they did the rest of
    //this would be one line.  Or similarly if they worked with lodash's flatten,
    //but they don't support that either.  But neither of those are the case, so
    //we'll have to concatenate a bit more manually.
    let words = stack.slice(from, to + 1);
    let result = new Uint8Array(words.length * Evm.Utils.WORD_SIZE);
    //shouldn't we total up the lengths? yeah, but each one should have a
    //length of 32, so unless somehting's gone wrong we can just multiply
    for (let index = 0; index < words.length; index++) {
        result.set(words[index], index * Evm.Utils.WORD_SIZE);
    }
    return result;
}
exports.readStack = readStack;
function readStackLiteral(pointer) {
    return pointer.literal;
}
exports.readStackLiteral = readStackLiteral;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 478976:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.storageSize = exports.getStateAllocations = exports.getStorageAllocations = exports.UnknownBaseContractIdError = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:storage:allocate");
const Common = __importStar(__webpack_require__(299987));
const Basic = __importStar(__webpack_require__(553928));
const Utils = __importStar(__webpack_require__(142526));
const Ast = __importStar(__webpack_require__(114442));
const Evm = __importStar(__webpack_require__(149218));
const Format = __importStar(__webpack_require__(429965));
const bn_js_1 = __importDefault(__webpack_require__(213550));
const lodash_partition_1 = __importDefault(__webpack_require__(246748));
class UnknownBaseContractIdError extends Error {
    constructor(derivedId, derivedName, derivedKind, baseId) {
        const message = `Cannot locate base contract ID ${baseId} of ${derivedKind} ${derivedName} (ID ${derivedId})`;
        super(message);
        this.name = "UnknownBaseContractIdError";
        this.derivedId = derivedId;
        this.derivedName = derivedName;
        this.derivedKind = derivedKind;
        this.baseId = baseId;
    }
}
exports.UnknownBaseContractIdError = UnknownBaseContractIdError;
//contracts contains only the contracts to be allocated; any base classes not
//being allocated should just be in referenceDeclarations
function getStorageAllocations(userDefinedTypes) {
    let allocations = {};
    for (const dataType of Object.values(userDefinedTypes)) {
        if (dataType.typeClass === "struct") {
            try {
                allocations = allocateStruct(dataType, userDefinedTypes, allocations);
            }
            catch (_) {
                //if allocation fails... oh well, allocation fails, we do nothing and just move on :P
                //note: a better way of handling this would probably be to *mark* it
                //as failed rather than throwing an exception as that would lead to less
                //recomputation, but this is simpler and I don't think the recomputation
                //should really be a problem
            }
        }
    }
    return allocations;
}
exports.getStorageAllocations = getStorageAllocations;
/**
 * This function gets allocations for the state variables of the contracts;
 * this is distinct from getStorageAllocations, which gets allocations for
 * storage structs.
 *
 * While mostly state variables are kept in storage, constant ones are not.
 * And immutable ones, once those are introduced, will be kept in code!
 * (But those don't exist yet so this function doesn't handle them yet.)
 */
function getStateAllocations(contracts, referenceDeclarations, userDefinedTypes, storageAllocations, existingAllocations = {}) {
    let allocations = existingAllocations;
    for (const contractInfo of contracts) {
        let { contractNode: contract, immutableReferences, compiler, compilationId } = contractInfo;
        try {
            allocations = allocateContractState(contract, immutableReferences, compilationId, compiler, referenceDeclarations[compilationId], userDefinedTypes, storageAllocations, allocations);
        }
        catch (_) {
            //we're just going to allow failure here and catch the problem elsewhere
        }
    }
    return allocations;
}
exports.getStateAllocations = getStateAllocations;
function allocateStruct(dataType, userDefinedTypes, existingAllocations) {
    //NOTE: dataType here should be a *stored* type!
    //it is up to the caller to take care of this
    return allocateMembers(dataType.id, dataType.memberTypes, userDefinedTypes, existingAllocations);
}
function allocateMembers(parentId, members, userDefinedTypes, existingAllocations) {
    let offset = 0; //will convert to BN when placing in slot
    let index = Evm.Utils.WORD_SIZE - 1;
    //don't allocate things that have already been allocated
    if (parentId in existingAllocations) {
        return existingAllocations;
    }
    let allocations = Object.assign({}, existingAllocations); //otherwise, we'll be adding to this, so we better clone
    //otherwise, we need to allocate
    let memberAllocations = [];
    for (const member of members) {
        let size;
        ({ size, allocations } = storageSizeAndAllocate(member.type, userDefinedTypes, allocations));
        //if it's sized in words (and we're not at the start of slot) we need to start on a new slot
        //if it's sized in bytes but there's not enough room, we also need a new slot
        if (Utils.isWordsLength(size)
            ? index < Evm.Utils.WORD_SIZE - 1
            : size.bytes > index + 1) {
            index = Evm.Utils.WORD_SIZE - 1;
            offset += 1;
        }
        //otherwise, we remain in place
        let range;
        if (Utils.isWordsLength(size)) {
            //words case
            range = {
                from: {
                    slot: {
                        offset: new bn_js_1.default(offset) //start at the current slot...
                    },
                    index: 0 //...at the beginning of the word.
                },
                to: {
                    slot: {
                        offset: new bn_js_1.default(offset + size.words - 1) //end at the current slot plus # of words minus 1...
                    },
                    index: Evm.Utils.WORD_SIZE - 1 //...at the end of the word.
                }
            };
        }
        else {
            //bytes case
            range = {
                from: {
                    slot: {
                        offset: new bn_js_1.default(offset) //start at the current slot...
                    },
                    index: index - (size.bytes - 1) //...early enough to fit what's being allocated.
                },
                to: {
                    slot: {
                        offset: new bn_js_1.default(offset) //end at the current slot...
                    },
                    index: index //...at the current position.
                }
            };
        }
        memberAllocations.push({
            name: member.name,
            type: member.type,
            pointer: {
                location: "storage",
                range
            }
        });
        //finally, adjust the current position.
        //if it was sized in words, move down that many slots and reset position w/in slot
        if (Utils.isWordsLength(size)) {
            offset += size.words;
            index = Evm.Utils.WORD_SIZE - 1;
        }
        //if it was sized in bytes, move down an appropriate number of bytes.
        else {
            index -= size.bytes;
            //but if this puts us into the next word, move to the next word.
            if (index < 0) {
                index = Evm.Utils.WORD_SIZE - 1;
                offset += 1;
            }
        }
    }
    //finally, let's determine the overall siz; we're dealing with a struct, so
    //the size is measured in words
    //it's one plus the last word used, i.e. one plus the current word... unless the
    //current word remains entirely unused, then it's just the current word
    //SPECIAL CASE: if *nothing* has been used, allocate a single word (that's how
    //empty structs behave in versions where they're legal)
    let totalSize;
    if (index === Evm.Utils.WORD_SIZE - 1 && offset !== 0) {
        totalSize = { words: offset };
    }
    else {
        totalSize = { words: offset + 1 };
    }
    //having made our allocation, let's add it to allocations!
    allocations[parentId] = {
        members: memberAllocations,
        size: totalSize
    };
    //...and we're done!
    return allocations;
}
function getStateVariables(contractNode) {
    // process for state variables
    return contractNode.nodes.filter((node) => node.nodeType === "VariableDeclaration" && node.stateVariable);
}
function allocateContractState(contract, immutableReferences, compilationId, compiler, referenceDeclarations, userDefinedTypes, storageAllocations, existingAllocations = {}) {
    //we're going to do a 2-deep clone here
    let allocations = Object.assign({}, ...Object.entries(existingAllocations).map(([compilationId, compilationAllocations]) => ({
        [compilationId]: Object.assign({}, compilationAllocations)
    })));
    if (!immutableReferences) {
        immutableReferences = {}; //also, let's set this up for convenience
    }
    //base contracts are listed from most derived to most base, so we
    //have to reverse before processing, but reverse() is in place, so we
    //clone with slice first
    let linearizedBaseContractsFromBase = contract.linearizedBaseContracts
        .slice()
        .reverse();
    //first, let's get all the variables under consideration
    let variables = [].concat(...linearizedBaseContractsFromBase.map((id) => {
        let baseNode = referenceDeclarations[id];
        if (baseNode === undefined) {
            throw new UnknownBaseContractIdError(contract.id, contract.name, contract.contractKind, id);
        }
        return getStateVariables(baseNode).map(definition => ({
            definition,
            definedIn: baseNode
        }));
    }));
    //just in case the constant field ever gets removed
    const isConstant = (definition) => definition.constant || definition.mutability === "constant";
    //now: we split the variables into storage, constant, and code
    let [constantVariables, variableVariables] = lodash_partition_1.default(variables, variable => isConstant(variable.definition));
    //why use this function instead of just checking
    //definition.mutability?
    //because of a bug in Solidity 0.6.5 that causes the mutability field
    //not to exist.  So, we also have to check against immutableReferences.
    const isImmutable = (definition) => definition.mutability === "immutable" ||
        definition.id.toString() in immutableReferences;
    let [immutableVariables, storageVariables] = lodash_partition_1.default(variableVariables, variable => isImmutable(variable.definition));
    //transform storage variables into data types
    let storageVariableTypes = storageVariables.map(variable => ({
        name: variable.definition.name,
        type: Ast.Import.definitionToType(variable.definition, compilationId, compiler)
    }));
    //let's allocate the storage variables using a fictitious ID
    const id = "-1";
    let storageVariableStorageAllocations = allocateMembers(id, storageVariableTypes, userDefinedTypes, storageAllocations)[id];
    //transform to new format
    let storageVariableAllocations = storageVariables.map(({ definition, definedIn }, index) => ({
        definition,
        definedIn,
        compilationId,
        pointer: storageVariableStorageAllocations.members[index].pointer
    }));
    //now let's create allocations for the immutables
    let immutableVariableAllocations = immutableVariables.map(({ definition, definedIn }) => {
        let references = immutableReferences[definition.id.toString()] || [];
        let pointer;
        if (references.length === 0) {
            pointer = {
                location: "nowhere"
            };
        }
        else {
            pointer = {
                location: "code",
                start: references[0].start,
                length: references[0].length
            };
        }
        return {
            definition,
            definedIn,
            compilationId,
            pointer
        };
    });
    //and let's create allocations for the constants
    let constantVariableAllocations = constantVariables.map(({ definition, definedIn }) => ({
        definition,
        definedIn,
        compilationId,
        pointer: {
            location: "definition",
            definition: definition.value
        }
    }));
    //now, reweave the three together
    let contractAllocation = [];
    for (let variable of variables) {
        let arrayToGrabFrom = isConstant(variable.definition)
            ? constantVariableAllocations
            : isImmutable(variable.definition)
                ? immutableVariableAllocations
                : storageVariableAllocations;
        contractAllocation.push(arrayToGrabFrom.shift()); //note that push and shift both modify!
    }
    //finally, set things and return
    if (!allocations[compilationId]) {
        allocations[compilationId] = {};
    }
    allocations[compilationId][contract.id] = {
        members: contractAllocation
    };
    return allocations;
}
//NOTE: This wrapper function is for use in decoding ONLY, after allocation is done.
//The allocator should (and does) instead use a direct call to storageSizeAndAllocate,
//not to the wrapper, because it may need the allocations returned.
function storageSize(dataType, userDefinedTypes, allocations) {
    return storageSizeAndAllocate(dataType, userDefinedTypes, allocations).size;
}
exports.storageSize = storageSize;
function storageSizeAndAllocate(dataType, userDefinedTypes, existingAllocations) {
    //we'll only directly handle reference types here;
    //direct types will be handled by dispatching to Basic.Allocate.byteLength
    //in the default case
    switch (dataType.typeClass) {
        case "bytes": {
            switch (dataType.kind) {
                case "static":
                    //really a basic type :)
                    return {
                        size: {
                            bytes: Basic.Allocate.byteLength(dataType, userDefinedTypes)
                        },
                        allocations: existingAllocations
                    };
                case "dynamic":
                    return {
                        size: { words: 1 },
                        allocations: existingAllocations
                    };
            }
        }
        case "string":
        case "mapping":
            return {
                size: { words: 1 },
                allocations: existingAllocations
            };
        case "array": {
            switch (dataType.kind) {
                case "dynamic":
                    return {
                        size: { words: 1 },
                        allocations: existingAllocations
                    };
                case "static":
                    //static array case
                    const length = dataType.length.toNumber(); //warning! but if it's too big we have a problem
                    if (length === 0) {
                        //in versions of Solidity where it's legal, arrays of length 0 still take up 1 word
                        return {
                            size: { words: 1 },
                            allocations: existingAllocations
                        };
                    }
                    let { size: baseSize, allocations } = storageSizeAndAllocate(dataType.baseType, userDefinedTypes, existingAllocations);
                    if (!Utils.isWordsLength(baseSize)) {
                        //bytes case
                        const perWord = Math.floor(Evm.Utils.WORD_SIZE / baseSize.bytes);
                        debug("length %o", length);
                        const numWords = Math.ceil(length / perWord);
                        return {
                            size: { words: numWords },
                            allocations
                        };
                    }
                    else {
                        //words case
                        return {
                            size: { words: baseSize.words * length },
                            allocations
                        };
                    }
            }
        }
        case "struct": {
            let allocations = existingAllocations;
            let allocation = allocations[dataType.id]; //may be undefined!
            if (allocation === undefined) {
                //if we don't find an allocation, we'll have to do the allocation ourselves
                const storedType = (userDefinedTypes[dataType.id]);
                if (!storedType) {
                    throw new Common.UnknownUserDefinedTypeError(dataType.id, Format.Types.typeString(dataType));
                }
                allocations = allocateStruct(storedType, userDefinedTypes, existingAllocations);
                allocation = allocations[dataType.id];
            }
            //having found our allocation, we can just look up its size
            return {
                size: allocation.size,
                allocations
            };
        }
        default:
            //otherwise, it's a direct type
            return {
                size: { bytes: Basic.Allocate.byteLength(dataType, userDefinedTypes) },
                allocations: existingAllocations
            };
    }
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 888569:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeStorageReference = exports.decodeStorageReferenceByAddress = exports.decodeStorage = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:storage:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Conversion = __importStar(__webpack_require__(152714));
const Format = __importStar(__webpack_require__(429965));
const Basic = __importStar(__webpack_require__(553928));
const Bytes = __importStar(__webpack_require__(767689));
const Utils = __importStar(__webpack_require__(142526));
const Evm = __importStar(__webpack_require__(149218));
const allocate_1 = __webpack_require__(478976);
const bn_js_1 = __importDefault(__webpack_require__(213550));
const errors_1 = __webpack_require__(672325);
function* decodeStorage(dataType, pointer, info) {
    if (Format.Types.isReferenceType(dataType)) {
        return yield* decodeStorageReference(dataType, pointer, info);
    }
    else {
        return yield* Basic.Decode.decodeBasic(dataType, pointer, info);
    }
}
exports.decodeStorage = decodeStorage;
//decodes storage at the address *read* from the pointer -- hence why this takes DataPointer rather than StoragePointer.
//NOTE: ONLY for use with pointers to reference types!
//Of course, pointers to value types don't exist in Solidity, so that warning is redundant, but...
function* decodeStorageReferenceByAddress(dataType, pointer, info) {
    const allocations = info.allocations.storage;
    let rawValue;
    try {
        rawValue = yield* read_1.default(pointer, info.state);
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error);
    }
    const startOffset = Conversion.toBN(rawValue);
    let rawSize;
    try {
        rawSize = allocate_1.storageSize(dataType, info.userDefinedTypes, allocations);
    }
    catch (error) {
        return errors_1.handleDecodingError(dataType, error);
    }
    //we *know* the type being decoded must be sized in words, because it's a
    //reference type, but TypeScript doesn't, so we'll have to use a type
    //coercion
    const size = rawSize.words;
    //now, construct the storage pointer
    const newPointer = {
        location: "storage",
        range: {
            from: {
                slot: {
                    offset: startOffset
                },
                index: 0
            },
            to: {
                slot: {
                    offset: startOffset.addn(size - 1)
                },
                index: Evm.Utils.WORD_SIZE - 1
            }
        }
    };
    //dispatch to decodeStorageReference
    return yield* decodeStorageReference(dataType, newPointer, info);
}
exports.decodeStorageReferenceByAddress = decodeStorageReferenceByAddress;
function* decodeStorageReference(dataType, pointer, info) {
    var data;
    var length;
    const { state } = info;
    const allocations = info.allocations.storage;
    switch (dataType.typeClass) {
        case "array": {
            debug("storage array! %o", pointer);
            let lengthAsBN;
            switch (dataType.kind) {
                case "dynamic":
                    debug("dynamic array");
                    debug("type %O", dataType);
                    try {
                        data = yield* read_1.default(pointer, state);
                    }
                    catch (error) {
                        return errors_1.handleDecodingError(dataType, error);
                    }
                    lengthAsBN = Conversion.toBN(data);
                    break;
                case "static":
                    debug("static array");
                    lengthAsBN = dataType.length;
                    break;
            }
            try {
                length = lengthAsBN.toNumber();
            }
            catch (_a) {
                return {
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "OverlongArraysAndStringsNotImplementedError",
                        lengthAsBN
                    }
                };
            }
            debug("length %o", length);
            debug("about to determine baseSize");
            let baseSize;
            try {
                baseSize = allocate_1.storageSize(dataType.baseType, info.userDefinedTypes, allocations);
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error);
            }
            debug("baseSize %o", baseSize);
            //we are going to make a list of child ranges, pushing them one by one onto
            //this list, and then decode them; the first part will vary based on whether
            //we're in the words case or the bytes case, the second will not
            let ranges = [];
            if (Utils.isWordsLength(baseSize)) {
                //currentSlot will point to the start of the entry being decoded
                let currentSlot = {
                    path: pointer.range.from.slot,
                    offset: new bn_js_1.default(0),
                    hashPath: dataType.kind === "dynamic"
                };
                for (let i = 0; i < length; i++) {
                    let childRange = {
                        from: {
                            slot: {
                                path: currentSlot.path,
                                offset: currentSlot.offset.clone(),
                                hashPath: currentSlot.hashPath
                            },
                            index: 0
                        },
                        to: {
                            slot: {
                                path: currentSlot.path,
                                offset: currentSlot.offset.addn(baseSize.words - 1),
                                hashPath: currentSlot.hashPath
                            },
                            index: Evm.Utils.WORD_SIZE - 1
                        }
                    };
                    ranges.push(childRange);
                    currentSlot.offset.iaddn(baseSize.words);
                }
            }
            else {
                const perWord = Math.floor(Evm.Utils.WORD_SIZE / baseSize.bytes);
                debug("perWord %d", perWord);
                //currentPosition will point to the start of the entry being decoded
                //note we have baseSize.bytes <= Evm.Utils.WORD_SIZE
                let currentPosition = {
                    slot: {
                        path: pointer.range.from.slot,
                        offset: new bn_js_1.default(0),
                        hashPath: dataType.kind === "dynamic"
                    },
                    index: Evm.Utils.WORD_SIZE - baseSize.bytes //note the starting index!
                };
                for (let i = 0; i < length; i++) {
                    let childRange = {
                        from: {
                            slot: {
                                path: currentPosition.slot.path,
                                offset: currentPosition.slot.offset.clone(),
                                hashPath: currentPosition.slot.hashPath
                            },
                            index: currentPosition.index
                        },
                        length: baseSize.bytes
                    };
                    ranges.push(childRange);
                    currentPosition.index -= baseSize.bytes;
                    if (currentPosition.index < 0) {
                        currentPosition.slot.offset.iaddn(1);
                        currentPosition.index = Evm.Utils.WORD_SIZE - baseSize.bytes;
                    }
                }
            }
            let decodedChildren = [];
            for (let childRange of ranges) {
                decodedChildren.push(yield* decodeStorage(dataType.baseType, { location: "storage", range: childRange }, info));
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedChildren
            };
        }
        case "bytes":
        case "string": {
            try {
                data = yield* read_1.default(pointer, state);
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error);
            }
            let lengthByte = data[Evm.Utils.WORD_SIZE - 1];
            if (lengthByte % 2 == 0) {
                // string lives in word, length is last byte / 2
                length = lengthByte / 2;
                debug("in-word; length %o", length);
                return yield* Bytes.Decode.decodeBytes(dataType, {
                    location: "storage",
                    range: {
                        from: { slot: pointer.range.from.slot, index: 0 },
                        to: { slot: pointer.range.from.slot, index: length - 1 }
                    }
                }, info);
            }
            else {
                let lengthAsBN = Conversion.toBN(data)
                    .subn(1)
                    .divn(2);
                try {
                    length = lengthAsBN.toNumber();
                }
                catch (_b) {
                    return {
                        //again with the TS failures...
                        type: dataType,
                        kind: "error",
                        error: {
                            kind: "OverlongArraysAndStringsNotImplementedError",
                            lengthAsBN
                        }
                    };
                }
                debug("new-word, length %o", length);
                return yield* Bytes.Decode.decodeBytes(dataType, {
                    location: "storage",
                    range: {
                        from: {
                            slot: {
                                path: pointer.range.from.slot,
                                offset: new bn_js_1.default(0),
                                hashPath: true
                            },
                            index: 0
                        },
                        length
                    }
                }, info);
            }
        }
        case "struct": {
            const typeId = dataType.id;
            const structAllocation = allocations[typeId];
            if (!structAllocation) {
                return {
                    type: dataType,
                    kind: "error",
                    error: {
                        kind: "UserDefinedTypeNotFoundError",
                        type: dataType
                    }
                };
            }
            let decodedMembers = [];
            const members = structAllocation.members;
            for (let index = 0; index < members.length; index++) {
                const memberAllocation = members[index];
                const memberPointer = memberAllocation.pointer;
                //the type system thinks memberPointer might also be a constant
                //definition pointer.  However, structs can't contain constants,
                //so *we* know it's not, and can safely coerce it.
                debug("pointer %O", pointer);
                const childRange = {
                    from: {
                        slot: {
                            path: pointer.range.from.slot,
                            offset: memberPointer.range.from.slot.offset.clone()
                            //note that memberPointer should have no path
                        },
                        index: memberPointer.range.from.index
                    },
                    to: {
                        slot: {
                            path: pointer.range.from.slot,
                            offset: memberPointer.range.to.slot.offset.clone()
                            //note that memberPointer should have no path
                        },
                        index: memberPointer.range.to.index
                    }
                };
                let storedType = info.userDefinedTypes[typeId];
                if (!storedType) {
                    return {
                        type: dataType,
                        kind: "error",
                        error: {
                            kind: "UserDefinedTypeNotFoundError",
                            type: dataType
                        }
                    };
                }
                let storedMemberType = storedType.memberTypes[index].type;
                let memberType = Format.Types.specifyLocation(storedMemberType, "storage");
                decodedMembers.push({
                    name: memberAllocation.name,
                    value: yield* decodeStorage(memberType, { location: "storage", range: childRange }, info)
                });
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedMembers
            };
        }
        case "mapping": {
            debug("decoding mapping");
            const valueType = dataType.valueType;
            let valueSize;
            try {
                valueSize = allocate_1.storageSize(valueType, info.userDefinedTypes, allocations);
            }
            catch (error) {
                return errors_1.handleDecodingError(dataType, error);
            }
            let decodedEntries = [];
            const baseSlot = pointer.range.from.slot;
            debug("baseSlot %o", baseSlot);
            debug("base slot address %o", Utils.slotAddress(baseSlot));
            const keySlots = info.mappingKeys.filter(({ path }) => Utils.slotAddress(baseSlot).eq(Utils.slotAddress(path)));
            for (const { key } of keySlots) {
                let valuePointer;
                if (Utils.isWordsLength(valueSize)) {
                    valuePointer = {
                        location: "storage",
                        range: {
                            from: {
                                slot: {
                                    key,
                                    path: baseSlot,
                                    offset: new bn_js_1.default(0)
                                },
                                index: 0
                            },
                            to: {
                                slot: {
                                    key,
                                    path: baseSlot,
                                    offset: new bn_js_1.default(valueSize.words - 1)
                                },
                                index: Evm.Utils.WORD_SIZE - 1
                            }
                        }
                    };
                }
                else {
                    valuePointer = {
                        location: "storage",
                        range: {
                            from: {
                                slot: {
                                    key,
                                    path: baseSlot,
                                    offset: new bn_js_1.default(0)
                                },
                                index: Evm.Utils.WORD_SIZE - valueSize.bytes
                            },
                            to: {
                                slot: {
                                    key,
                                    path: baseSlot,
                                    offset: new bn_js_1.default(0)
                                },
                                index: Evm.Utils.WORD_SIZE - 1
                            }
                        }
                    };
                }
                decodedEntries.push({
                    key,
                    value: yield* decodeStorage(valueType, valuePointer, info)
                });
            }
            return {
                type: dataType,
                kind: "value",
                value: decodedEntries
            };
        }
    }
}
exports.decodeStorageReference = decodeStorageReference;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 781037:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Read = exports.Decode = exports.Allocate = exports.Utils = void 0;
__exportStar(__webpack_require__(618020), exports);
const Utils = __importStar(__webpack_require__(142526));
exports.Utils = Utils;
const Allocate = __importStar(__webpack_require__(478976));
exports.Allocate = Allocate;
const Decode = __importStar(__webpack_require__(888569));
exports.Decode = Decode;
const Read = __importStar(__webpack_require__(165135));
exports.Read = Read;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 165135:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readStorage = exports.readSlot = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:storage:read");
const Conversion = __importStar(__webpack_require__(152714));
const Utils = __importStar(__webpack_require__(142526));
const Evm = __importStar(__webpack_require__(149218));
const errors_1 = __webpack_require__(672325);
function* readSlot(storage, slot) {
    const address = Utils.slotAddress(slot);
    // debug("reading slot: %o", Conversion.toHexString(address));
    const hexAddress = Conversion.toHexString(address, Evm.Utils.WORD_SIZE);
    let word = storage[hexAddress];
    //if we can't find the word in the map, we place a request to the invoker to supply it
    //(contract-decoder will look it up from the blockchain, while the debugger will just
    //say 0)
    if (word === undefined) {
        word = yield {
            type: "storage",
            slot: address
        };
    }
    return word;
}
exports.readSlot = readSlot;
function* readStorage(pointer, state) {
    const { storage } = state;
    const { range } = pointer;
    debug("readRange %o", range);
    let { from, to, length } = range;
    from = {
        slot: from.slot,
        index: from.index || 0
    };
    if (length !== undefined) {
        to = {
            slot: {
                path: from.slot.path || undefined,
                offset: from.slot.offset.addn(Math.floor((from.index + length - 1) / Evm.Utils.WORD_SIZE))
            },
            index: (from.index + length - 1) % Evm.Utils.WORD_SIZE
        };
    }
    debug("normalized readRange %o", { from, to });
    let totalWordsAsBN = to.slot.offset.sub(from.slot.offset).addn(1);
    let totalWords;
    try {
        totalWords = totalWordsAsBN.toNumber();
    }
    catch (_) {
        throw new errors_1.DecodingError({
            kind: "ReadErrorStorage",
            range
        });
    }
    let data = new Uint8Array(totalWords * Evm.Utils.WORD_SIZE);
    for (let i = 0; i < totalWords; i++) {
        let offset = from.slot.offset.addn(i);
        const word = yield* readSlot(storage, Object.assign(Object.assign({}, from.slot), { offset }));
        if (typeof word !== "undefined") {
            data.set(word, i * Evm.Utils.WORD_SIZE);
        }
    }
    debug("words %o", data);
    data = data.slice(from.index, (totalWords - 1) * Evm.Utils.WORD_SIZE + to.index + 1);
    debug("data: %o", data);
    return data;
}
exports.readStorage = readStorage;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 618020:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
//# sourceMappingURL=types.js.map

/***/ }),

/***/ 142526:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.equalSlots = exports.slotAddress = exports.storageLengthToBytes = exports.isWordsLength = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:storage:utils");
const Evm = __importStar(__webpack_require__(149218));
const MappingKey = __importStar(__webpack_require__(514817));
function isWordsLength(size) {
    return size.words !== undefined;
}
exports.isWordsLength = isWordsLength;
function storageLengthToBytes(size) {
    if (isWordsLength(size)) {
        debug("size.words %d", size.words);
        return size.words * Evm.Utils.WORD_SIZE;
    }
    else {
        return size.bytes;
    }
}
exports.storageLengthToBytes = storageLengthToBytes;
/**
 * convert a slot to a word corresponding to actual storage address
 *
 * if `slot` is an array, return hash of array values.
 * if `slot` array is nested, recurse on sub-arrays
 *
 * @param slot - number or possibly-nested array of numbers
 */
function slotAddress(slot) {
    if (slot.key !== undefined && slot.path !== undefined) {
        // mapping reference
        return Evm.Utils.keccak256(MappingKey.Encode.mappingKeyAsHex(slot.key), slotAddress(slot.path)).add(slot.offset);
    }
    else if (slot.path !== undefined) {
        const pathAddress = slotAddress(slot.path);
        const path = slot.hashPath
            ? Evm.Utils.keccak256(pathAddress)
            : pathAddress;
        return path.add(slot.offset);
    }
    else {
        return slot.offset;
    }
}
exports.slotAddress = slotAddress;
//note: this function compares slots mostly by structure,
//rather than by their numerical value
function equalSlots(slot1, slot2) {
    if (!slot1 || !slot2) {
        return !slot1 && !slot2; //if either is undefined, it's true only if both are
    }
    if (!slot1.offset.eq(slot2.offset)) {
        return false;
    }
    if (slot1.hashPath !== slot2.hashPath) {
        return false;
    }
    if (!equalSlots(slot1.path, slot2.path)) {
        return false;
    }
    //to compare keys, we'll just compare their hex encodings
    //(yes, that leaves some wiggle room, as it could consider different
    //*types* of keys to be equal, but if keys are the only difference then
    //that should determine those types, so it shouldn't be a problem)
    if (!slot1.key || !slot2.key) {
        //first, though, they likely don't *have* keys
        return !slot1.key && !slot2.key;
    }
    //if they do have keys, though...
    return Evm.Utils.equalData(MappingKey.Encode.encodeMappingKey(slot1.key), MappingKey.Encode.encodeMappingKey(slot2.key));
}
exports.equalSlots = equalSlots;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 182243:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.decodeTopic = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:topic:decode");
const read_1 = __importDefault(__webpack_require__(887534));
const Basic = __importStar(__webpack_require__(553928));
const Format = __importStar(__webpack_require__(429965));
const Conversion = __importStar(__webpack_require__(152714));
function* decodeTopic(dataType, pointer, info, options = {}) {
    if (Format.Types.isReferenceType(dataType) ||
        dataType.typeClass === "tuple") {
        //we cannot decode reference types "stored" in topics; we have to just return an error
        let bytes = yield* read_1.default(pointer, info.state);
        let raw = Conversion.toHexString(bytes);
        //NOTE: even in strict mode we want to just return this, not throw an error here
        return {
            //dunno why TS is failing here
            type: dataType,
            kind: "error",
            error: {
                kind: "IndexedReferenceTypeError",
                type: dataType,
                raw
            }
        };
    }
    //otherwise, dispatch to decodeBasic
    return yield* Basic.Decode.decodeBasic(dataType, pointer, info, options);
}
exports.decodeTopic = decodeTopic;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 44804:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.encodeTopic = void 0;
const debug_1 = __importDefault(__webpack_require__(833149));
const debug = debug_1.default("codec:topic:encode");
const Conversion = __importStar(__webpack_require__(152714));
const Evm = __importStar(__webpack_require__(149218));
const BasicEncode = __importStar(__webpack_require__(151561));
/**
 * Encodes for event topics (indexed parameters).
 * Warning: This function is not fully implemented yet!
 * @Category Encoding (low-level)
 */
function encodeTopic(input) {
    //errors can't be encoded
    if (input.kind === "error") {
        debug("input: %O", input);
        //...unless it's an IndexedReferenceTypeError, in which
        //case, let's read otu that raw data!
        if (input.error.kind === "IndexedReferenceTypeError") {
            return Conversion.toBytes(input.error.raw, Evm.Utils.WORD_SIZE);
        }
        else {
            return undefined;
        }
    }
    //otherwise, just dispath to encodeBasic
    return BasicEncode.encodeBasic(input);
    //...of course, really here we should be checking
    //whether the input *is* a basic type, and if not, handling
    //that appropriately!  But so far we don't need this, so this
    //part of the function isn't implemented yet
}
exports.encodeTopic = encodeTopic;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 963196:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Read = exports.Encode = exports.Decode = void 0;
const Decode = __importStar(__webpack_require__(182243));
exports.Decode = Decode;
const Encode = __importStar(__webpack_require__(44804));
exports.Encode = Encode;
const Read = __importStar(__webpack_require__(61352));
exports.Read = Read;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 61352:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.readTopic = void 0;
function readTopic(pointer, state) {
    //not bothering with error handling on this one as I don't expect errors
    return state.eventtopics[pointer.topic];
}
exports.readTopic = readTopic;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 141016:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const semver = __webpack_require__(734604);
const CompilerSupplier = __webpack_require__(76684);
const Native = __webpack_require__(461657);
const Local = __webpack_require__(399220);
const path = __webpack_require__(385622);
const fs = __webpack_require__(655674);

const RangeUtils = {
  //takes a version string which may be native or local, and resolves
  //it to one which is (presumably) either a version or a version range
  resolveToRange: function (version) {
    if (!version) {
      return CompilerSupplier.getDefaultVersion();
    }
    //if version was native or local, must determine what version that
    //actually corresponds to
    if (version === "native") {
      return new Native().load().version();
    } else if (fs.existsSync(version) && path.isAbsolute(version)) {
      return new Local({ version }).load().version();
    }
    return version;
  },

  //parameter range may be either an individual version or a range
  rangeContainsAtLeast: function (range, comparisonVersion) {
    //the following line works with prereleases
    const individualAtLeast =
      semver.valid(range, { loose: true }) &&
      semver.gte(range, comparisonVersion, {
        includePrerelease: true,
        loose: true
      });
    //the following line doesn't, despite the flag, but does work with version ranges
    const rangeAtLeast =
      semver.validRange(range, { loose: true }) &&
      !semver.gtr(comparisonVersion, range, {
        includePrerelease: true,
        loose: true
      }); //intersects will throw if given undefined so must ward against
    return individualAtLeast || rangeAtLeast;
  },

  //parameter version may be either an individual version or a range
  //first case is there to handle ranges, second to handle anything else
  coerce: function (version) {
    return (
      semver.validRange(version, { loose: true }) ||
      semver.coerce(version, { loose: true }).toString()
    );
  }
};

module.exports = RangeUtils;


/***/ }),

/***/ 874269:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(590412)("compile-vyper");
const path = __webpack_require__(385622);
const exec = __webpack_require__(63129).exec;
const fs = __webpack_require__(935747);
const colors = __webpack_require__(183196);
const minimatch = __webpack_require__(791171);
const semver = __webpack_require__(590560);

const findContracts = __webpack_require__(123542);
const Common = __webpack_require__(529833);
const Config = __webpack_require__(120553);
const { requiredSources } = __webpack_require__(653377);

const { compileJson } = __webpack_require__(313919);

const VYPER_PATTERN_STRICT = "**/*.{vy,v.py,vyper.py}"; //no JSON

// Check that vyper is available, return its version
function checkVyper() {
  return new Promise((resolve, reject) => {
    exec("vyper-json --version", function (err, stdout, _stderr) {
      if (err) {
        //vyper-json not available, check vyper
        exec("vyper --version", function (err, stdout, stderr) {
          if (err) {
            //error: neither vyper nor vyper-json available
            return reject(`${colors.red("Error executing vyper:")}\n${stderr}`);
          }
          const version = normalizeVersion(stdout.trim());
          if (
            semver.satisfies(version, ">=0.2.5", {
              loose: true,
              includePrerelase: true
            })
          ) {
            //if version is >=0.2.5, we can still use JSON via
            //vyper --standard-json
            resolve({
              version,
              json: true,
              jsonCommand: "vyper --standard-json"
            });
          } else {
            //otherwise, we're stuck using vyper w/o JSON
            resolve({ version, json: false });
          }
        });
      } else {
        //no error: vyper-json is available
        const version = normalizeVersion(stdout.trim());
        resolve({ version, json: true, jsonCommand: "vyper-json" });
      }
    });
  });
}

//HACK: alters prerelease versions so semver can understand them
function normalizeVersion(version) {
  return version.replace(/^(\d+\.\d+\.\d+)b(\d+)/, "$1-beta.$2");
}

// Execute vyper for single source file
function execVyper(options, sourcePath, version, callback) {
  const formats = ["abi", "bytecode", "bytecode_runtime"];
  debug("version: %s", version);
  if (
    semver.satisfies(version, ">=0.1.0-beta.7", {
      loose: true,
      includePrerelase: true
    })
  ) {
    //Vyper chokes on unknown formats, so only include this for
    //ones that support it (they were introduced in 0.1.0b7)
    formats.push("source_map");
  }
  let evmVersionOption = "";
  if (
    options.compilers.vyper.settings &&
    options.compilers.vyper.settings.evmVersion
  ) {
    const evmVersion = options.compilers.vyper.settings.evmVersion;
    if (evmVersion.includes("'")) {
      throw new Error("Invalid EVM version");
    }
    evmVersionOption = `--evm-version '${evmVersion}'`;
  }
  if (options.contracts_directory.includes("'")) {
    throw new Error("Contracts directory contains apostrophe");
  }
  const command = `vyper -f ${formats.join(
    ","
  )} ${evmVersionOption} ${sourcePath} -p '${options.contracts_directory}'`;

  exec(command, { maxBuffer: 600 * 1024 }, function (err, stdout, stderr) {
    if (err)
      return callback(
        `${stderr}\n${colors.red(
          `Compilation of ${sourcePath} failed. See above.`
        )}`
      );

    var outputs = stdout.split(/\r?\n/);

    debug("formats: %O", formats);
    debug("outputs: %O", outputs);

    const compiledContract = outputs.reduce((contract, output, index) => {
      return Object.assign(contract, { [formats[index]]: output });
    }, {});

    callback(null, compiledContract);
  });
}

/**
 *
 * read source contents from sourcePath
 */
function readSource(sourcePath) {
  const sourceBuffer = fs.readFileSync(sourcePath);
  return sourceBuffer.toString();
}

/**
 * aggregate source information based on compiled output;
 * this can include sources that are not contracts
 */

//note: this takes paths, rather than full source objects like compileJson!
async function compileNoJson({ paths: sources, options, version }) {
  const compiler = { name: "vyper", version };
  const promises = [];
  const properSources = sources.filter(source => !source.endsWith(".json")); //filter out JSON interfaces
  const targets = options.compilationTargets
    ? properSources.filter(sourcePath =>
        options.compilationTargets.includes(sourcePath)
      )
    : properSources;
  targets.forEach(sourcePath => {
    promises.push(
      new Promise((resolve, reject) => {
        execVyper(options, sourcePath, version, function (
          error,
          compiledContract
        ) {
          if (error) return reject(error);

          debug("compiledContract: %O", compiledContract);

          // remove first extension from filename
          const extension = path.extname(sourcePath);
          const basename = path.basename(sourcePath, extension);

          // if extension is .py, remove second extension from filename
          const contractName =
            extension !== ".py"
              ? basename
              : path.basename(basename, path.extname(basename));

          const sourceContents = readSource(sourcePath);
          const deployedSourceMap = compiledContract.source_map //there is no constructor source map
            ? JSON.parse(compiledContract.source_map)
            : undefined;

          const contractDefinition = {
            contractName: contractName,
            sourcePath: sourcePath,
            source: sourceContents,
            abi: JSON.parse(compiledContract.abi),
            bytecode: {
              bytes: compiledContract.bytecode.slice(2), //remove "0x" prefix
              linkReferences: [] //no libraries in Vyper
            },
            deployedBytecode: {
              bytes: compiledContract.bytecode_runtime.slice(2), //remove "0x" prefix
              linkReferences: [] //no libraries in Vyper
            },
            deployedSourceMap,
            compiler
          };

          const compilation = {
            sources: [
              {
                sourcePath,
                contents: sourceContents,
                language: "Vyper"
              }
            ],
            contracts: [contractDefinition],
            compiler,
            sourceIndexes: [sourcePath]
          };

          resolve(compilation);
        });
      })
    );
  });
  const compilations = await Promise.all(promises);

  return { compilations };
}

const Compile = {
  // Check that vyper is available then forward to internal compile function
  async sources({ sources = {}, options }) {
    options = Config.default().merge(options);
    const paths = Object.keys(sources);
    const vyperFiles = paths.filter(path =>
      minimatch(path, VYPER_PATTERN_STRICT, { dot: true })
    );

    // no vyper files found, no need to check vyper
    // (note that JSON-only will not activate vyper)
    if (vyperFiles.length === 0) {
      return { compilations: [] };
    }

    Compile.display(vyperFiles, options);
    const { version, json: useJson, jsonCommand } = await checkVyper();
    if (!useJson) {
      //it might be possible to handle this case by writing the sources
      //to a temporary directory (and possibly using some sort of remapping--
      //a manual one I mean, Vyper doesn't have remappings),
      //but for now I'll just have it throw for simplicity
      throw new Error("Compiling literal Vyper sources requires vyper-json");
    }

    return compileJson({ sources, options, version, command: jsonCommand });
  },

  async sourcesWithDependencies({ paths = [], options }) {
    options = Config.default().merge(options);
    debug("paths: %O", paths);
    const vyperFilesStrict = paths.filter(path =>
      minimatch(path, VYPER_PATTERN_STRICT, { dot: true })
    );
    debug("vyperFilesStrict: %O", vyperFilesStrict);

    // no vyper targets found, no need to check Vyper
    if (vyperFilesStrict.length === 0) {
      return { compilations: [] };
    }

    const { allSources, compilationTargets } = await requiredSources(
      options.with({
        paths: vyperFilesStrict,
        base_path: options.contracts_directory
      })
    );

    debug("allSources: %O", allSources);
    debug("compilationTargets: %O", compilationTargets);
    const vyperTargets = compilationTargets.filter(path =>
      minimatch(path, VYPER_PATTERN_STRICT, { dot: true })
    );

    // no vyper targets found, no need to activate Vyper
    if (vyperTargets.length === 0) {
      return { compilations: [] };
    }

    //having gotten the sources from the resolver, we invoke compileJson
    //ourselves, rather than going through Compile.sources()
    Compile.display(compilationTargets, options);

    const { version, json: useJson, jsonCommand } = await checkVyper();

    if (useJson) {
      return compileJson({
        sources: allSources,
        options: options.with({
          compilationTargets
        }),
        version,
        command: jsonCommand
      });
    } else {
      return await compileNoJson({
        paths: Object.keys(allSources),
        options: options.with({
          compilationTargets
        }),
        version
      });
    }
  },

  // contracts_directory: String. Directory where contract files can be found.
  // quiet: Boolean. Suppress output. Defaults to false.
  // strict: Boolean. Return compiler warnings as errors. Defaults to false.
  async all(options) {
    options = Config.default().merge(options);
    const files = await findContracts(options.contracts_directory);

    const vyperFilesStrict = files.filter(path =>
      minimatch(path, VYPER_PATTERN_STRICT, { dot: true })
    );
    // no vyper targets found, no need to check Vyper
    if (vyperFilesStrict.length === 0) {
      return { compilations: [] };
    }

    return await Compile.sourcesWithDependencies({
      paths: files,
      options
    });
  },

  // contracts_directory: String. Directory where contract files can be found.
  // all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files
  //      in the build directory to see what needs to be compiled.
  // quiet: Boolean. Suppress output. Defaults to false.
  // strict: Boolean. Return compiler warnings as errors. Defaults to false.
  async necessary(options) {
    options = Config.default().merge(options);

    const profiler = await new Common.Profiler({});
    const updated = await profiler.updated(options);
    if (updated.length === 0) {
      return { compilations: [] };
    }
    return await Compile.sourcesWithDependencies({
      paths: updated,
      options
    });
  },

  async display(paths, options) {
    if (options.quiet !== true) {
      if (!Array.isArray(paths)) {
        paths = Object.keys(paths);
      }

      const sourceFileNames = paths.sort().map(contract => {
        if (path.isAbsolute(contract)) {
          return `.${path.sep}${path.relative(
            options.working_directory,
            contract
          )}`;
        }

        return contract;
      });
      options.events.emit("compile:sourcesToCompile", { sourceFileNames });
    }
  }
};

module.exports = {
  Compile
};


/***/ }),

/***/ 887359:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(590412)("compile-vyper:parser");
const OS = __webpack_require__(712087);

function parseImports(body) {
  // WARNING: We're going to do this crudely with regexes!!
  //
  // Vyper has a rigid enough syntax that I think this is workable.
  //
  // We can't use the Solidity approach here of analyzing error messages
  // because the Vyper compiler will only provide an error for the *first*
  // failing import, not all of them.

  // (before we do all that, though, we'll try parsing as JSON
  // and return no imports if it parses, in case this gets passed
  // a JSON file!)
  try {
    JSON.parse(body);
    debug("was JSON, no imports");
    return []; //if we reach this point it was a JSON file
  } catch (_) {
    //it was Vyper, proceed onward
  }

  const stripWhitespace = str => str.replace(/\s/g, ""); //remove even internal whitespace

  //HACK: this isn't actually a correct way of handling line
  //extensions and comments... but it should be good enough
  //for our purposes!  I can't think of any cases that this
  //gets wrong *in a way that we care about*

  return (
    body
      .replace(/(#.*)\\\r?\n/g, "$1") //remove backslashes from end of comments
      // (this is the most-incorrect step; it will detect a "comment" even if
      // the # is used in a string literal.  but this shouldn't screw up imports,
      // so...)
      .replace(/\\\r?\n/g, " ") //process line extensions;
      //for convenience we use \r?\n instead of OS.EOL
      //(we don't care that this screws up string literals)
      .split(OS.EOL) //split body into lines
      .map(line => {
        //extract imports!
        const importRegex = /^import\b(.*?)\bas\b/;
        const fromImportRegex = /^from\b(.*?)\bimport\b(.*?)($|\bas\b)/;
        let matches;
        if ((matches = line.match(importRegex))) {
          const [_, path] = matches;
          return stripWhitespace(path);
        } else if ((matches = line.match(fromImportRegex))) {
          const [_, basePath, endPath] = matches;
          debug("basePath: %s; endPath: %s", basePath, endPath);
          const strippedBasePath = stripWhitespace(basePath);
          if (strippedBasePath === "vyper.interfaces") {
            //built-in import; we should not attempt to resolve it
            return null;
          }
          const strippedEndPath = stripWhitespace(endPath);
          return strippedBasePath.endsWith(".")
            ? `${strippedBasePath}${strippedEndPath}` //don't add extra "." for "from . import", etc
            : `${strippedBasePath}.${strippedEndPath}`;
          //on the endPath because
        } else {
          return null;
        }
      })
      .filter(moduleName => moduleName !== null)
  );
}

module.exports = {
  parseImports
};


/***/ }),

/***/ 653377:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(590412)("compile-vyper:profiler");
const Common = __webpack_require__(529833);
const Resolver = __webpack_require__(648511);
const { parseImports } = __webpack_require__(887359);

// Returns the minimal set of sources to pass to vyper-json as compilations targets,
// as well as the complete set of sources so vyper-json can resolve the comp targets' imports.
async function requiredSources(options) {
  const resolver = new Resolver(options, {
    translateJsonToSolidity: false,
    resolveVyperModules: true
  });

  debug("resolver.sources.length: %d", resolver.sources.length);

  // generate profiler
  const profiler = new Common.Profiler({
    parseImports,
    shouldIncludePath
  });

  // invoke profiler
  debug("invoking profiler");
  return await profiler.requiredSources(options.with({ resolver }));
}

function shouldIncludePath(path) {
  return path.match(/\.(vy|json|v\.py|vyper\.py)$/) !== null;
}

module.exports = {
  requiredSources
};


/***/ }),

/***/ 313919:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(590412)("compile-vyper:vyper-json");
const execSync = __webpack_require__(63129).execSync;
const path = __webpack_require__(385622);
const semver = __webpack_require__(590560);
const Common = __webpack_require__(529833);
const partition = __webpack_require__(246748);

//NOTE: this file has a fair bit of copypaste-with-modifications
//from compile-solidity/run.js, so be warned...
//(some has since been factored into compile-common, but not all)

function compileJson({ sources: rawSources, options, version, command }) {
  const compiler = { name: "vyper", version };

  const {
    sources,
    targets,
    originalSourcePaths
  } = Common.Sources.collectSources(
    rawSources,
    options.compilationTargets,
    options.contracts_directory
  );

  //Vyper complains if we give it a source that is not also a target,
  //*unless* we give it as an interface.  So we have to split that out.
  //(JSON files also must always be interfaces)
  const [properSourcePaths, interfacePaths] = partition(
    Object.keys(sources),
    targets.length > 0
      ? sourcePath => !sourcePath.endsWith(".json") &&
        targets.includes(sourcePath)
      : sourcePath => !sourcePath.endsWith(".json")
  );

  //in order to better support absolute Vyper imports, we pretend that
  //the contracts directory is the root directory.  note this means that
  //if an imported source from somewhere other than FS uses an absolute
  //import to refer to its own project root, it won't work.  But, oh well.

  const properSources = Object.assign(
    {},
    ...properSourcePaths.map(sourcePath => ({
      [sourcePath]: sources[sourcePath]
    }))
  );

  const interfaces = Object.assign(
    {},
    ...interfacePaths.map(sourcePath => ({
      [sourcePath]: sources[sourcePath]
    }))
  );

  // construct compiler input
  const compilerInput = prepareCompilerInput({
    sources: properSources,
    interfaces,
    settings: options.compilers.vyper.settings || {},
    version
  });

  // perform compilation
  const rawCompilerOutput = invokeCompiler({
    compilerInput,
    command
  });
  debug("rawCompilerOutput: %O", rawCompilerOutput);

  // handle warnings as errors if options.strict
  // log if not options.quiet
  const { warnings, errors } = detectErrors({
    compilerOutput: rawCompilerOutput,
    options
  });
  if (warnings.length > 0) {
    options.events.emit("compile:warnings", { warnings });
  }

  if (errors.length > 0) {
    if (!options.quiet) {
      options.logger.log("");
    }

    throw new Common.Errors.CompileError(errors);
  }

  const compilerOutput = correctPaths(rawCompilerOutput);

  const outputSources = processAllSources({
    sources,
    compilerOutput,
    originalSourcePaths
  });
  const sourceIndexes = outputSources.map(source => source.sourcePath);
  const compilation = {
    sourceIndexes,
    contracts: processContracts({
      sources,
      compilerOutput,
      version,
      originalSourcePaths
    }),
    sources: outputSources,
    compiler
  };

  return { compilations: [compilation] };
}

function invokeCompiler({ compilerInput, command }) {
  const inputString = JSON.stringify(compilerInput);
  const outputString = execVyperJson(inputString, command);
  return JSON.parse(outputString);
}

function execVyperJson(inputString, command) {
  return execSync(command, {
    input: inputString,
    maxBuffer: 1024 * 1024 * 10 //I guess?? copied from compile-solidity
  });
}

function prepareCompilerInput({
  sources,
  settings,
  interfaces,
  version
}) {
  const outputSelection = prepareOutputSelection({ version });
  return {
    language: "Vyper",
    sources: prepareSources({ sources }),
    interfaces: prepareInterfaces({ interfaces }),
    settings: {
      evmVersion: settings.evmVersion,
      outputSelection
    },
    //older versions of vyper require outputSelection *outside* of settings.
    //we'll put it in both places for compatibility.
    outputSelection
  };
}

function prepareSources({ sources }) {
  return Object.entries(sources)
    .map(([sourcePath, content]) => ({ [sourcePath]: { content } }))
    .reduce((a, b) => Object.assign({}, a, b), {});
}

function prepareInterfaces({ interfaces }) {
  return Object.entries(interfaces)
    .map(([sourcePath, content]) =>
      sourcePath.endsWith(".json") //for JSON we need the ABI *object*, not JSON!
        ? { [sourcePath]: { abi: JSON.parse(content) } }
        : { [sourcePath]: { content } }
     )
    .reduce((a, b) => Object.assign({}, a, b), {});
}

function prepareOutputSelection({ version }) {
  //Vyper uses a simpler output selection format
  //than solc does; it also supports solc's format,
  //but I've gone with the simpler version here
  let defaultSelectors = [
    "abi",
    "ast",
    "evm.bytecode.object",
    //we have to omit sourceMap here, as annoyingly,
    //Vyper errors if you give it a not-yet-supported output selection...
    "evm.deployedBytecode.object",
    "evm.deployedBytecode.sourceMap"
  ];
  if (
    semver.satisfies(version, ">=0.1.0-beta.17", {
      loose: true,
      includePrerelase: true
    })
  ) {
    //again, due to Vyper erroring if you ask for output it doesn't know about,
    //we have to only add these to the output if we're on a sufficiently recent
    //version
    const additionalSelectors = ["userdoc", "devdoc"];
    defaultSelectors = defaultSelectors.concat(additionalSelectors);
  }

  //because we've already filtered down the sources to match the targets,
  //we can just say that the targets are everything
  return {
    "*": defaultSelectors
  };
}

//this also is copy-pasted, but minus some complications
function detectErrors({ compilerOutput: { errors: outputErrors }, options }) {
  outputErrors = outputErrors || [];
  const rawErrors = options.strict
    ? outputErrors
    : outputErrors.filter(({ severity }) => severity !== "warning");

  const rawWarnings = options.strict
    ? [] // none of those in strict mode
    : outputErrors.filter(({ severity }) => severity === "warning");

  // extract messages
  // NOTE: sufficiently old Vyper versions don't have formattedMessage, so we use message
  // instead in those cases
  let errors = rawErrors
    .map(({ formattedMessage, message }) => formattedMessage || message)
    .join();
  const warnings = rawWarnings.map(
    ({ formattedMessage, message }) => formattedMessage || message
  );

  return { warnings, errors };
}

//warning: copypaste
function processAllSources({ sources, compilerOutput, originalSourcePaths }) {
  if (!compilerOutput.sources) return [];
  let outputSources = [];
  for (const [sourcePath, { id, ast }] of Object.entries(
    compilerOutput.sources
  )) {
    outputSources[id] = {
      sourcePath: originalSourcePaths[sourcePath],
      contents: sources[sourcePath],
      ast,
      language: "Vyper"
    };
  }
  return outputSources;
}

function processContracts({
  compilerOutput,
  sources,
  version,
  originalSourcePaths
}) {
  if (!compilerOutput.contracts) return [];
  return (
    Object.entries(compilerOutput.contracts)
      // map to [[{ source, contractName, contract }]]
      .map(([sourcePath, sourceContracts]) =>
        Object.entries(sourceContracts).map(([contractName, contract]) => ({
          // if extension is .py, remove second extension from contract name (HACK)
          contractName:
            path.extname(sourcePath) !== ".py"
              ? contractName
              : path.basename(contractName, path.extname(contractName)),
          contract,
          source: {
            ast: compilerOutput.sources[sourcePath].ast,
            contents: sources[sourcePath],
            sourcePath
          }
        }))
      )
      // and flatten
      .reduce((a, b) => [...a, ...b], [])

      // All source will have a key, but only the compiled source will have
      // the evm output.
      .filter(({ contract: { evm } }) => Object.keys(evm).length > 0)

      // convert to output format
      .map(
        ({
          contractName,
          contract: {
            evm: {
              bytecode: { object: bytecode },
              deployedBytecode: {
                sourceMap: deployedSourceMap,
                object: deployedBytecode
              }
            },
            abi,
            devdoc,
            userdoc
          },
          source: { ast, sourcePath: transformedSourcePath, contents: source }
        }) => ({
          contractName,
          abi,
          devdoc,
          userdoc,
          sourcePath: originalSourcePaths[transformedSourcePath],
          source,
          deployedSourceMap,
          ast,
          bytecode: {
            bytes: bytecode.slice(2), //Vyper uses a "0x" prefix
            linkReferences: [] //no libraries in Vyper
          },
          deployedBytecode: {
            bytes: deployedBytecode.slice(2), //Vyper uses a "0x" prefix
            linkReferences: [] //no libraries in Vyper
          },
          compiler: {
            name: "vyper",
            version
          }
        })
      )
  );
}

function correctPaths(compilerOutput) {
  return {
    compiler: compilerOutput.compiler,
    errors: compilerOutput.errors,
    sources: fixKeys(compilerOutput.sources),
    contracts: fixKeys(compilerOutput.contracts)
  };
}

function fixKeys(pathKeyedObject) {
  return Object.assign(
    {},
    ...Object.entries(pathKeyedObject).map(([key, value]) => ({
      [fixPath(key)]: value
    }))
  );
}

function fixPath(path) {
  if (path[0] === "/") {
    return path;
  } else {
    return "/" + path;
  }
}

module.exports = {
  compileJson,
  execVyperJson
};


/***/ }),

/***/ 418370:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var pkgVersion = __webpack_require__(494315)/* .version */ .i8;
var Ajv = __webpack_require__(565096);
var util = __webpack_require__(431669);

var contractObjectSchema = __webpack_require__(191412);
var networkObjectSchema = __webpack_require__(459874);
var abiSchema = __webpack_require__(934735);

/**
 * Property definitions for Contract Objects
 *
 * Describes canonical output properties as sourced from some "dirty" input
 * object. Describes normalization process to account for deprecated and/or
 * nonstandard keys and values.
 *
 * Maps (key -> property) where:
 *  - `key` is the top-level output key matching up with those in the schema
 *  - `property` is an object with optional values:
 *      - `sources`: list of sources (see below); default `key`
 *      - `transform`: function(value) -> transformed value; default x -> x
 *
 * Each source represents a means to select a value from dirty object.
 * Allows:
 *  - dot-separated (`.`) string, corresponding to path to value in dirty
 *    object
 *  - function(dirtyObj) -> (cleanValue | undefined)
 *
 * The optional `transform` parameter standardizes value regardless of source,
 * for purposes of ensuring data type and/or string schemas.
 */

// helper that ensures abi's do not contain function signatures
const sanitizedValue = dirtyValueArray => {
  let sanitizedValueArray = [];
  dirtyValueArray.forEach(item => {
    let sanitizedItem = Object.assign({}, item);
    delete sanitizedItem.signature;
    sanitizedValueArray.push(sanitizedItem);
  });
  return sanitizedValueArray;
};

// filter `signature` property from an event
const sanitizeEvent = dirtyEvent =>
  Object.entries(dirtyEvent).reduce(
    (acc, [property, value]) =>
      property === "signature"
        ? acc
        : Object.assign(acc, { [property]: value }),
    {}
  );

// sanitize aggregrate events given a `network-object.spec.json#events` object
const sanitizeAllEvents = dirtyEvents =>
  Object.entries(dirtyEvents).reduce(
    (acc, [property, event]) =>
      Object.assign(acc, { [property]: sanitizeEvent(event) }),
    {}
  );

var properties = {
  contractName: {
    sources: ["contractName", "contract_name"]
  },
  abi: {
    sources: ["abi", "interface"],
    transform: function (value) {
      if (typeof value === "string") {
        try {
          value = JSON.parse(value);
        } catch (_) {
          value = undefined;
        }
      }
      if (Array.isArray(value)) {
        return sanitizedValue(value);
      }
      return value;
    }
  },
  metadata: {
    sources: ["metadata"]
  },
  bytecode: {
    sources: ["bytecode", "binary", "unlinked_binary", "evm.bytecode.object"],
    transform: function (value) {
      if (value && value.indexOf("0x") !== 0) {
        value = "0x" + value;
      }
      return value;
    }
  },
  deployedBytecode: {
    sources: [
      "deployedBytecode",
      "runtimeBytecode",
      "evm.deployedBytecode.object"
    ],
    transform: function (value) {
      if (value && value.indexOf("0x") !== 0) {
        value = "0x" + value;
      }
      return value;
    }
  },
  immutableReferences: {},
  generatedSources: {},
  deployedGeneratedSources: {},
  sourceMap: {
    transform: function (value) {
      if (typeof value === "string") {
        try {
          return JSON.parse(value);
        } catch (_) {
          return value;
        }
      } else {
        return value;
      }
    },
    sources: ["sourceMap", "srcmap", "evm.bytecode.sourceMap"]
  },
  deployedSourceMap: {
    transform: function (value) {
      if (typeof value === "string") {
        try {
          return JSON.parse(value);
        } catch (_) {
          return value;
        }
      } else {
        return value;
      }
    },
    sources: [
      "deployedSourceMap",
      "srcmapRuntime",
      "evm.deployedBytecode.sourceMap"
    ]
  },
  source: {},
  sourcePath: {},
  ast: {},
  legacyAST: {
    transform: function (value, obj) {
      if (value) {
        return value;
      } else {
        return obj.ast;
      }
    }
  },
  compiler: {},
  networks: {
    /**
     * Normalize a networks object. Currently this makes sure `events` are
     * always sanitized and `links` is extracted when copying from
     * a TruffleContract context object.
     *
     * @param {object} value - the target object
     * @param {object | TruffleContract} obj - the context, or source object.
     * @return {object} The normalized Network object
     */
    transform: function (value = {}, obj) {
      // Sanitize value's events for known networks
      Object.keys(value).forEach(networkId => {
        if (value[networkId].events) {
          value[networkId].events = sanitizeAllEvents(value[networkId].events);
        }
      });

      // Set and sanitize the current networks property from the
      // TruffleContract. Note: obj is a TruffleContract if it has
      // `network_id` attribute
      const networkId = obj.network_id;
      if (networkId && value.hasOwnProperty(networkId)) {
        value[networkId].links = obj.links;
        value[networkId].events = sanitizeAllEvents(obj.events);
      }

      return value;
    }
  },
  schemaVersion: {
    sources: ["schemaVersion", "schema_version"]
  },
  updatedAt: {
    sources: ["updatedAt", "updated_at"],
    transform: function (value) {
      if (typeof value === "number") {
        value = new Date(value).toISOString();
      }
      return value;
    }
  },
  networkType: {},
  devdoc: {},
  userdoc: {},
  db: {}
};

/**
 * Construct a getter for a given key, possibly applying some post-retrieve
 * transformation on the resulting value.
 *
 * @return {Function} Accepting dirty object and returning value || undefined
 */
function getter(key, transform) {
  if (transform === undefined) {
    transform = function (x) {
      return x;
    };
  }

  return function (obj) {
    try {
      return transform(obj[key]);
    } catch (_) {
      return undefined;
    }
  };
}

/**
 * Chains together a series of function(obj) -> value, passing resulting
 * returned value to next function in chain.
 *
 * Accepts any number of functions passed as arguments
 * @return {Function} Accepting initial object, returning end-of-chain value
 *
 * Assumes all intermediary values to be objects, with well-formed sequence
 * of operations.
 */
function chain() {
  var getters = Array.prototype.slice.call(arguments);
  return function (obj) {
    return getters.reduce(function (cur, get) {
      return get(cur);
    }, obj);
  };
}

// Schema module
//

var TruffleContractSchema = {
  // Return a promise to validate a contract object
  // - Resolves as validated `contractObj`
  // - Rejects with list of errors from schema validator
  validate: function (contractObj) {
    var ajv = new Ajv({ verbose: true });
    ajv.addSchema(abiSchema);
    ajv.addSchema(networkObjectSchema);
    ajv.addSchema(contractObjectSchema);
    if (ajv.validate("contract-object.spec.json", contractObj)) {
      return contractObj;
    } else {
      const message = `Schema validation failed. Errors:\n\n${ajv.errors
        .map(
          ({
            keyword,
            dataPath,
            schemaPath,
            params,
            message,
            data,
            parentSchema
          }) =>
            util.format(
              "%s (%s):\n%s\n",
              message,
              keyword,
              util.inspect(
                {
                  dataPath,
                  schemaPath,
                  params,
                  data,
                  parentSchema
                },
                { depth: 5 }
              )
            )
        )
        .join("\n")}`;
      const error = new Error(message);
      error.errors = ajv.errors;
      throw error;
    }
  },

  // accepts as argument anything that can be turned into a contract object
  // returns a contract object
  normalize: function (objDirty, options) {
    options = options || {};
    var normalized = {};

    // iterate over each property
    Object.keys(properties).forEach(function (key) {
      var property = properties[key];
      var value; // normalized value || undefined

      // either used the defined sources or assume the key will only ever be
      // listed as its canonical name (itself)
      var sources = property.sources || [key];

      // iterate over sources until value is defined or end of list met
      for (var i = 0; value === undefined && i < sources.length; i++) {
        var source = sources[i];
        // string refers to path to value in objDirty, split and chain
        // getters
        if (typeof source === "string") {
          var traversals = source.split(".").map(function (k) {
            return getter(k);
          });
          source = chain.apply(null, traversals);
        }

        // source should be a function that takes the objDirty and returns
        // value or undefined
        value = source(objDirty);
      }

      // run source-agnostic transform on value
      // (e.g. make sure bytecode begins 0x)
      if (property.transform) {
        value = property.transform(value, objDirty);
      }

      // add resulting (possibly undefined) to normalized obj
      normalized[key] = value;
    });

    // Copy x- options
    Object.keys(objDirty).forEach(function (key) {
      if (key.indexOf("x-") === 0) {
        normalized[key] = getter(key)(objDirty);
      }
    });

    // update schema version
    normalized.schemaVersion = pkgVersion;

    if (options.validate) {
      this.validate(normalized);
    }

    return normalized;
  }
};

module.exports = TruffleContractSchema;


/***/ }),

/***/ 494315:
/***/ ((module) => {

"use strict";
module.exports = {"i8":"3.4.0"};

/***/ }),

/***/ 934735:
/***/ ((module) => {

"use strict";
module.exports = JSON.parse("{\"$id\":\"abi.spec.json\",\"$schema\":\"http://json-schema.org/schema#\",\"title\":\"ABI\",\"type\":\"array\",\"items\":{\"oneOf\":[{\"$ref\":\"#/definitions/Event\"},{\"$ref\":\"#/definitions/Error\"},{\"$ref\":\"#/definitions/ConstructorFunction\"},{\"$ref\":\"#/definitions/FallbackFunction\"},{\"$ref\":\"#/definitions/ReceiveFunction\"},{\"$ref\":\"#/definitions/NormalFunction\"}]},\"definitions\":{\"Name\":{\"type\":\"string\",\"pattern\":\"^$|^[a-zA-Z_\\\\$][a-zA-Z_\\\\$0-9]*$\"},\"Type\":{\"oneOf\":[{\"type\":\"string\",\"pattern\":\"^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^address(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^bool(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^u?fixed(8x1|8x2|8x3|8x4|8x5|8x6|8x7|8x8|8x9|8x10|8x11|8x12|8x13|8x14|8x15|8x16|8x17|8x18|8x19|8x20|8x21|8x22|8x23|8x24|8x25|8x26|8x27|8x28|8x29|8x30|8x31|8x32|8x33|8x34|8x35|8x36|8x37|8x38|8x39|8x40|8x41|8x42|8x43|8x44|8x45|8x46|8x47|8x48|8x49|8x50|8x51|8x52|8x53|8x54|8x55|8x56|8x57|8x58|8x59|8x60|8x61|8x62|8x63|8x64|8x65|8x66|8x67|8x68|8x69|8x70|8x71|8x72|8x73|8x74|8x75|8x76|8x77|8x78|8x79|8x80|16x1|16x2|16x3|16x4|16x5|16x6|16x7|16x8|16x9|16x10|16x11|16x12|16x13|16x14|16x15|16x16|16x17|16x18|16x19|16x20|16x21|16x22|16x23|16x24|16x25|16x26|16x27|16x28|16x29|16x30|16x31|16x32|16x33|16x34|16x35|16x36|16x37|16x38|16x39|16x40|16x41|16x42|16x43|16x44|16x45|16x46|16x47|16x48|16x49|16x50|16x51|16x52|16x53|16x54|16x55|16x56|16x57|16x58|16x59|16x60|16x61|16x62|16x63|16x64|16x65|16x66|16x67|16x68|16x69|16x70|16x71|16x72|16x73|16x74|16x75|16x76|16x77|16x78|16x79|16x80|24x1|24x2|24x3|24x4|24x5|24x6|24x7|24x8|24x9|24x10|24x11|24x12|24x13|24x14|24x15|24x16|24x17|24x18|24x19|24x20|24x21|24x22|24x23|24x24|24x25|24x26|24x27|24x28|24x29|24x30|24x31|24x32|24x33|24x34|24x35|24x36|24x37|24x38|24x39|24x40|24x41|24x42|24x43|24x44|24x45|24x46|24x47|24x48|24x49|24x50|24x51|24x52|24x53|24x54|24x55|24x56|24x57|24x58|24x59|24x60|24x61|24x62|24x63|24x64|24x65|24x66|24x67|24x68|24x69|24x70|24x71|24x72|24x73|24x74|24x75|24x76|24x77|24x78|24x79|24x80|32x1|32x2|32x3|32x4|32x5|32x6|32x7|32x8|32x9|32x10|32x11|32x12|32x13|32x14|32x15|32x16|32x17|32x18|32x19|32x20|32x21|32x22|32x23|32x24|32x25|32x26|32x27|32x28|32x29|32x30|32x31|32x32|32x33|32x34|32x35|32x36|32x37|32x38|32x39|32x40|32x41|32x42|32x43|32x44|32x45|32x46|32x47|32x48|32x49|32x50|32x51|32x52|32x53|32x54|32x55|32x56|32x57|32x58|32x59|32x60|32x61|32x62|32x63|32x64|32x65|32x66|32x67|32x68|32x69|32x70|32x71|32x72|32x73|32x74|32x75|32x76|32x77|32x78|32x79|32x80|40x1|40x2|40x3|40x4|40x5|40x6|40x7|40x8|40x9|40x10|40x11|40x12|40x13|40x14|40x15|40x16|40x17|40x18|40x19|40x20|40x21|40x22|40x23|40x24|40x25|40x26|40x27|40x28|40x29|40x30|40x31|40x32|40x33|40x34|40x35|40x36|40x37|40x38|40x39|40x40|40x41|40x42|40x43|40x44|40x45|40x46|40x47|40x48|40x49|40x50|40x51|40x52|40x53|40x54|40x55|40x56|40x57|40x58|40x59|40x60|40x61|40x62|40x63|40x64|40x65|40x66|40x67|40x68|40x69|40x70|40x71|40x72|40x73|40x74|40x75|40x76|40x77|40x78|40x79|40x80|48x1|48x2|48x3|48x4|48x5|48x6|48x7|48x8|48x9|48x10|48x11|48x12|48x13|48x14|48x15|48x16|48x17|48x18|48x19|48x20|48x21|48x22|48x23|48x24|48x25|48x26|48x27|48x28|48x29|48x30|48x31|48x32|48x33|48x34|48x35|48x36|48x37|48x38|48x39|48x40|48x41|48x42|48x43|48x44|48x45|48x46|48x47|48x48|48x49|48x50|48x51|48x52|48x53|48x54|48x55|48x56|48x57|48x58|48x59|48x60|48x61|48x62|48x63|48x64|48x65|48x66|48x67|48x68|48x69|48x70|48x71|48x72|48x73|48x74|48x75|48x76|48x77|48x78|48x79|48x80|56x1|56x2|56x3|56x4|56x5|56x6|56x7|56x8|56x9|56x10|56x11|56x12|56x13|56x14|56x15|56x16|56x17|56x18|56x19|56x20|56x21|56x22|56x23|56x24|56x25|56x26|56x27|56x28|56x29|56x30|56x31|56x32|56x33|56x34|56x35|56x36|56x37|56x38|56x39|56x40|56x41|56x42|56x43|56x44|56x45|56x46|56x47|56x48|56x49|56x50|56x51|56x52|56x53|56x54|56x55|56x56|56x57|56x58|56x59|56x60|56x61|56x62|56x63|56x64|56x65|56x66|56x67|56x68|56x69|56x70|56x71|56x72|56x73|56x74|56x75|56x76|56x77|56x78|56x79|56x80|64x1|64x2|64x3|64x4|64x5|64x6|64x7|64x8|64x9|64x10|64x11|64x12|64x13|64x14|64x15|64x16|64x17|64x18|64x19|64x20|64x21|64x22|64x23|64x24|64x25|64x26|64x27|64x28|64x29|64x30|64x31|64x32|64x33|64x34|64x35|64x36|64x37|64x38|64x39|64x40|64x41|64x42|64x43|64x44|64x45|64x46|64x47|64x48|64x49|64x50|64x51|64x52|64x53|64x54|64x55|64x56|64x57|64x58|64x59|64x60|64x61|64x62|64x63|64x64|64x65|64x66|64x67|64x68|64x69|64x70|64x71|64x72|64x73|64x74|64x75|64x76|64x77|64x78|64x79|64x80|72x1|72x2|72x3|72x4|72x5|72x6|72x7|72x8|72x9|72x10|72x11|72x12|72x13|72x14|72x15|72x16|72x17|72x18|72x19|72x20|72x21|72x22|72x23|72x24|72x25|72x26|72x27|72x28|72x29|72x30|72x31|72x32|72x33|72x34|72x35|72x36|72x37|72x38|72x39|72x40|72x41|72x42|72x43|72x44|72x45|72x46|72x47|72x48|72x49|72x50|72x51|72x52|72x53|72x54|72x55|72x56|72x57|72x58|72x59|72x60|72x61|72x62|72x63|72x64|72x65|72x66|72x67|72x68|72x69|72x70|72x71|72x72|72x73|72x74|72x75|72x76|72x77|72x78|72x79|72x80|80x1|80x2|80x3|80x4|80x5|80x6|80x7|80x8|80x9|80x10|80x11|80x12|80x13|80x14|80x15|80x16|80x17|80x18|80x19|80x20|80x21|80x22|80x23|80x24|80x25|80x26|80x27|80x28|80x29|80x30|80x31|80x32|80x33|80x34|80x35|80x36|80x37|80x38|80x39|80x40|80x41|80x42|80x43|80x44|80x45|80x46|80x47|80x48|80x49|80x50|80x51|80x52|80x53|80x54|80x55|80x56|80x57|80x58|80x59|80x60|80x61|80x62|80x63|80x64|80x65|80x66|80x67|80x68|80x69|80x70|80x71|80x72|80x73|80x74|80x75|80x76|80x77|80x78|80x79|80x80|88x1|88x2|88x3|88x4|88x5|88x6|88x7|88x8|88x9|88x10|88x11|88x12|88x13|88x14|88x15|88x16|88x17|88x18|88x19|88x20|88x21|88x22|88x23|88x24|88x25|88x26|88x27|88x28|88x29|88x30|88x31|88x32|88x33|88x34|88x35|88x36|88x37|88x38|88x39|88x40|88x41|88x42|88x43|88x44|88x45|88x46|88x47|88x48|88x49|88x50|88x51|88x52|88x53|88x54|88x55|88x56|88x57|88x58|88x59|88x60|88x61|88x62|88x63|88x64|88x65|88x66|88x67|88x68|88x69|88x70|88x71|88x72|88x73|88x74|88x75|88x76|88x77|88x78|88x79|88x80|96x1|96x2|96x3|96x4|96x5|96x6|96x7|96x8|96x9|96x10|96x11|96x12|96x13|96x14|96x15|96x16|96x17|96x18|96x19|96x20|96x21|96x22|96x23|96x24|96x25|96x26|96x27|96x28|96x29|96x30|96x31|96x32|96x33|96x34|96x35|96x36|96x37|96x38|96x39|96x40|96x41|96x42|96x43|96x44|96x45|96x46|96x47|96x48|96x49|96x50|96x51|96x52|96x53|96x54|96x55|96x56|96x57|96x58|96x59|96x60|96x61|96x62|96x63|96x64|96x65|96x66|96x67|96x68|96x69|96x70|96x71|96x72|96x73|96x74|96x75|96x76|96x77|96x78|96x79|96x80|104x1|104x2|104x3|104x4|104x5|104x6|104x7|104x8|104x9|104x10|104x11|104x12|104x13|104x14|104x15|104x16|104x17|104x18|104x19|104x20|104x21|104x22|104x23|104x24|104x25|104x26|104x27|104x28|104x29|104x30|104x31|104x32|104x33|104x34|104x35|104x36|104x37|104x38|104x39|104x40|104x41|104x42|104x43|104x44|104x45|104x46|104x47|104x48|104x49|104x50|104x51|104x52|104x53|104x54|104x55|104x56|104x57|104x58|104x59|104x60|104x61|104x62|104x63|104x64|104x65|104x66|104x67|104x68|104x69|104x70|104x71|104x72|104x73|104x74|104x75|104x76|104x77|104x78|104x79|104x80|112x1|112x2|112x3|112x4|112x5|112x6|112x7|112x8|112x9|112x10|112x11|112x12|112x13|112x14|112x15|112x16|112x17|112x18|112x19|112x20|112x21|112x22|112x23|112x24|112x25|112x26|112x27|112x28|112x29|112x30|112x31|112x32|112x33|112x34|112x35|112x36|112x37|112x38|112x39|112x40|112x41|112x42|112x43|112x44|112x45|112x46|112x47|112x48|112x49|112x50|112x51|112x52|112x53|112x54|112x55|112x56|112x57|112x58|112x59|112x60|112x61|112x62|112x63|112x64|112x65|112x66|112x67|112x68|112x69|112x70|112x71|112x72|112x73|112x74|112x75|112x76|112x77|112x78|112x79|112x80|120x1|120x2|120x3|120x4|120x5|120x6|120x7|120x8|120x9|120x10|120x11|120x12|120x13|120x14|120x15|120x16|120x17|120x18|120x19|120x20|120x21|120x22|120x23|120x24|120x25|120x26|120x27|120x28|120x29|120x30|120x31|120x32|120x33|120x34|120x35|120x36|120x37|120x38|120x39|120x40|120x41|120x42|120x43|120x44|120x45|120x46|120x47|120x48|120x49|120x50|120x51|120x52|120x53|120x54|120x55|120x56|120x57|120x58|120x59|120x60|120x61|120x62|120x63|120x64|120x65|120x66|120x67|120x68|120x69|120x70|120x71|120x72|120x73|120x74|120x75|120x76|120x77|120x78|120x79|120x80|128x1|128x2|128x3|128x4|128x5|128x6|128x7|128x8|128x9|128x10|128x11|128x12|128x13|128x14|128x15|128x16|128x17|128x18|128x19|128x20|128x21|128x22|128x23|128x24|128x25|128x26|128x27|128x28|128x29|128x30|128x31|128x32|128x33|128x34|128x35|128x36|128x37|128x38|128x39|128x40|128x41|128x42|128x43|128x44|128x45|128x46|128x47|128x48|128x49|128x50|128x51|128x52|128x53|128x54|128x55|128x56|128x57|128x58|128x59|128x60|128x61|128x62|128x63|128x64|128x65|128x66|128x67|128x68|128x69|128x70|128x71|128x72|128x73|128x74|128x75|128x76|128x77|128x78|128x79|128x80|136x1|136x2|136x3|136x4|136x5|136x6|136x7|136x8|136x9|136x10|136x11|136x12|136x13|136x14|136x15|136x16|136x17|136x18|136x19|136x20|136x21|136x22|136x23|136x24|136x25|136x26|136x27|136x28|136x29|136x30|136x31|136x32|136x33|136x34|136x35|136x36|136x37|136x38|136x39|136x40|136x41|136x42|136x43|136x44|136x45|136x46|136x47|136x48|136x49|136x50|136x51|136x52|136x53|136x54|136x55|136x56|136x57|136x58|136x59|136x60|136x61|136x62|136x63|136x64|136x65|136x66|136x67|136x68|136x69|136x70|136x71|136x72|136x73|136x74|136x75|136x76|136x77|136x78|136x79|136x80|144x1|144x2|144x3|144x4|144x5|144x6|144x7|144x8|144x9|144x10|144x11|144x12|144x13|144x14|144x15|144x16|144x17|144x18|144x19|144x20|144x21|144x22|144x23|144x24|144x25|144x26|144x27|144x28|144x29|144x30|144x31|144x32|144x33|144x34|144x35|144x36|144x37|144x38|144x39|144x40|144x41|144x42|144x43|144x44|144x45|144x46|144x47|144x48|144x49|144x50|144x51|144x52|144x53|144x54|144x55|144x56|144x57|144x58|144x59|144x60|144x61|144x62|144x63|144x64|144x65|144x66|144x67|144x68|144x69|144x70|144x71|144x72|144x73|144x74|144x75|144x76|144x77|144x78|144x79|144x80|152x1|152x2|152x3|152x4|152x5|152x6|152x7|152x8|152x9|152x10|152x11|152x12|152x13|152x14|152x15|152x16|152x17|152x18|152x19|152x20|152x21|152x22|152x23|152x24|152x25|152x26|152x27|152x28|152x29|152x30|152x31|152x32|152x33|152x34|152x35|152x36|152x37|152x38|152x39|152x40|152x41|152x42|152x43|152x44|152x45|152x46|152x47|152x48|152x49|152x50|152x51|152x52|152x53|152x54|152x55|152x56|152x57|152x58|152x59|152x60|152x61|152x62|152x63|152x64|152x65|152x66|152x67|152x68|152x69|152x70|152x71|152x72|152x73|152x74|152x75|152x76|152x77|152x78|152x79|152x80|160x1|160x2|160x3|160x4|160x5|160x6|160x7|160x8|160x9|160x10|160x11|160x12|160x13|160x14|160x15|160x16|160x17|160x18|160x19|160x20|160x21|160x22|160x23|160x24|160x25|160x26|160x27|160x28|160x29|160x30|160x31|160x32|160x33|160x34|160x35|160x36|160x37|160x38|160x39|160x40|160x41|160x42|160x43|160x44|160x45|160x46|160x47|160x48|160x49|160x50|160x51|160x52|160x53|160x54|160x55|160x56|160x57|160x58|160x59|160x60|160x61|160x62|160x63|160x64|160x65|160x66|160x67|160x68|160x69|160x70|160x71|160x72|160x73|160x74|160x75|160x76|160x77|160x78|160x79|160x80|168x1|168x2|168x3|168x4|168x5|168x6|168x7|168x8|168x9|168x10|168x11|168x12|168x13|168x14|168x15|168x16|168x17|168x18|168x19|168x20|168x21|168x22|168x23|168x24|168x25|168x26|168x27|168x28|168x29|168x30|168x31|168x32|168x33|168x34|168x35|168x36|168x37|168x38|168x39|168x40|168x41|168x42|168x43|168x44|168x45|168x46|168x47|168x48|168x49|168x50|168x51|168x52|168x53|168x54|168x55|168x56|168x57|168x58|168x59|168x60|168x61|168x62|168x63|168x64|168x65|168x66|168x67|168x68|168x69|168x70|168x71|168x72|168x73|168x74|168x75|168x76|168x77|168x78|168x79|168x80|176x1|176x2|176x3|176x4|176x5|176x6|176x7|176x8|176x9|176x10|176x11|176x12|176x13|176x14|176x15|176x16|176x17|176x18|176x19|176x20|176x21|176x22|176x23|176x24|176x25|176x26|176x27|176x28|176x29|176x30|176x31|176x32|176x33|176x34|176x35|176x36|176x37|176x38|176x39|176x40|176x41|176x42|176x43|176x44|176x45|176x46|176x47|176x48|176x49|176x50|176x51|176x52|176x53|176x54|176x55|176x56|176x57|176x58|176x59|176x60|176x61|176x62|176x63|176x64|176x65|176x66|176x67|176x68|176x69|176x70|176x71|176x72|176x73|176x74|176x75|176x76|176x77|176x78|176x79|176x80|184x1|184x2|184x3|184x4|184x5|184x6|184x7|184x8|184x9|184x10|184x11|184x12|184x13|184x14|184x15|184x16|184x17|184x18|184x19|184x20|184x21|184x22|184x23|184x24|184x25|184x26|184x27|184x28|184x29|184x30|184x31|184x32|184x33|184x34|184x35|184x36|184x37|184x38|184x39|184x40|184x41|184x42|184x43|184x44|184x45|184x46|184x47|184x48|184x49|184x50|184x51|184x52|184x53|184x54|184x55|184x56|184x57|184x58|184x59|184x60|184x61|184x62|184x63|184x64|184x65|184x66|184x67|184x68|184x69|184x70|184x71|184x72|184x73|184x74|184x75|184x76|184x77|184x78|184x79|184x80|192x1|192x2|192x3|192x4|192x5|192x6|192x7|192x8|192x9|192x10|192x11|192x12|192x13|192x14|192x15|192x16|192x17|192x18|192x19|192x20|192x21|192x22|192x23|192x24|192x25|192x26|192x27|192x28|192x29|192x30|192x31|192x32|192x33|192x34|192x35|192x36|192x37|192x38|192x39|192x40|192x41|192x42|192x43|192x44|192x45|192x46|192x47|192x48|192x49|192x50|192x51|192x52|192x53|192x54|192x55|192x56|192x57|192x58|192x59|192x60|192x61|192x62|192x63|192x64|192x65|192x66|192x67|192x68|192x69|192x70|192x71|192x72|192x73|192x74|192x75|192x76|192x77|192x78|192x79|192x80|200x1|200x2|200x3|200x4|200x5|200x6|200x7|200x8|200x9|200x10|200x11|200x12|200x13|200x14|200x15|200x16|200x17|200x18|200x19|200x20|200x21|200x22|200x23|200x24|200x25|200x26|200x27|200x28|200x29|200x30|200x31|200x32|200x33|200x34|200x35|200x36|200x37|200x38|200x39|200x40|200x41|200x42|200x43|200x44|200x45|200x46|200x47|200x48|200x49|200x50|200x51|200x52|200x53|200x54|200x55|200x56|200x57|200x58|200x59|200x60|200x61|200x62|200x63|200x64|200x65|200x66|200x67|200x68|200x69|200x70|200x71|200x72|200x73|200x74|200x75|200x76|200x77|200x78|200x79|200x80|208x1|208x2|208x3|208x4|208x5|208x6|208x7|208x8|208x9|208x10|208x11|208x12|208x13|208x14|208x15|208x16|208x17|208x18|208x19|208x20|208x21|208x22|208x23|208x24|208x25|208x26|208x27|208x28|208x29|208x30|208x31|208x32|208x33|208x34|208x35|208x36|208x37|208x38|208x39|208x40|208x41|208x42|208x43|208x44|208x45|208x46|208x47|208x48|208x49|208x50|208x51|208x52|208x53|208x54|208x55|208x56|208x57|208x58|208x59|208x60|208x61|208x62|208x63|208x64|208x65|208x66|208x67|208x68|208x69|208x70|208x71|208x72|208x73|208x74|208x75|208x76|208x77|208x78|208x79|208x80|216x1|216x2|216x3|216x4|216x5|216x6|216x7|216x8|216x9|216x10|216x11|216x12|216x13|216x14|216x15|216x16|216x17|216x18|216x19|216x20|216x21|216x22|216x23|216x24|216x25|216x26|216x27|216x28|216x29|216x30|216x31|216x32|216x33|216x34|216x35|216x36|216x37|216x38|216x39|216x40|216x41|216x42|216x43|216x44|216x45|216x46|216x47|216x48|216x49|216x50|216x51|216x52|216x53|216x54|216x55|216x56|216x57|216x58|216x59|216x60|216x61|216x62|216x63|216x64|216x65|216x66|216x67|216x68|216x69|216x70|216x71|216x72|216x73|216x74|216x75|216x76|216x77|216x78|216x79|216x80|224x1|224x2|224x3|224x4|224x5|224x6|224x7|224x8|224x9|224x10|224x11|224x12|224x13|224x14|224x15|224x16|224x17|224x18|224x19|224x20|224x21|224x22|224x23|224x24|224x25|224x26|224x27|224x28|224x29|224x30|224x31|224x32|224x33|224x34|224x35|224x36|224x37|224x38|224x39|224x40|224x41|224x42|224x43|224x44|224x45|224x46|224x47|224x48|224x49|224x50|224x51|224x52|224x53|224x54|224x55|224x56|224x57|224x58|224x59|224x60|224x61|224x62|224x63|224x64|224x65|224x66|224x67|224x68|224x69|224x70|224x71|224x72|224x73|224x74|224x75|224x76|224x77|224x78|224x79|224x80|232x1|232x2|232x3|232x4|232x5|232x6|232x7|232x8|232x9|232x10|232x11|232x12|232x13|232x14|232x15|232x16|232x17|232x18|232x19|232x20|232x21|232x22|232x23|232x24|232x25|232x26|232x27|232x28|232x29|232x30|232x31|232x32|232x33|232x34|232x35|232x36|232x37|232x38|232x39|232x40|232x41|232x42|232x43|232x44|232x45|232x46|232x47|232x48|232x49|232x50|232x51|232x52|232x53|232x54|232x55|232x56|232x57|232x58|232x59|232x60|232x61|232x62|232x63|232x64|232x65|232x66|232x67|232x68|232x69|232x70|232x71|232x72|232x73|232x74|232x75|232x76|232x77|232x78|232x79|232x80|240x1|240x2|240x3|240x4|240x5|240x6|240x7|240x8|240x9|240x10|240x11|240x12|240x13|240x14|240x15|240x16|240x17|240x18|240x19|240x20|240x21|240x22|240x23|240x24|240x25|240x26|240x27|240x28|240x29|240x30|240x31|240x32|240x33|240x34|240x35|240x36|240x37|240x38|240x39|240x40|240x41|240x42|240x43|240x44|240x45|240x46|240x47|240x48|240x49|240x50|240x51|240x52|240x53|240x54|240x55|240x56|240x57|240x58|240x59|240x60|240x61|240x62|240x63|240x64|240x65|240x66|240x67|240x68|240x69|240x70|240x71|240x72|240x73|240x74|240x75|240x76|240x77|240x78|240x79|240x80|248x1|248x2|248x3|248x4|248x5|248x6|248x7|248x8|248x9|248x10|248x11|248x12|248x13|248x14|248x15|248x16|248x17|248x18|248x19|248x20|248x21|248x22|248x23|248x24|248x25|248x26|248x27|248x28|248x29|248x30|248x31|248x32|248x33|248x34|248x35|248x36|248x37|248x38|248x39|248x40|248x41|248x42|248x43|248x44|248x45|248x46|248x47|248x48|248x49|248x50|248x51|248x52|248x53|248x54|248x55|248x56|248x57|248x58|248x59|248x60|248x61|248x62|248x63|248x64|248x65|248x66|248x67|248x68|248x69|248x70|248x71|248x72|248x73|248x74|248x75|248x76|248x77|248x78|248x79|248x80|256x1|256x2|256x3|256x4|256x5|256x6|256x7|256x8|256x9|256x10|256x11|256x12|256x13|256x14|256x15|256x16|256x17|256x18|256x19|256x20|256x21|256x22|256x23|256x24|256x25|256x26|256x27|256x28|256x29|256x30|256x31|256x32|256x33|256x34|256x35|256x36|256x37|256x38|256x39|256x40|256x41|256x42|256x43|256x44|256x45|256x46|256x47|256x48|256x49|256x50|256x51|256x52|256x53|256x54|256x55|256x56|256x57|256x58|256x59|256x60|256x61|256x62|256x63|256x64|256x65|256x66|256x67|256x68|256x69|256x70|256x71|256x72|256x73|256x74|256x75|256x76|256x77|256x78|256x79|256x80)?(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^bytes(0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|32)(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^bytes(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^function(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^string(\\\\[[0-9]*\\\\])*$\"},{\"type\":\"string\",\"pattern\":\"^tuple(\\\\[[0-9]*\\\\])*$\"}]},\"StateMutability\":{\"type\":\"string\",\"enum\":[\"pure\",\"view\",\"nonpayable\",\"payable\"]},\"NormalFunction\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"function\"],\"default\":\"function\"},\"name\":{\"$ref\":\"#/definitions/Name\"},\"inputs\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"}},\"outputs\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"},\"default\":[]},\"stateMutability\":{\"$ref\":\"#/definitions/StateMutability\"},\"constant\":{\"type\":\"boolean\"},\"payable\":{\"type\":\"boolean\"}},\"anyOf\":[{\"required\":[\"name\",\"inputs\",\"stateMutability\"]},{\"required\":[\"name\",\"inputs\",\"constant\",\"payable\"]}],\"additionalProperties\":false},\"ConstructorFunction\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"constructor\"]},\"inputs\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"}},\"stateMutability\":{\"$ref\":\"#/definitions/StateMutability\"},\"constant\":{\"type\":\"boolean\"},\"payable\":{\"type\":\"boolean\"}},\"anyOf\":[{\"required\":[\"type\",\"inputs\",\"stateMutability\"]},{\"required\":[\"type\",\"inputs\",\"payable\"]}],\"additionalProperties\":false},\"FallbackFunction\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"fallback\"]},\"stateMutability\":{\"$ref\":\"#/definitions/StateMutability\"},\"payable\":{\"type\":\"boolean\"}},\"anyOf\":[{\"required\":[\"type\",\"stateMutability\"]},{\"required\":[\"type\",\"payable\"]}],\"additionalProperties\":false},\"ReceiveFunction\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"receive\"]},\"stateMutability\":{\"type\":\"string\",\"enum\":[\"payable\"]}},\"required\":[\"type\",\"stateMutability\"],\"additionalProperties\":false},\"Event\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"event\"]},\"name\":{\"$ref\":\"#/definitions/Name\"},\"inputs\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/EventParameter\"}},\"anonymous\":{\"type\":\"boolean\"}},\"required\":[\"type\",\"name\",\"inputs\",\"anonymous\"],\"additionalProperties\":false},\"Error\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"error\"]},\"name\":{\"$ref\":\"#/definitions/Name\"},\"inputs\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"}}},\"required\":[\"type\",\"name\",\"inputs\"],\"additionalProperties\":false},\"Parameter\":{\"type\":\"object\",\"if\":{\"properties\":{\"type\":{\"oneOf\":[{\"pattern\":\"^tuple\"}]}}},\"then\":{\"properties\":{\"name\":{\"$ref\":\"#/definitions/Name\"},\"type\":{\"$ref\":\"#/definitions/Type\"},\"components\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"}},\"internalType\":{\"type\":\"string\"}},\"required\":[\"name\",\"type\",\"components\"],\"additionalProperties\":false},\"else\":{\"properties\":{\"name\":{\"$ref\":\"#/definitions/Name\"},\"type\":{\"$ref\":\"#/definitions/Type\"},\"internalType\":{\"type\":\"string\"}},\"required\":[\"name\",\"type\"],\"additionalProperties\":false}},\"EventParameter\":{\"type\":\"object\",\"if\":{\"properties\":{\"type\":{\"oneOf\":[{\"pattern\":\"^tuple\"}]}}},\"then\":{\"properties\":{\"name\":{\"$ref\":\"#/definitions/Name\"},\"type\":{\"$ref\":\"#/definitions/Type\"},\"components\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/definitions/Parameter\"}},\"indexed\":{\"type\":\"boolean\"},\"internalType\":{\"type\":\"string\"}},\"required\":[\"name\",\"type\",\"components\",\"indexed\"],\"additionalProperties\":false},\"else\":{\"properties\":{\"name\":{\"$ref\":\"#/definitions/Name\"},\"type\":{\"$ref\":\"#/definitions/Type\"},\"indexed\":{\"type\":\"boolean\"},\"internalType\":{\"type\":\"string\"}},\"required\":[\"name\",\"type\",\"indexed\"],\"additionalProperties\":false}}}}");

/***/ }),

/***/ 191412:
/***/ ((module) => {

"use strict";
module.exports = JSON.parse("{\"$id\":\"contract-object.spec.json\",\"$schema\":\"http://json-schema.org/schema#\",\"title\":\"Contract Object\",\"description\":\"Describes a contract consumable by Truffle, possibly including deployed instances on networks\",\"type\":\"object\",\"properties\":{\"contractName\":{\"$ref\":\"#/definitions/ContractName\",\"description\":\"Name used to identify the contract\",\"default\":\"Contract\"},\"abi\":{\"$ref\":\"abi.spec.json#\",\"description\":\"Interface description returned by compiler for source\"},\"metadata\":{\"$ref\":\"#/definitions/Metadata\"},\"bytecode\":{\"$ref\":\"#/definitions/Bytecode\",\"description\":\"Bytecode sent as contract-creation transaction data, with unresolved link references\"},\"deployedBytecode\":{\"$ref\":\"#/definitions/Bytecode\",\"description\":\"On-chain deployed contract bytecode, with unresolved link references\"},\"sourceMap\":{\"$ref\":\"#/definitions/SourceMap\",\"description\":\"Source mapping for contract-creation transaction data bytecode\"},\"deployedSourceMap\":{\"$ref\":\"#/definitions/SourceMap\",\"description\":\"Source mapping for contract bytecode\"},\"source\":{\"$ref\":\"#/definitions/Source\"},\"sourcePath\":{\"$ref\":\"#/definitions/SourcePath\"},\"ast\":{\"$ref\":\"#/definitions/AST\"},\"legacyAST\":{\"$ref\":\"#/definitions/LegacyAST\"},\"compiler\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"version\":{\"type\":\"string\"}}},\"networks\":{\"type\":\"object\",\"patternProperties\":{\"^[a-zA-Z0-9]+$\":{\"$ref\":\"network-object.spec.json#\"}},\"additionalProperties\":false},\"schemaVersion\":{\"$ref\":\"#/definitions/SchemaVersion\"},\"updatedAt\":{\"type\":\"string\",\"format\":\"date-time\"},\"networkType\":{\"$ref\":\"#/definitions/NetworkType\",\"default\":\"ethereum\"},\"devdoc\":{\"$ref\":\"#/definitions/NatSpec\"},\"userdoc\":{\"$ref\":\"#/definitions/NatSpec\"},\"immutableReferences\":{\"$ref\":\"#/definitions/ImmutableReferences\"},\"generatedSources\":{\"$ref\":\"#/definitions/GeneratedSources\"},\"deployedGeneratedSources\":{\"$ref\":\"#/definitions/GeneratedSources\"},\"db\":{\"type\":\"object\",\"patternProperties\":{\"^[a-zA-Z0-9]+$\":{\"type\":\"object\",\"description\":\"Reference to @truffle/db canonical ID object for correlation purposes\",\"properties\":{\"id\":{\"type\":\"string\"}}}}}},\"required\":[\"abi\"],\"patternProperties\":{\"^x-\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"boolean\"},{\"type\":\"number\"},{\"type\":\"object\"},{\"type\":\"array\"}]}},\"additionalProperties\":false,\"definitions\":{\"ContractName\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z_][a-zA-Z0-9_]*$\"},\"NatSpec\":{\"type\":\"object\"},\"Metadata\":{\"type\":\"string\"},\"NetworkType\":{\"type\":\"string\"},\"Bytecode\":{\"type\":\"string\",\"pattern\":\"^0x0?$|^0x([a-fA-F0-9]{2}|__.{38})+$\"},\"ImmutableReferences\":{\"type\":\"object\",\"patternProperties\":{\"[1-9][0-9]*\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"start\":{\"type\":\"integer\",\"minimum\":0},\"length\":{\"type\":\"integer\",\"minimum\":0}},\"additionalProperties\":false}}},\"additionalProperties\":false},\"GeneratedSources\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"integer\",\"minimum\":0},\"language\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"},\"contents\":{\"type\":\"string\"},\"ast\":{\"type\":\"object\"}},\"additionalProperties\":false}},\"Source\":{\"type\":\"string\"},\"SourceMap\":{\"type\":\"string\",\"examples\":[\"315:637:1:-;;;452:55;;;;;;;-1:-1:-1;;;;;485:9:1;476:19;:8;:19;;;;;;;;;;498:5;476:27;;452:55;315:637;;;;;;;\"]},\"SourcePath\":{\"type\":\"string\"},\"AST\":{\"type\":\"object\"},\"LegacyAST\":{\"type\":\"object\"},\"SchemaVersion\":{\"type\":\"string\",\"pattern\":\"[0-9]+\\\\.[0-9]+\\\\.[0-9]+\"}}}");

/***/ }),

/***/ 459874:
/***/ ((module) => {

"use strict";
module.exports = JSON.parse("{\"$id\":\"network-object.spec.json\",\"$schema\":\"http://json-schema.org/schema#\",\"title\":\"Network Object\",\"type\":\"object\",\"properties\":{\"address\":{\"$ref\":\"#/definitions/Address\"},\"transactionHash\":{\"$ref\":\"#/definitions/TransactionHash\"},\"events\":{\"type\":\"object\",\"patternProperties\":{\"^0x[a-fA-F0-9]{64}$\":{\"$ref\":\"abi.spec.json#/definitions/Event\"}},\"additionalProperties\":false},\"links\":{\"type\":\"object\",\"patternProperties\":{\"^[a-zA-Z_][a-zA-Z0-9_]*$\":{\"$ref\":\"#/definitions/Address\"}},\"additionalProperties\":false},\"db\":{\"type\":\"object\",\"patternProperties\":{\"^[a-zA-Z0-9]+$\":{\"type\":\"object\",\"description\":\"Reference to @truffle/db canonical ID object for correlation purposes\",\"properties\":{\"id\":{\"type\":\"string\"}}}}}},\"additionalProperties\":false,\"definitions\":{\"Address\":{\"type\":\"string\",\"pattern\":\"^0x[a-fA-F0-9]{40}$\"},\"TransactionHash\":{\"type\":\"string\",\"pattern\":\"^0x[a-fA-F0-9]{64}$\"}}}");

/***/ }),

/***/ 378883:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Schema = __webpack_require__(418370);
const Contract = __webpack_require__(807974);
const truffleContractVersion = __webpack_require__(996191)/* .version */ .i8;

const contract = (json = {}) => {
  const normalizedArtifactObject = Schema.normalize(json);

  // Note we don't use `new` here at all. This will cause the class to
  // "mutate" instead of instantiate an instance.
  return Contract.clone(normalizedArtifactObject);
};

contract.version = truffleContractVersion;

module.exports = contract;

if (typeof window !== "undefined") {
  window.TruffleContract = contract;
}


/***/ }),

/***/ 85210:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const execute = __webpack_require__(141441);
const debug = __webpack_require__(774685)("contract:contract:bootstrap");

module.exports = fn => {
  // Add our static methods
  // Add something here about excluding send, privately defined methods
  Object.keys(fn._constructorMethods).forEach(function (key) {
    fn[key] = fn._constructorMethods[key].bind(fn);
  });

  // Add our properties.
  Object.keys(fn._properties).forEach(function (key) {
    fn.addProp(key, fn._properties[key]);
  });

  // estimateGas & request as sub-property of new
  fn["new"].estimateGas = execute.estimateDeployment.bind(fn);
  fn["new"].request = execute.requestDeployment.bind(fn);

  //add enumerations. (probably these should go in
  //constructorMethods.js, but this is easier to modify... we'll
  //redo all this in the rewrite anyway)
  if (fn._json) {
    //getters will throw otherwise!
    if (fn.ast) {
      //note this was set up earlier
      const node = locateNode(fn.contractName, fn.ast); //name also set up earlier
      if (node) {
        fn.enums = extractEnums(node);
        for (const [name, enumeration] of Object.entries(fn.enums)) {
          //enum is a reserved word :P
          if (!(name in fn)) {
            //don't overwrite anything!
            fn[name] = enumeration;
          }
        }
      }
    }
  }

  return fn;
};

function locateNode(name, ast) {
  if (ast.nodeType === "SourceUnit") {
    return ast.nodes.find(
      node => node.nodeType === "ContractDefinition" && node.name === name
    );
  } else {
    return undefined;
  }
}

function extractEnums(node) {
  return Object.assign(
    {},
    ...node.nodes
      .filter(definition => definition.nodeType === "EnumDefinition")
      .map(definition => ({
        [definition.name]: Object.assign(
          {},
          ...definition.members.map((member, index) => ({[member.name]: index}))
        )
      }))
  );
}


/***/ }),

/***/ 402629:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const {
  Web3Shim,
  createInterfaceAdapter
} = __webpack_require__(936339);
const utils = __webpack_require__(913735);
const execute = __webpack_require__(141441);
const bootstrap = __webpack_require__(85210);
const debug = __webpack_require__(774685)("contract:contract:constructorMethods");
const OS = __webpack_require__(712087);

module.exports = Contract => ({
  configureNetwork({ networkType, provider } = {}) {
    // otherwise use existing value as default (at most one of these)
    networkType = networkType || this.networkType;
    provider = provider || this.currentProvider;

    // recreate interfaceadapter
    this.interfaceAdapter = createInterfaceAdapter({ networkType, provider });

    if (this.web3) {
      // update existing
      this.web3.setNetworkType(networkType);
      this.web3.setProvider(provider);
    } else {
      // create new
      this.web3 = new Web3Shim({ networkType, provider });
    }

    // save properties
    this.currentProvider = provider;
    this.networkType = networkType;
  },

  setProvider(provider) {
    if (!provider) {
      throw new Error(
        `Invalid provider passed to setProvider(); provider is ${provider}`
      );
    }

    this.configureNetwork({ provider });
  },

  new() {
    utils.checkProvider(this);

    if (!this.bytecode || this.bytecode === "0x") {
      throw new Error(
        `${this.contractName} error: contract binary not set. Can't deploy new instance.\n` +
          `This contract may be abstract, not implement an abstract parent's methods completely\n` +
          `or not invoke an inherited contract's constructor correctly\n`
      );
    }

    var constructorABI = this.abi.filter(i => i.type === "constructor")[0];

    return execute.deploy.call(this, constructorABI)(...arguments);
  },

  async at(address) {
    if (
      address == null ||
      typeof address !== "string" ||
      address.length !== 42
    ) {
      throw new Error(
        `Invalid address passed to ${this.contractName}.at(): ${address}`
      );
    }

    await this.detectNetwork();
    const onChainCode = await this.interfaceAdapter.getCode(address);
    await utils.checkCode(onChainCode, this.contractName, address);
    return new this(address);
  },

  async deployed() {
    if (this.reloadJson) {
      this.reloadJson(); //truffle test monkey-patches in this method
    }
    utils.checkProvider(this);
    await this.detectNetwork();
    utils.checkNetworkArtifactMatch(this);
    utils.checkDeployment(this);
    return new this(this.address);
  },

  defaults(class_defaults) {
    if (this.class_defaults == null) {
      this.class_defaults = {};
    }

    if (class_defaults == null) {
      class_defaults = {};
    }

    Object.keys(class_defaults).forEach(key => {
      const value = class_defaults[key];
      this.class_defaults[key] = value;
    });

    return this.class_defaults;
  },

  hasNetwork(network_id) {
    return this._json.networks[`${network_id}`] != null;
  },

  isDeployed() {
    if (this.network_id == null) {
      return false;
    }

    if (this._json.networks[this.network_id] == null) {
      return false;
    }

    return !!this.network.address;
  },

  async detectNetwork() {
    // if artifacts already have a network_id and network configuration synced,
    // use that network and use latest block gasLimit
    if (this.network_id && this.networks[this.network_id] != null) {
      const { gasLimit } = await this.interfaceAdapter.getBlock("latest");
      return { id: this.network_id, blockLimit: gasLimit };
    }
    // since artifacts don't have a network_id synced with a network configuration,
    // poll chain for network_id and sync artifacts
    const chainNetworkID = await this.interfaceAdapter.getNetworkId();
    const { gasLimit } = await this.interfaceAdapter.getBlock("latest");
    return await utils.setInstanceNetworkID(this, chainNetworkID, gasLimit);
  },

  setNetwork(network_id) {
    if (!network_id) return;
    this.network_id = `${network_id}`;
  },

  setNetworkType(networkType = "ethereum") {
    this.configureNetwork({ networkType });
  },

  setWallet(wallet) {
    this.configureNetwork();

    this.web3.eth.accounts.wallet = wallet;
  },

  // Overrides the deployed address to null.
  // You must call this explicitly so you don't inadvertently do this otherwise.
  resetAddress() {
    delete this.network.address;
  },

  // accepts 4 input formats
  //  - (<name>, <address>)
  //  - (<contractType>) - must have a deployed instance with an address
  //  - (<contractInstance>)
  //  - ({ <libName>: <address>, <libName2>: <address2>, ... })
  link(name, address) {
    switch (typeof name) {
      case "string":
        // Case: Contract.link(<libraryName>, <address>)
        if (this._json.networks[this.network_id] == null) {
          this._json.networks[this.network_id] = {
            events: {},
            links: {}
          };
        }

        this.network.links[name] = address;
        return;
      case "function":
        // Case: Contract.link(<contractType>)
        const contract = name;

        if (contract.isDeployed() === false) {
          throw new Error("Cannot link contract without an address.");
        }

        this.link(contract.contractName, contract.address);

        // Merge events so this contract knows about library's events
        Object.keys(contract.events).forEach(topic => {
          this.network.events[topic] = contract.events[topic];
        });
        return;
      case "object":
        // 2 Cases:
        //   - Contract.link({<libraryName>: <address>, ... })
        //   - Contract.link(<instance>)
        const obj = name;
        if (
          obj.constructor &&
          typeof obj.constructor.contractName === "string" &&
          obj.address
        ) {
          // obj is a Truffle contract instance
          this.link(obj.constructor.contractName, obj.address);
        } else {
          // obj is of the form { <libraryName>: <address>, ... }
          Object.keys(obj).forEach(name => this.link(name, obj[name]));
        }
        return;
      default:
        const invalidInput =
          `Input to the link method is in the incorrect` +
          ` format. Input must be one of the following:${OS.EOL}` +
          `    - a library name and address                 > ("MyLibrary", ` +
          `"0x123456789...")${OS.EOL}` +
          `    - a contract type                            > ` +
          `(MyContract)${OS.EOL}` +
          `    - a contract instance                        > ` +
          `(myContract)${OS.EOL}` +
          `    - an object with library names and addresses > ({ <libName>: ` +
          `<address>, <libName2>: <address2>, ... })${OS.EOL}`;
        throw new Error(invalidInput);
    }
  },

  // Note, this function can be called with two input types:
  // 1. Object with a bunch of data; this data will be merged with the json data of contract being cloned.
  // 2. network id; this will clone the contract and set a specific network id upon cloning.
  clone(json) {
    json = json || {};

    const temp = function TruffleContract() {
      this.constructor = temp;
      return Contract.apply(this, arguments);
    };

    temp.prototype = Object.create(this.prototype);

    let network_id;

    // If we have a network id passed
    if (typeof json !== "object") {
      network_id = json;
      json = this._json;
    }

    json = utils.merge({}, this._json || {}, json);

    temp._constructorMethods = this._constructorMethods;
    temp._properties = this._properties;

    temp._property_values = {};
    temp._json = json;

    bootstrap(temp);

    temp.class_defaults = temp.prototype.defaults || {};

    if (network_id) {
      temp.setNetwork(network_id);
    }

    if (this.currentProvider) {
      temp.configureNetwork({
        provider: this.currentProvider,
        networkType: this.networkType
      });
    }

    // Copy over custom key/values to the contract class
    Object.keys(json).forEach(key => {
      if (key.indexOf("x-") !== 0) return;
      temp[key] = json[key];
    });

    return temp;
  },

  addProp(key, fn) {
    const getter = () => {
      if (fn.get != null) {
        return fn.get.call(this);
      }

      return this._property_values[key] || fn.call(this);
    };

    const setter = val => {
      if (fn.set != null) {
        fn.set.call(this, val);
        return;
      }

      // If there's not a setter, then the property is immutable.
      throw new Error(`${key} property is immutable`);
    };

    const definition = {};
    definition.enumerable = false;
    definition.configurable = false;
    definition.get = getter;
    definition.set = setter;

    Object.defineProperty(this, key, definition);
  },

  toJSON() {
    return this._json;
  },

  decodeLogs: utils.decodeLogs
});


/***/ }),

/***/ 807974:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/* module decorator */ module = __webpack_require__.nmd(module);
const debug = __webpack_require__(774685)("contract:contract");
let Web3 = __webpack_require__(503283);
const webUtils = __webpack_require__(118269);
const execute = __webpack_require__(141441);
const bootstrap = __webpack_require__(85210);
const constructorMethods = __webpack_require__(402629);
const properties = __webpack_require__(40920);

// For browserified version. If browserify gave us an empty version,
// look for the one provided by the user.
if (typeof Web3 === "object" && Object.keys(Web3).length === 0) {
  Web3 = global.Web3;
}

(function (module) {
  // Accepts a contract object created with web3.eth.Contract or an address.
  function Contract(contract) {
    var instance = this;
    var constructor = instance.constructor;

    // Disambiguate between .at() and .new()
    if (typeof contract === "string") {
      var web3Instance = new constructor.web3.eth.Contract(constructor.abi);
      web3Instance.options.address = contract;
      contract = web3Instance;
    }

    // Core:
    instance.methods = {};
    instance.abi = constructor.abi;
    instance.address = contract.options.address;
    instance.transactionHash = contract.transactionHash;
    instance.contract = contract;

    //for stacktracing in tests
    if (constructor.debugger) {
      instance.debugger = constructor.debugger;
    }

    // User defined methods, overloaded methods, events
    instance.abi.forEach(function (item) {
      switch (item.type) {
        case "function":
          var isConstant =
            ["pure", "view"].includes(item.stateMutability) || item.constant; // new form // deprecated case

          var signature = webUtils._jsonInterfaceMethodToString(item);

          var method = function (constant, web3Method) {
            var fn;

            constant
              ? (fn = execute.call.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ))
              : (fn = execute.send.call(
                  constructor,
                  web3Method,
                  item,
                  instance.address
                ));

            fn.call = execute.call.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.sendTransaction = execute.send.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.estimateGas = execute.estimate.call(
              constructor,
              web3Method,
              item,
              instance.address
            );
            fn.request = execute.request.call(
              constructor,
              web3Method,
              item,
              instance.address
            );

            return fn;
          };

          // Only define methods once. Any overloaded methods will have all their
          // accessors available by ABI signature available on the `methods` key below.
          if (instance[item.name] === undefined) {
            instance[item.name] = method(
              isConstant,
              contract.methods[item.name]
            );
          }

          // Overloaded methods should be invoked via the .methods property
          instance.methods[signature] = method(
            isConstant,
            contract.methods[signature]
          );
          break;

        case "event":
          instance[item.name] = execute.event.call(
            constructor,
            contract.events[item.name]
          );
          break;
      }
    });

    // sendTransaction / send
    instance.sendTransaction = execute.send.call(
      constructor,
      null,
      null,
      instance.address
    );

    // Prefer user defined `send`
    if (!instance.send) {
      instance.send = (value, txParams = {}) => {
        const packet = Object.assign({value: value}, txParams);
        return instance.sendTransaction(packet);
      };
    }

    // Other events
    instance.allEvents = execute.allEvents.call(constructor, contract);
    instance.getPastEvents = execute.getPastEvents.call(constructor, contract);
  }

  Contract._constructorMethods = constructorMethods(Contract);

  // Getter functions are scoped to Contract object.
  Contract._properties = properties;

  bootstrap(Contract);
  module.exports = Contract;

  return Contract;
})(module || {});


/***/ }),

/***/ 40920:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const utils = __webpack_require__(913735);
const web3Utils = __webpack_require__(118269);

module.exports = {
  contract_name: {
    get: function () {
      return this.contractName;
    },
    set: function (val) {
      this.contractName = val;
    }
  },
  contractName: {
    get: function () {
      return this._json.contractName || "Contract";
    },
    set: function (val) {
      this._json.contractName = val;
    }
  },

  gasMultiplier: {
    get: function () {
      if (this._json.gasMultiplier === undefined) {
        this._json.gasMultiplier = 1.25;
      }
      return this._json.gasMultiplier;
    },
    set: function (val) {
      this._json.gasMultiplier = val;
    }
  },
  timeoutBlocks: {
    get: function () {
      return this._json.timeoutBlocks;
    },
    set: function (val) {
      this._json.timeoutBlocks = val;
    }
  },
  autoGas: {
    get: function () {
      if (this._json.autoGas === undefined) {
        this._json.autoGas = true;
      }
      return this._json.autoGas;
    },
    set: function (val) {
      this._json.autoGas = val;
    }
  },
  numberFormat: {
    get: function () {
      if (this._json.numberFormat === undefined) {
        this._json.numberFormat = "BN";
      }
      return this._json.numberFormat;
    },
    set: function (val) {
      const allowedFormats = ["BigNumber", "BN", "String"];

      const msg =
        `Invalid number format setting: "${val}": ` +
        `valid formats are: ${JSON.stringify(allowedFormats)}.`;

      if (!allowedFormats.includes(val)) throw new Error(msg);

      this._json.numberFormat = val;
    }
  },
  abi: {
    get: function () {
      return this._json.abi;
    },
    set: function (val) {
      this._json.abi = val;
    }
  },
  metadata: function () {
    return this._json.metadata;
  },
  network: function () {
    var network_id = this.network_id;

    if (network_id == null) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork(), run " +
        this.contractName +
        ".detectNetwork(), or use new()," +
        " at() or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    // TODO: this might be bad; setting a value on a get.
    if (this._json.networks[network_id] == null) {
      var error =
        this.contractName +
        " has no network configuration" +
        " for its current network id (" +
        network_id +
        ").";

      throw new Error(error);
    }

    var returnVal = this._json.networks[network_id];

    // Normalize output
    if (returnVal.links == null) {
      returnVal.links = {};
    }

    if (returnVal.events == null) {
      returnVal.events = {};
    }

    return returnVal;
  },
  networks: function () {
    return this._json.networks;
  },
  address: {
    get: function () {
      var address = this.network.address;

      if (address == null) {
        var error =
          "Cannot find deployed address: " +
          this.contractName +
          " not deployed or address not set.";
        throw new Error(error);
      }

      return address;
    },
    set: function (val) {
      if (val == null) {
        throw new Error("Cannot set deployed address; malformed value: " + val);
      }

      var network_id = this.network_id;

      if (network_id == null) {
        var error =
          this.contractName +
          " has no network id set, cannot lookup artifact data." +
          " Either set the network manually using " +
          this.contractName +
          ".setNetwork(), run " +
          this.contractName +
          ".detectNetwork()," +
          " or use new(), at() or deployed() as a thenable which will" +
          " detect the network automatically.";

        throw new Error(error);
      }

      // Create a network if we don't have one.
      if (this._json.networks[network_id] == null) {
        this._json.networks[network_id] = {
          events: {},
          links: {}
        };
      }

      // Finally, set the address.
      this.network.address = val;
    }
  },
  transactionHash: {
    get: function () {
      return this.network.transactionHash;
    },
    set: function (val) {
      this.network.transactionHash = val;
    }
  },
  links: function () {
    if (!this.network_id) {
      var error =
        this.contractName +
        " has no network id set, cannot lookup artifact data." +
        " Either set the network manually using " +
        this.contractName +
        ".setNetwork()," +
        " run " +
        this.contractName +
        ".detectNetwork(), or use new(), at()" +
        " or deployed() as a thenable which will detect the network automatically.";

      throw new Error(error);
    }

    if (this._json.networks[this.network_id] == null) {
      return {};
    }

    return this.network.links || {};
  },
  events: function () {
    var events;

    if (this._json.networks[this.network_id] == null) {
      events = {};
    } else {
      events = this.network.events || {};
    }

    // Merge abi events with whatever's returned.
    var abi = this.abi;

    abi.forEach(function (item) {
      if (item.type !== "event") return;

      if (item.signature) {
        events[item.signature] = item;
      } else {
        var signature = item.name + "(";

        item.inputs.forEach(function (input, index) {
          signature += input.type;

          if (index < item.inputs.length - 1) {
            signature += ",";
          }
        });

        signature += ")";

        var topic = web3Utils.keccak256(signature);

        events[topic] = item;
      }
    });

    return events;
  },
  binary: function () {
    return utils.linkBytecode(this.bytecode, this.links);
  },
  deployedBinary: function () {
    return utils.linkBytecode(this.deployedBytecode, this.links);
  },

  // deprecated; use bytecode
  unlinked_binary: {
    get: function () {
      return this.bytecode;
    },
    set: function (val) {
      this.bytecode = val;
    }
  },
  // alias for unlinked_binary; unlinked_binary will eventually be deprecated
  bytecode: {
    get: function () {
      return this._json.bytecode;
    },
    set: function (val) {
      this._json.bytecode = val;
    }
  },
  deployedBytecode: {
    get: function () {
      var code = this._json.deployedBytecode;

      if (!code) {
        return code;
      }

      if (code.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      return code;
    },
    set: function (val) {
      var code = val;

      if (val && val.indexOf("0x") !== 0) {
        code = "0x" + code;
      }

      this._json.deployedBytecode = code;
    }
  },
  sourceMap: {
    get: function () {
      return this._json.sourceMap;
    },
    set: function (val) {
      this._json.sourceMap = val;
    }
  },
  deployedSourceMap: {
    get: function () {
      return this._json.deployedSourceMap;
    },
    set: function (val) {
      this._json.deployedSourceMap = val;
    }
  },
  source: {
    get: function () {
      return this._json.source;
    },
    set: function (val) {
      this._json.source = val;
    }
  },
  sourcePath: {
    get: function () {
      return this._json.sourcePath;
    },
    set: function (val) {
      this._json.sourcePath = val;
    }
  },
  legacyAST: {
    get: function () {
      return this._json.legacyAST;
    },
    set: function (val) {
      this._json.legacyAST = val;
    }
  },
  ast: {
    get: function () {
      return this._json.ast;
    },
    set: function (val) {
      this._json.ast = val;
    }
  },
  compiler: {
    get: function () {
      return this._json.compiler;
    },
    set: function (val) {
      this._json.compiler = val;
    }
  },
  // Deprecated
  schema_version: function () {
    return this.schemaVersion;
  },
  schemaVersion: function () {
    return this._json.schemaVersion;
  },
  // deprecated
  updated_at: function () {
    return this.updatedAt;
  },
  updatedAt: function () {
    try {
      return this.network.updatedAt || this._json.updatedAt;
    } catch (e) {
      return this._json.updatedAt;
    }
  },
  userdoc: function () {
    return this._json.userdoc;
  },
  devdoc: function () {
    return this._json.devdoc;
  },
  networkType: {
    get: function () {
      return this._json.networkType || "ethereum";
    },
    set: function (_networkType) {
      this._json.networkType = _networkType;
    }
  },
  immutableReferences: {
    get: function () {
      return this._json.immutableReferences;
    },
    set: function (refs) {
      this._json.immutableReferences = refs;
    }
  },
  generatedSources: {
    get: function () {
      return this._json.generatedSources;
    },
    set: function (sources) {
      this._json.generatedSources = sources;
    }
  },
  deployedGeneratedSources: {
    get: function () {
      return this._json.deployedGeneratedSources;
    },
    set: function (sources) {
      this._json.deployedGeneratedSources = sources;
    }
  },
  db: {
    get: function () {
      return this._json.db;
    },
    set: function (db) {
      this._json.db = db;
    }
  }
};


/***/ }),

/***/ 141441:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(774685)("contract:execute");
const PromiEvent = __webpack_require__(420302);
const EventEmitter = __webpack_require__(128614);
const utils = __webpack_require__(913735);
const StatusError = __webpack_require__(460550);
const Reason = __webpack_require__(812630);
const handlers = __webpack_require__(399198);
const override = __webpack_require__(547009);
const reformat = __webpack_require__(190908);
const { sendTransactionManual } = __webpack_require__(895945);

const execute = {
  // -----------------------------------  Helpers --------------------------------------------------
  /**
   * Retrieves gas estimate multiplied by the set gas multiplier for a `sendTransaction` call.
   * @param  {Object} params     `sendTransaction` parameters
   * @param  {Number} blockLimit  most recent network block.blockLimit
   * @return {Number}             gas estimate
   */
  getGasEstimate: function (params, blockLimit) {
    const constructor = this;
    const interfaceAdapter = this.interfaceAdapter;

    return new Promise(function (accept) {
      // Always prefer specified gas - this includes gas set by class_defaults
      if (params.gas) return accept(params.gas);
      if (!constructor.autoGas) return accept();

      interfaceAdapter
        .estimateGas(params)
        .then(gas => {
          const bestEstimate = utils.multiplyBigNumberByDecimal(
            utils.bigNumberify(gas),
            constructor.gasMultiplier
          );

          // Don't go over blockLimit
          const limit = utils.bigNumberify(blockLimit);
          bestEstimate.gte(limit)
            ? accept(limit.sub(1).toHexString())
            : accept(bestEstimate.toHexString());

          // We need to let txs that revert through.
          // Often that's exactly what you are testing.
        })
        .catch(() => accept());
    });
  },

  /**
   * Prepares simple wrapped calls by checking network and organizing the method inputs into
   * objects web3 can consume.
   * @param  {Object} constructor   TruffleContract constructor
   * @param  {Object} methodABI     Function ABI segment w/ inputs & outputs keys.
   * @param  {Array}  _arguments    Arguments passed to method invocation
   * @return {Promise}              Resolves object w/ tx params disambiguated from arguments
   */
  prepareCall: async function (constructor, methodABI, _arguments) {
    let args = Array.prototype.slice.call(_arguments);
    let params = utils.getTxParams.call(constructor, methodABI, args);

    args = utils.convertToEthersBN(args);

    if (constructor.ens && constructor.ens.enabled) {
      const { web3 } = constructor;
      const processedValues = await utils.ens.convertENSNames({
        ensSettings: constructor.ens,
        inputArgs: args,
        inputParams: params,
        methodABI,
        web3
      });
      args = processedValues.args;
      params = processedValues.params;
    }

    const network = await constructor.detectNetwork();
    return { args, params, network };
  },

  /**
   * Disambiguates between transaction parameter objects and BN / BigNumber objects
   * @param  {Any}  arg
   * @return {Boolean}
   */
  hasTxParams: function (arg) {
    return utils.is_object(arg) && !utils.is_big_number(arg);
  },

  /**
   * Parses function arguments to discover if the terminal argument specifies the `defaultBlock`
   * to execute a call at.
   * @param  {Array}  args      `arguments` that were passed to method
   * @param  {Any}    lastArg    terminal argument passed to method
   * @param  {Array}  inputs     ABI segment defining method arguments
   * @return {Boolean}           true if final argument is `defaultBlock`
   */
  hasDefaultBlock: function (args, lastArg, inputs) {
    const hasDefaultBlock =
      !execute.hasTxParams(lastArg) && args.length > inputs.length;
    const hasDefaultBlockWithParams =
      execute.hasTxParams(lastArg) && args.length - 1 > inputs.length;
    return hasDefaultBlock || hasDefaultBlockWithParams;
  },

  // -----------------------------------  Methods --------------------------------------------------

  /**
   * Executes method as .call and processes optional `defaultBlock` argument.
   * @param  {Function} fn         method
   * @param  {Object}   methodABI  Function ABI segment w/ inputs & outputs keys.
   * @return {Promise}             Return value of the call.
   */
  call: function (fn, methodABI, address) {
    const constructor = this;

    return function () {
      let defaultBlock = constructor.web3.eth.defaultBlock || "latest";
      const args = Array.prototype.slice.call(arguments);
      const lastArg = args[args.length - 1];
      const promiEvent = new PromiEvent();

      // Extract defaultBlock parameter
      if (execute.hasDefaultBlock(args, lastArg, methodABI.inputs)) {
        defaultBlock = args.pop();
      }

      execute
        .prepareCall(constructor, methodABI, args)
        .then(async ({ args, params }) => {
          let result;

          params.to = address;

          promiEvent.eventEmitter.emit("execute:call:method", {
            fn: fn,
            args: args,
            address: address,
            abi: methodABI,
            contract: constructor
          });

          result = await fn(...args).call(params, defaultBlock);
          result = reformat.numbers.call(
            constructor,
            result,
            methodABI.outputs
          );
          return promiEvent.resolve(result);
        })
        .catch(promiEvent.reject);

      return promiEvent.eventEmitter;
    };
  },

  /**
   * Executes method as .send
   * @param  {Function} fn         Method to invoke
   * @param  {Object}   methodABI  Function ABI segment w/ inputs & outputs keys.
   * @param  {String}   address    Deployed address of the targeted instance
   * @return {PromiEvent}          Resolves a transaction receipt (via the receipt handler)
   */
  send: function (fn, methodABI, address) {
    const constructor = this;
    const web3 = constructor.web3;

    return function () {
      const promiEvent = new PromiEvent(false, constructor.debugger);

      execute
        .prepareCall(constructor, methodABI, arguments)
        .then(async ({ args, params, network }) => {
          const context = {
            contract: constructor, // Can't name this field `constructor` or `_constructor`
            promiEvent: promiEvent,
            params: params
          };

          params.to = address;
          params.data = fn ? fn(...args).encodeABI() : params.data;

          promiEvent.eventEmitter.emit("execute:send:method", {
            fn,
            args,
            address,
            abi: methodABI,
            contract: constructor
          });

          try {
            params.gas = await execute.getGasEstimate.call(
              constructor,
              params,
              network.blockLimit
            );
          } catch (error) {
            promiEvent.reject(error);
            return;
          }

          execute
            .sendTransaction(web3, params, promiEvent, context) //the crazy things we do for stacktracing...
            .then(receipt => {
              if (promiEvent.debug) {
                // in this case, we need to manually invoke the handler since it
                // hasn't been set up (hack?)
                handlers.receipt(context, receipt);
              }
              //otherwise, just let the handlers handle things
            })
            .catch(override.start.bind(constructor, context));
        })
        .catch(promiEvent.reject);

      return promiEvent.eventEmitter;
    };
  },

  /**
   * Deploys an instance
   * @param  {Object} constructorABI  Constructor ABI segment w/ inputs & outputs keys
   * @return {PromiEvent}             Resolves a TruffleContract instance
   */
  deploy: function (constructorABI) {
    const constructor = this;
    const web3 = constructor.web3;

    return function () {
      let deferred;
      const promiEvent = new PromiEvent(false, constructor.debugger, true);

      execute
        .prepareCall(constructor, constructorABI, arguments)
        .then(async ({ args, params, network }) => {
          const { blockLimit } = network;

          utils.checkLibraries.apply(constructor);

          // Promievent and flag that allows instance to resolve (rather than just receipt)
          const context = {
            contract: constructor,
            promiEvent,
            onlyEmitReceipt: true
          };

          const options = {
            data: constructor.binary,
            arguments: args
          };

          const contract = new web3.eth.Contract(constructor.abi);
          params.data = contract.deploy(options).encodeABI();

          params.gas = await execute.getGasEstimate.call(
            constructor,
            params,
            blockLimit
          );

          context.params = params;

          promiEvent.eventEmitter.emit("execute:deploy:method", {
            args,
            abi: constructorABI,
            contract: constructor
          });

          deferred = execute.sendTransaction(web3, params, promiEvent, context); //the crazy things we do for stacktracing...

          try {
            const receipt = await deferred;
            if (receipt.status !== undefined && !receipt.status) {
              const reason = await Reason.get(params, web3);

              const error = new StatusError(
                params,
                context.transactionHash,
                receipt,
                reason
              );

              return context.promiEvent.reject(error);
            }

            const web3Instance = new web3.eth.Contract(
              constructor.abi,
              receipt.contractAddress
            );
            web3Instance.transactionHash = context.transactionHash;

            context.promiEvent.resolve(new constructor(web3Instance));
          } catch (web3Error) {
            // Manage web3's 50 blocks' timeout error.
            // Web3's own subscriptions go dead here.
            await override.start.call(constructor, context, web3Error);
          }
        })
        .catch(promiEvent.reject);

      return promiEvent.eventEmitter;
    };
  },

  /**
   * Begins listening for an event OR manages the event callback
   * @param  {Function} fn  Solidity event method
   * @return {Emitter}      Event emitter
   */
  event: function (fn) {
    const constructor = this;
    const decode = utils.decodeLogs;
    let currentLogID = null;

    // Someone upstream is firing duplicates :/
    function dedupe(id) {
      return id === currentLogID ? false : (currentLogID = id);
    }

    return function (params, callback) {
      if (typeof params === "function") {
        callback = params;
        params = {};
      }

      // As callback
      if (callback !== undefined) {
        const intermediary = function (err, e) {
          if (err) return callback(err);
          if (!dedupe(e.id)) return;
          callback(null, decode.call(constructor, e, true)[0]);
        };

        return constructor
          .detectNetwork()
          .then(() => fn.call(constructor.events, params, intermediary));
      }

      // As EventEmitter
      const emitter = new EventEmitter();

      constructor.detectNetwork().then(() => {
        const event = fn(params);

        event.on(
          "data",
          e =>
            dedupe(e.id) &&
            emitter.emit("data", decode.call(constructor, e, true)[0])
        );
        event.on(
          "changed",
          e =>
            dedupe(e.id) &&
            emitter.emit("changed", decode.call(constructor, e, true)[0])
        );
        event.on("error", e => emitter.emit("error", e));
      });

      return emitter;
    };
  },

  /**
   * Wraps web3 `allEvents`, with additional log decoding
   * @return {PromiEvent}  EventEmitter
   */
  allEvents: function (web3Instance) {
    const constructor = this;
    const decode = utils.decodeLogs;
    let currentLogID = null;

    // Someone upstream is firing duplicates :/
    function dedupe(id) {
      return id === currentLogID ? false : (currentLogID = id);
    }

    return function (params) {
      const emitter = new EventEmitter();

      constructor.detectNetwork().then(() => {
        const event = web3Instance.events.allEvents(params);

        event.on(
          "data",
          e =>
            dedupe(e.id) &&
            emitter.emit("data", decode.call(constructor, e, true)[0])
        );
        event.on(
          "changed",
          e =>
            dedupe(e.id) &&
            emitter.emit("changed", decode.call(constructor, e, true)[0])
        );
        event.on("error", e => emitter.emit("error", e));
      });

      return emitter;
    };
  },

  /**
   * Wraps web3 `getPastEvents`, with additional log decoding
   * @return {Promise}  Resolves array of event objects
   */
  getPastEvents: function (web3Instance) {
    const constructor = this;
    const decode = utils.decodeLogs;

    return function (event, options) {
      return web3Instance
        .getPastEvents(event, options)
        .then(events => decode.call(constructor, events, false));
    };
  },

  /**
   * Estimates gas cost of a method invocation
   * @param  {Function} fn  Method to target
   * @param  {Object}   methodABI  Function ABI segment w/ inputs & outputs keys.
   * @return {Promise}
   */
  estimate: function (fn, methodABI) {
    const constructor = this;
    return function () {
      return execute
        .prepareCall(constructor, methodABI, arguments)
        .then(res => fn(...res.args).estimateGas(res.params));
    };
  },

  /**
   *
   * @param  {Function} fn  Method to target
   * @param  {Object}   methodABI  Function ABI segment w/ inputs & outputs keys.
   * @return {Promise}
   */
  request: function (fn, methodABI, address) {
    const constructor = this;
    return function () {
      return execute
        .prepareCall(constructor, methodABI, arguments)
        .then(res => {
          //clone res.params
          let tx = {};
          for (let key in res.params) {
            tx[key] = res.params[key];
          }
          //set to
          tx.to = address;
          //set data
          tx.data = fn(...res.args).encodeABI();
          return tx;
        });
    };
  },

  // This gets attached to `.new` (declared as a static_method in `contract`)
  // during bootstrapping as `estimateGas`
  estimateDeployment: function () {
    const constructor = this;

    const constructorABI = constructor.abi.filter(
      i => i.type === "constructor"
    )[0];

    return execute
      .prepareCall(constructor, constructorABI, arguments)
      .then(res => {
        const options = {
          data: constructor.binary,
          arguments: res.args
        };

        delete res.params["data"]; // Is this necessary?

        const instance = new constructor.web3.eth.Contract(
          constructor.abi,
          res.params
        );
        return instance.deploy(options).estimateGas(res.params);
      });
  },

  // This gets attached to `.new` (declared as a static_method in `contract`)
  // during bootstrapping as `request`
  requestDeployment: function () {
    const constructor = this;

    const constructorABI = constructor.abi.filter(
      i => i.type === "constructor"
    )[0];

    return execute
      .prepareCall(constructor, constructorABI, arguments)
      .then(res => {
        //clone res.params
        let tx = {};
        for (let key in res.params) {
          tx[key] = res.params[key];
        }

        const options = {
          data: constructor.binary,
          arguments: res.args
        };

        const instance = new constructor.web3.eth.Contract(
          constructor.abi,
          res.params
        );
        tx.data = instance.deploy(options).encodeABI();
        return tx;
      });
  },

  //our own custom sendTransaction function, made to mimic web3's,
  //while also being able to do things, like, say, store the transaction
  //hash even in case of failure.  it's not as powerful in some ways,
  //as it just returns an ordinary Promise rather than web3's PromiEvent,
  //but it's more suited to our purposes (we're not using that PromiEvent
  //functionality here anyway)
  //input works the same as input to web3.sendTransaction
  //(well, OK, it's lacking some things there too, but again, good enough
  //for our purposes)
  sendTransaction: async function (web3, params, promiEvent, context) {
    //if we don't need the debugger, let's not risk any errors on our part,
    //and just have web3 do everything
    if (!promiEvent || !promiEvent.debug) {
      const deferred = web3.eth.sendTransaction(params);
      handlers.setup(deferred, context);
      return deferred;
    }
    //otherwise, do things manually!
    //(and skip the PromiEvent stuff :-/ )
    return sendTransactionManual(web3, params, promiEvent);
  }
};

module.exports = execute;


/***/ }),

/***/ 399198:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(774685)("contract:handlers");
const StatusError = __webpack_require__(460550);
const Utils = __webpack_require__(913735);
const Reason = __webpack_require__(812630);

/*
  Handlers for events emitted by `send` / `call` etc.
 */
const handlers = {
  // ----------------------------------- Constants -------------------------------------------------

  maxConfirmations: 24, // Maximum number of confirmation web3 emits
  defaultTimeoutBlocks: 50, // Maximum number of blocks web3 will wait before abandoning tx
  timeoutMessage: "50 blocks", // Substring of web3 timeout error.
  defaultWeb3Error: "please check your gas limit", // Substring of default Web3 error

  // -----------------------------------  Helpers --------------------------------------------------

  /**
   * Parses error message and determines if we should squash web3 timeout errors at user's request.
   * @param  {Object} contract contract instance
   * @param  {Object} message  error message
   * @return {Boolean}
   */
  ignoreTimeoutError({ contract }, { message }) {
    const timedOut = message && message.includes(handlers.timeoutMessage);

    const shouldWait =
      contract &&
      contract.timeoutBlocks &&
      contract.timeoutBlocks > handlers.defaultTimeoutBlocks;

    const waitForTxPropagation =
      message && message.includes(handlers.defaultWeb3Error);

    return shouldWait && (timedOut || waitForTxPropagation);
  },

  /**
   * Attaches Truffle specific handlers to all of the events emitted by a web3 method.
   * @param {Object}       context  execution state
   * @param {PromiEvent}   emitter  promiEvent returned by a web3 method call
   */
  setup: function(emitter, context) {
    emitter.on("error", handlers.error.bind(emitter, context));
    emitter.on("transactionHash", handlers.hash.bind(emitter, context));
    // web3 block polls if the confirmation listener is enabled so we want to
    // give users a way of opting out of this behavior - it causes problems in testing
    if (!context.contract.disableConfirmationListener) {
      emitter.on("confirmation", handlers.confirmation.bind(emitter, context));
    }
    emitter.on("receipt", handlers.receipt.bind(emitter, context));
  },

  // -----------------------------------  Handlers -------------------------------------------------
  /**
   * Error event handler. Emits error unless error is block timeout and user has
   * specified we should wait longer
   * @param  {Object} context   execution state
   * @param  {Object} error     error
   */
  error: function(context, error) {
    if (!handlers.ignoreTimeoutError(context, error)) {
      context.promiEvent.eventEmitter.emit("error", error);
      this.removeListener("error", handlers.error);
    }
  },

  /**
   * Transaction hash event handler. Attaches the hash to the context object
   * so it can be attached to the contract instance after a deployment resolves.
   * @param  {Object} context   execution state
   * @param  {String} hash      transaction hash
   */
  hash: function(context, hash) {
    context.transactionHash = hash;
    context.promiEvent.eventEmitter.emit("transactionHash", hash);
    this.removeListener("transactionHash", handlers.hash);
  },

  confirmation: function(context, number, receipt) {
    context.promiEvent.eventEmitter.emit("confirmation", number, receipt);

    // Per web3: initial confirmation index is 0
    if (number === handlers.maxConfirmations + 1) {
      this.removeListener("confirmation", handlers.confirmation);
    }
  },

  /**
   * Receipt event handler. This handler decodes the event logs, re-emits the receipt,
   * and (for method calls only) resolves/rejects the promiEvent with the receipt.
   * @param  {Object} context   execution state
   * @param  {Object} receipt   transaction receipt
   */
  receipt: async function(context, receipt) {
    // keep around the raw (not decoded) logs in the raw logs field as a
    // stopgap until we can get the ABI for all events, not just the current
    // contract
    receipt.rawLogs = receipt.logs;

    // Decode logs, use as receipt.logs for ease of use.
    try {
      receipt.logs = receipt.logs
        ? Utils.decodeLogs.call(context.contract, receipt.logs)
        : [];
    } catch (error) {
      return context.promiEvent.reject(error);
    }

    // Emit receipt
    context.promiEvent.eventEmitter.emit("receipt", receipt);

    // .new(): Exit early. We need the promiEvent to resolve a contract instance.
    if (context.onlyEmitReceipt) {
      context.receipt = receipt;
      return;
    }

    // .method(): resolve/reject receipt in handler
    if (receipt.status !== undefined && !receipt.status) {
      const reason = await Reason.get(
        context.params,
        context.contract.web3,
        context.contract.interfaceAdapter
      );

      const error = new StatusError(
        context.params,
        receipt.transactionHash,
        receipt,
        reason
      );

      return context.promiEvent.reject(error);
    }

    // This object has some duplicate data but is backward compatible.
    context.promiEvent.resolve({
      tx: receipt.transactionHash,
      receipt: receipt,
      logs: receipt.logs
    });

    //HACK: adding this conditional for when the handler is invoked
    //manually during stacktracing
    if (this.removeListener) {
      this.removeListener("receipt", handlers.receipt);
    }
  }
};

module.exports = handlers;


/***/ }),

/***/ 895945:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(774685)("contract:manual-send");
const ethers = __webpack_require__(204003);
const Utils = __webpack_require__ (913735);
const { formatters } = __webpack_require__(484390); //used for reproducing web3's behavior

//this is less manual now, it uses ethers, whew
//(it's still more manual than using web3)
async function sendTransactionManual(web3, params, promiEvent) {
  debug("executing manually!");
  //set up ethers provider
  const ethersProvider = new ethers.providers.Web3Provider(
    web3.currentProvider
  );
  //let's clone params and set it up properly
  const { transaction, from } = setUpParameters(params, web3);
  //now: if the from address is in the wallet, web3 will sign the transaction before
  //sending, so we have to account for that
  const account = web3.eth.accounts.wallet[from];
  const ethersSigner = account
    ? new ethers.Wallet(account.privateKey, ethersProvider)
    : ethersProvider.getSigner(from);
  debug("got signer");
  let txHash, receipt, ethersResponse;
  try {
    //note: the following code won't work with ethers v5.
    //wth ethers v5, in the getSigner() case, you'll need to
    //use sendUncheckedTransaction instead of sendTransaction.
    //I don't know why.
    ethersResponse = await ethersSigner.sendTransaction(transaction);
    txHash = ethersResponse.hash;
    receipt = await ethersProvider.waitForTransaction(txHash);
    debug("no error");
  } catch (error) {
    ({ txHash, receipt } = handleError(error));
    if (!receipt) {
      receipt = await ethersProvider.waitForTransaction(txHash);
    }
  }
  debug("txHash: %s", txHash);
  receipt = translateReceipt(receipt);
  promiEvent.setTransactionHash(txHash); //this here is why I wrote this function @_@
  return await handleResult(receipt, transaction.to == null);
}

function handleError(error) {
  debug("error: %O", error);
  if (error.data && Object.keys(error.data).length === 3) {
    //error.data will have 3 keys: stack, name, and the txHash
    const transactionHash = Object.keys(error.data).find(
      key => key !== "stack" && key !== "name"
    );
    return { txHash: transactionHash };
  } else if (error.transactionHash && error.receipt) {
    return {
      txHash: error.transactionHash,
      receipt: error.receipt
    };
  } else {
    throw error; //rethrow unexpected errors
  }
}

async function handleResult(receipt, isDeployment) {
  const deploymentFailedMessage = "The contract code couldn't be stored, please check your gas limit.";
  if (receipt.status) {
    if (isDeployment) {
      //in the deployment case, web3 might error even when technically successful @_@
      if ((await web3.eth.getCode(receipt.contractAddress)) === "0x") {
        throw new Error(deploymentFailedMessage);
      }
    }
    return receipt;
  } else {
    //otherwise: we have to mimic web3's errors @_@
    if (isDeployment) {
      //deployment case
      throw new Error(deploymentFailedMessage);
    }
    throw new Error(
      "Transaction has been reverted by the EVM:" +
        "\n" +
        JSON.stringify(receipt)
    );
  }
}

function setUpParameters(params, web3) {
  let transaction = Object.assign({}, params);
  transaction.from =
    transaction.from != undefined
      ? transaction.from
      : web3.eth.defaultAccount;
  //now let's have web3 check our inputs
  transaction = formatters.inputTransactionFormatter(transaction); //warning, not a pure fn
  //...but ethers uses gasLimit instead of gas like web3
  transaction.gasLimit = transaction.gas;
  delete transaction.gas;
  //also, it insists "from" be kept separate
  const { from } = transaction;
  delete transaction.from;
  return { transaction, from }
}

//translate the receipt to web3 format by converting BigNumbers
//(note: these are *ethers* BigNumbers) to numbers
function translateReceipt(receipt) {
  return Object.assign({},
    ...Object.entries(receipt).map(([key, value]) => ({
      [key]: Utils.is_big_number(value)
        ? value.toNumber()
        : value
    }))
  );
}

module.exports = {
  sendTransactionManual
}


/***/ }),

/***/ 547009:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Reason = __webpack_require__(812630);
const handlers = __webpack_require__(399198);

const override = {
  timeoutMessage: "not mined within", // Substring of timeout err fired by web3
  defaultWeb3Error: "please check your gas limit", // Substring of default Web3 error
  defaultMaxBlocks: 50, // Max # of blocks web3 will wait for a tx
  pollingInterval: 1000,

  /**
   * Attempts to extract receipt object from Web3 error message
   * @param  {Object} message       web3 error
   * @return {Object|undefined} receipt
   */
  extractReceipt(message) {
    const hasReceipt = message && message.includes("{");
    message.includes("}");

    if (hasReceipt) {
      const receiptString = "{" + message.split("{")[1].trim();
      try {
        return JSON.parse(receiptString);
      } catch (err) {
        // ignore
      }
    }
  },

  /**
   * Fired after web3 ceases to support subscriptions if user has specified
   * a higher block wait time than web3's 50 blocks limit. Opens a subscription to listen
   * for new blocks and begins evaluating whether block height has reached the user
   * defined timeout threshhold. Resolves either a contract instance or a transaction receipt.
   *
   * @param  {Object} context execution state
   * @param  {Object} err     error
   */
  start: async function(context, web3Error) {
    const constructor = this;
    let currentBlock = override.defaultMaxBlocks;

    // Reject after attempting to get reason string if we shouldn't be waiting.
    if (!handlers.ignoreTimeoutError(context, web3Error)) {
      // We might have been routed here in web3 >= beta.34 by their own status check
      // error. We want to extract the receipt, emit a receipt event
      // and reject it ourselves.
      const receipt = override.extractReceipt(web3Error.message);
      if (receipt) {
        await handlers.receipt(context, receipt);
        return;
      }

      // This will run if there's a reason and no status field
      // e.g: revert with reason ganache-cli --vmErrorsOnRPCResponse=true
      const reason = await Reason.get(
        context.params,
        constructor.web3,
        constructor.interfaceAdapter
      );
      if (reason) {
        web3Error.reason = reason;
        web3Error.message += ` -- Reason given: ${reason}.`;
      }

      return context.promiEvent.reject(web3Error);
    }

    // This will run every block from now until contract.timeoutBlocks
    const listener = function(pollID) {
      currentBlock++;

      if (currentBlock > constructor.timeoutBlocks) {
        clearInterval(pollID);
        return;
      }

      constructor.interfaceAdapter
        .getTransactionReceipt(context.transactionHash)
        .then(result => {
          if (!result) return;

          // make sure reporter receives tx receipt promievent
          handlers.receipt(context, result);
          result.contractAddress
            ? constructor
                .at(result.contractAddress)
                .then(context.promiEvent.resolve)
                .catch(context.promiEvent.reject)
            : constructor.promiEvent.resolve(result);
        })
        .catch(err => {
          clearInterval(pollID);
          context.promiEvent.reject(err);
        });
    };

    // Start polling
    let currentPollingBlock = await constructor.interfaceAdapter.getBlockNumber();

    const pollID = setInterval(async () => {
      const newBlock = await constructor.interfaceAdapter.getBlockNumber();

      if (newBlock > currentPollingBlock) {
        currentPollingBlock = newBlock;
        listener(pollID);
      }
    }, override.pollingInterval);
  }
};

module.exports = override;


/***/ }),

/***/ 420302:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(774685)("contract:promievent");
const DebugUtils = __webpack_require__(93293);
const Web3PromiEvent = __webpack_require__(304017);

function PromiEvent(justPromise, bugger = undefined, isDeploy = false) {
  const { resolve, reject, eventEmitter } = new Web3PromiEvent(justPromise);

  const originalStackTrace = new Error().stack;

  function rejectHijacker(e) {
    debug("hijacking!");
    debug("hash: %s", this.txHash);
    let getSolidityStackTrace;
    if (bugger && this.txHash) {
      debug("debugging time!");
      getSolidityStackTrace = async () => {
        try {
          await bugger.load(this.txHash);
          await bugger.continueUntilBreakpoint();
          const report = bugger.stacktrace();
          await bugger.unload();
          return DebugUtils.formatStacktrace(report, 4); //indent 4 to match node's stacktraces
        } catch (_) {
          //ignore errors
          return undefined;
        }
      };
    } else {
      getSolidityStackTrace = async () => undefined;
    }

    getSolidityStackTrace().then((solidityStackTrace) => {
      debug("e.stack: %s", e.stack);
      debug("originalStackTrace: %s", originalStackTrace);
      debug("solidityStackTrace: %s", solidityStackTrace);
      const initialLinesRegexp = isDeploy
        ? /^.*\n.*\n.*\n.*/ //first 4 lines (note . does not include \n)
        : /^.*\n.*\n.*/; //first 3 lines
      //we replace not just the first line but also the next 2 as they contain
      //useless stuff users shouldn't see; in case of deployments there's one
      //additional to remove
      try {
        let stackTrace = originalStackTrace.replace(
          initialLinesRegexp,
          e.stack.split("\n")[0]
        );
        if (solidityStackTrace) {
          //let's split the solidity stack trace into first line & rest
          let [
            _,
            solidityFirstLine,
            solidityRemaining,
          ] = solidityStackTrace.match(/^(.*?)\r?\n((.|\r|\n)*)$/);

          stackTrace = stackTrace.replace(
            /^.*/, //note that . does not include \n
            solidityRemaining //note: this does not end in \n, so no modification needed
          );
          e.hijackedMessage = e.message;
          e.message = solidityFirstLine;
        }

        e.hijackedStack = e.stack;
        e.stack = stackTrace;
      } catch (_) {
        //again, ignore errors
        //(not sure how this can happen here but I'll leave this block here)
      }
      reject(e);
    });
  }

  this.resolve = resolve;
  this.reject = rejectHijacker.bind(this);
  this.eventEmitter = eventEmitter;
  if (bugger) {
    this.debug = true;
  }
}

PromiEvent.resolve = Web3PromiEvent.resolve;

PromiEvent.prototype.setTransactionHash = function (txHash) {
  debug("setting!");
  debug("hash: %s", txHash);
  this.txHash = txHash;
};

module.exports = PromiEvent;


/***/ }),

/***/ 812630:
/***/ ((module) => {

/**
 * Methods to fetch and decode reason string from ganache when a tx errors.
 */

const reason = {
  /**
   * Extracts a reason string from `eth_call` response
   * @param  {Object}           res  response from `eth_call` to extract reason
   * @param  {Web3}             web3 a helpful friend
   * @param  {InterfaceAdapter}      interfaceAdapter a new helpful friend
   * @return {String|Undefined}      decoded reason string
   */
  _extract: function(res, web3, _interfaceAdapter) {
    //I'm not sure why interfaceAdapter is here if it's not used,
    //so I just put an underscore in front of its name for now...
    if (!res || (!res.error && !res.result)) return;

    const errorStringHash = "0x08c379a0";

    const isObject =
      res && typeof res === "object" && res.error && res.error.data;
    const isString =
      res && typeof res === "object" && typeof res.result === "string";

    if (isObject) {
      const data = res.error.data;
      const hash = Object.keys(data)[0];

      if (data[hash].return && data[hash].return.includes(errorStringHash)) {
        try {
          return web3.eth.abi.decodeParameter(
            "string",
            data[hash].return.slice(10)
          );
        } catch (_) {
          return undefined;
        }
      }
    } else if (isString && res.result.includes(errorStringHash)) {
      try {
        return web3.eth.abi.decodeParameter("string", res.result.slice(10));
      } catch (_) {
        return undefined;
      }
    }
  },

  /**
   * Runs tx via `eth_call` and resolves a reason string if it exists on the response.
   * @param  {Object} web3
   * @param  {Object} interfaceAdapter
   * @return {String|Undefined}
   */
  get: function(params, web3, interfaceAdapter) {
    const packet = {
      jsonrpc: "2.0",
      method: "eth_call",
      params: [params, "latest"],
      id: new Date().getTime()
    };

    return new Promise(resolve => {
      web3.currentProvider.send(packet, (err, response) => {
        const reasonString = reason._extract(response, web3, interfaceAdapter);
        resolve(reasonString);
      });
    });
  }
};

module.exports = reason;


/***/ }),

/***/ 190908:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

/**
 * Utilities for reformatting web3 outputs
 */
const BigNumber = __webpack_require__(800526);
const web3Utils = __webpack_require__(118269);

/**
 * Converts from string to other number format
 * @param  {String} val    number string returned by web3
 * @param  {String} format name of format to convert to
 * @return {Object|String} converted value
 */
const _convertNumber = function(val, format) {
  const badFormatMsg = `Attempting to convert to unknown number format: ${format}`;

  switch (format) {
    case "BigNumber":
      return new BigNumber(val);
    case "BN":
      return web3Utils.toBN(val);
    case "String":
      return val;
    default:
      throw new Error(badFormatMsg);
  }
};

/**
 * Converts arrays of number strings to other number formats
 * @param  {String[]} arr       number string array returned by web3
 * @param  {String}   format    name of format to convert to
 * @return {Object[]|String[]}  array of converted values
 */
const _convertNumberArray = function(arr, format, depth = 0) {
  if (depth == 0) return arr.map(item => _convertNumber(item, format));
  // arr is nested
  return arr.map(item => _convertNumberArray(item, format, depth - 1));
};

/**
 * Reformats numbers in the result/result-object of a web3 call.
 * Possible forms of `result` are:
 *   - object (with index keys and optionally, named keys)
 *   - array
 *   - single primitive
 * @param  {String|Object|Array} result      web3 call result
 * @param  {Array}               abiSegment  event params OR .call outputs
 * @return {String|Object|Array} reformatted result
 */
const numbers = function(result, abiSegment) {
  const format = this.numberFormat;

  abiSegment.forEach((output, i) => {
    // output is a number type (uint || int);
    if (output.type.includes("int")) {
      // output is an array type
      if (output.type.includes("[")) {
        // larger than zero if nested array
        let depth = output.type.split("[").length - 2;

        // result is array
        if (Array.isArray(result)) {
          result = _convertNumberArray(result, format, depth);

          // result is object
        } else {
          // output has name
          if (output.name.length) {
            result[output.name] = _convertNumberArray(
              result[output.name],
              format,
              depth
            );
          }
          // output will always have an index key
          result[i] = _convertNumberArray(result[i], format, depth);
        }
        //
      } else if (typeof result === "object") {
        // output has name
        if (output.name.length) {
          result[output.name] = _convertNumber(result[output.name], format);
        }

        // output will always have an index key
        result[i] = _convertNumber(result[i], format);
      } else {
        result = _convertNumber(result, format);
      }
    }
  });
  return result;
};

module.exports = {
  numbers: numbers
};


/***/ }),

/***/ 460550:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const TruffleError = __webpack_require__(673321);
const utils = __webpack_require__(913735);

const defaultGas = 90000;

class StatusError extends TruffleError {
  constructor(args, tx, receipt, reason) {
    let message;
    const gasLimit = args.gas || defaultGas;
    let reasonString = "";

    if (reason) reasonString = `Reason given: ${reason}.`;

    if (utils.bigNumberify(receipt.gasUsed).eq(utils.bigNumberify(gasLimit))) {
      message =
        "Transaction: " +
        tx +
        " exited with an error (status 0) after consuming all gas.\n" +
        "     Please check that the transaction:\n" +
        "     - satisfies all conditions set by Solidity `assert` statements.\n" +
        "     - has enough gas to execute the full transaction.\n" +
        "     - does not trigger an invalid opcode by other means (ex: accessing an array out of bounds).";
    } else {
      message =
        `Transaction: ${tx} exited with an error (status 0). ${reasonString}\n` +
        "     Please check that the transaction:\n" +
        "     - satisfies all conditions set by Solidity `require` statements.\n" +
        "     - does not trigger a Solidity `revert` statement.\n";
    }

    super(message);
    this.tx = tx;
    this.receipt = receipt;
    this.reason = reason;
  }
}

module.exports = StatusError;


/***/ }),

/***/ 150145:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const ENSJS = __webpack_require__(297442);
const { isAddress } = __webpack_require__(118269);

module.exports = {
  convertENSNames: async function({
    ensSettings,
    inputArgs,
    methodABI,
    inputParams,
    web3
  }) {
    const { registryAddress } = ensSettings;
    let args;
    if (inputArgs.length && methodABI) {
      args = await this.convertENSArgsNames(
        inputArgs,
        methodABI,
        web3,
        registryAddress
      );
    } else {
      args = inputArgs;
    }
    const params = await this.convertENSParamsNames(
      inputParams,
      web3,
      registryAddress
    );
    return { args, params };
  },

  getNewENSJS: function({ provider, registryAddress }) {
    return new ENSJS(provider, registryAddress);
  },

  resolveNameToAddress: function(name, ensjs) {
    return ensjs.resolver(name).addr();
  },

  convertENSArgsNames: function(inputArgs, methodABI, web3, registryAddress) {
    if (methodABI.inputs.length === 0) return inputArgs;
    const ensjs = this.getNewENSJS({
      provider: web3.currentProvider,
      registryAddress
    });

    const convertedNames = inputArgs.map((argument, index) => {
      if (index + 1 > methodABI.inputs.length) {
        return argument;
      } else if (methodABI.inputs[index].type === "address") {
        // Check all address arguments for ENS names
        const argIsAddress = isAddress(argument);
        if (argIsAddress) return argument;
        return this.resolveNameToAddress(argument, ensjs);
      } else {
        return argument;
      }
    });
    return Promise.all(convertedNames);
  },

  convertENSParamsNames: async function(params, web3, registryAddress) {
    if (params.from && !isAddress(params.from)) {
      const ensjs = this.getNewENSJS({
        provider: web3.currentProvider,
        registryAddress
      });
      const newFrom = await this.resolveNameToAddress(params.from, ensjs);
      return Object.assign({}, params, { from: newFrom });
    } else {
      return params;
    }
  }
};


/***/ }),

/***/ 913735:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(774685)("contract:utils");
const web3Utils = __webpack_require__(118269);
const { bigNumberify } = __webpack_require__(661895);
const abi = __webpack_require__(893338);
const BlockchainUtils = __webpack_require__(986317);
const reformat = __webpack_require__(190908);
const ens = __webpack_require__(150145);

const allowedTxParams = new Set([
  "from",
  "to",
  "gas",
  "gasPrice",
  "value",
  "data",
  "nonce",
  "privateFor",
  "overwrite"
]);

const Utils = {
  is_object(val) {
    return typeof val === "object" && !Array.isArray(val);
  },

  is_big_number(val) {
    if (typeof val !== "object") return false;

    //NOTE: For some reason, contrary to the docs,
    //web3Utils.isBigNumber returns true not only for
    //bignumber.js BigNumbers, but also for ethers BigNumbers,
    //even though these are totally different things.
    return web3Utils.isBN(val) || web3Utils.isBigNumber(val);
  },

  isTxParams(val) {
    if (!Utils.is_object(val)) return false;
    if (Utils.is_big_number(val)) return false;
    return Object.keys(val).some(fieldName => allowedTxParams.has(fieldName));
  },

  decodeLogs(_logs, isSingle) {
    const constructor = this;
    const logs = Utils.toTruffleLog(_logs, isSingle);

    return logs
      .map(log => {
        const logABI = constructor.events[log.topics[0]];

        if (logABI == null) return null;

        const copy = Utils.merge({}, log);

        copy.event = logABI.name;
        copy.topics = logABI.anonymous ? copy.topics : copy.topics.slice(1);

        if (copy.data === "0x") copy.data = "";

        let logArgs;
        try {
          logArgs = abi.decodeLog(logABI.inputs, copy.data, copy.topics);
          copy.args = reformat.numbers.call(
            constructor,
            logArgs,
            logABI.inputs
          );
        } catch (_) {
          return null;
        }

        delete copy.data;
        delete copy.topics;

        return copy;
      })
      .filter(log => log != null);
  },

  toTruffleLog(events, isSingle) {
    // Transform singletons (from event listeners) to the kind of
    // object we find on the receipt
    if (isSingle && typeof isSingle === "boolean") {
      const temp = [];
      temp.push(events);
      return temp.map(log => {
        log.data = log.raw.data;
        log.topics = log.raw.topics;
        return log;
      });
    }

    // Or reformat items in the existing array
    events.forEach(event => {
      if (event.raw) {
        event.data = event.raw.data;
        event.topics = event.raw.topics;
      }
    });

    return events;
  },

  merge() {
    const merged = {};
    const args = Array.prototype.slice.call(arguments);

    for (let i = 0; i < args.length; i++) {
      const object = args[i];
      const keys = Object.keys(object);
      for (let j = 0; j < keys.length; j++) {
        const key = keys[j];
        const value = object[key];
        merged[key] = value;
      }
    }

    return merged;
  },

  linkBytecode(bytecode, links) {
    Object.keys(links).forEach(library_name => {
      const library_address = links[library_name];
      const regex = new RegExp(`__${library_name}_+`, "g");

      bytecode = bytecode.replace(regex, library_address.replace("0x", ""));
    });

    return bytecode;
  },

  // Extracts optional tx params from a list of fn arguments
  getTxParams(methodABI, args) {
    const constructor = this;

    const expectedArgCount = methodABI ? methodABI.inputs.length : 0;

    let tx_params = {};
    const lastArg = args[args.length - 1];

    if (
      args.length === expectedArgCount + 1 &&
      Utils.isTxParams(lastArg)
    ) {
      tx_params = args.pop();
    }

    return Utils.merge(constructor.class_defaults, tx_params);
  },

  // Verifies that a contracts libraries have been linked correctly.
  // Throws on error
  checkLibraries() {
    const constructor = this;
    const regex = /__[^_]+_+/g;
    let unlinkedLibraries = constructor.binary.match(regex);

    if (unlinkedLibraries !== null) {
      unlinkedLibraries = unlinkedLibraries
        .map((
          name // Remove underscores
        ) => name.replace(/_/g, ""))
        .sort()
        .filter((name, index, arr) => {
          // Remove duplicates
          if (index + 1 >= arr.length) {
            return true;
          }

          return name !== arr[index + 1];
        })
        .join(", ");

      const error = `${
        constructor.contractName
      } contains unresolved libraries. You must deploy and link the following libraries before you can deploy a new version of ${
        constructor.contractName
      }: ${unlinkedLibraries}`;

      throw new Error(error);
    }
  },

  convertToEthersBN(original) {
    const converted = [];
    original.forEach(item => {
      // Recurse for arrays
      if (Array.isArray(item)) {
        converted.push(Utils.convertToEthersBN(item));

        // Convert Web3 BN / BigNumber
      } else if (Utils.is_big_number(item)) {
        //HACK: Since we can't rely on web3Utils.isBigNumber to tell
        //whether we have a bignumber.js BigNumber, we'll just check
        //whether it has the toFixed method
        const stringValue = item.toFixed
          ? item.toFixed() //prevents use of scientific notation
          : item.toString();
        const ethersBN = bigNumberify(stringValue);
        converted.push(ethersBN);
      } else {
        converted.push(item);
      }
    });
    return converted;
  },

  /**
   * Multiplies an ethers.js BigNumber and a number with decimal places using
   * integer math rather than using an arbitrary floating-point library like
   * `bignumber.js`.
   * @param  {BigNumber} bignum            an ethers.js BigNumber (use bigNumberify)
   * @param  {Number}    decimal           a number which has 0+ decimal places
   * @param  {Number}    [maxPrecision=5]  the max number of signficant figures
   *                                       `decimal` can have. (default: 5)
   * @return {BigNumber}                   floor(bignum * decimal)
   */
  multiplyBigNumberByDecimal(bignum, decimal, maxPrecision) {
    if (typeof maxPrecision === "undefined") {
      maxPrecision = 5;
    }

    const significantFigures = Math.min(
      decimal.toString().length - 1, // length less one because `.`
      maxPrecision
    );

    const denominator = bigNumberify(10).pow(significantFigures);
    const multiplier = Math.round(decimal * denominator);
    const numerator = bigNumberify(multiplier).mul(bignum);

    return numerator.div(denominator);
  },

  // checks if given contract instance has a set provider
  checkProvider({ currentProvider, contractName }) {
    if (!currentProvider)
      throw new Error(
        `${contractName} error: Please call setProvider() first before calling new().`
      );
  },

  // verifies current network has been assigned to contract instance
  checkNetworkArtifactMatch({ networks, network_id, contractName }) {
    if (networks[network_id] == null)
      throw new Error(
        `${contractName} has not been deployed to detected network (network/artifact mismatch)`
      );
  },

  // verifies contract instance has been deployed
  checkDeployment({ isDeployed, contractName, network_id }) {
    if (!isDeployed())
      throw new Error(
        `${contractName} has not been deployed to detected network (${network_id})`
      );
  },

  // checks if provided contract address has on-chain code
  checkCode(onChainCode, contractName, address) {
    if (!onChainCode || onChainCode.replace("0x", "").replace(/0/g, "") === "")
      throw new Error(
        `Cannot create instance of ${contractName}; no code at address ${address}`
      );
  },

  // parses known contract instance networks
  async parseKnownNetworks(
    { networks, currentProvider, setNetwork, network_id },
    gasLimit
  ) {
    if (!networks && Object.keys(networks).length === 0) {
      return false;
    }
    // go through all the networks that are listed as
    // blockchain uris and see if they match
    for (const network in networks) {
      if (network.startsWith("blockchain://")) {
        const networkMatches = await BlockchainUtils.matches(
          network,
          currentProvider
        );
        if (networkMatches) {
          setNetwork(network);
          return {
            id: network_id,
            blockLimit: gasLimit
          };
        }
      }
    }
    // no match found!
    return false;
  },

  // sets a contract instance network ID
  async setInstanceNetworkID(
    TruffleContractInstance,
    chainNetworkID,
    gasLimit
  ) {
    // if chainNetworkID already present as network configuration, use it
    if (TruffleContractInstance.hasNetwork(chainNetworkID)) {
      TruffleContractInstance.setNetwork(chainNetworkID);
      return {
        id: TruffleContractInstance.network_id,
        blockLimit: gasLimit
      };
    }
    // chainNetworkID not present,
    // parse all known networks
    const matchedNetwork = await Utils.parseKnownNetworks(
      TruffleContractInstance,
      gasLimit
    );
    if (matchedNetwork) return matchedNetwork;

    // network unknown, trust the provider and use given chainNetworkID
    TruffleContractInstance.setNetwork(chainNetworkID);
    return { id: TruffleContractInstance.network_id, blockLimit: gasLimit };
  }
};

Utils.ens = ens;
Utils.bigNumberify = bigNumberify;

module.exports = Utils;


/***/ }),

/***/ 996191:
/***/ ((module) => {

"use strict";
module.exports = {"i8":"4.3.15"};

/***/ }),

/***/ 876775:
/***/ ((module) => {

function webpackEmptyContext(req) {
	var e = new Error("Cannot find module '" + req + "'");
	e.code = 'MODULE_NOT_FOUND';
	throw e;
}
webpackEmptyContext.keys = () => ([]);
webpackEmptyContext.resolve = webpackEmptyContext;
webpackEmptyContext.id = 876775;
module.exports = webpackEmptyContext;

/***/ }),

/***/ 93293:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const OS = __webpack_require__(712087);
const debug = __webpack_require__(273687)("debug-utils");
const util = __webpack_require__(431669);
const Codec = __webpack_require__(20102);
const BN = __webpack_require__(213550);

const chromafi = __webpack_require__(910298);
const hljsDefineSolidity = __webpack_require__(225914);
hljsDefineSolidity(chromafi.hljs);
const chalk = __webpack_require__(732589);

const panicTable = {
  0x01: "Failed assertion",
  0x11: "Arithmetic overflow",
  0x12: "Division by zero",
  0x21: "Enum value out of bounds",
  0x22: "Malformed string",
  0x31: "Array underflow",
  0x32: "Index out of bounds",
  0x41: "Oversized array or out of memory",
  0x51: "Call to invalid function"
};

const verbosePanicTable = {
  0x01: "An assert() check was not satisfied.",
  0x11: "An arithmetic overflow occurred outside an unchecked { ... } block.",
  0x12: "A division by zero occurred.",
  0x21: "An integer was cast to an enum type that cannot hold it.",
  0x22: "There was an attempt to read an incorrectly-encoded string or bytestring.",
  0x31: "An empty array's pop() method was called.",
  0x32: "An array or bytestring was indexed or sliced with an out-of-bounds index.",
  0x41: "An oversized array was created, or the contract ran out of memory.",
  0x51: "An uninitialized internal function pointer was called."
};

const commandReference = {
  "o": "step over",
  "i": "step into",
  "u": "step out",
  "n": "step next",
  ";": "step instruction (include number to step multiple)",
  "p": "print instruction & state (`p [mem|cal|sto]*`; see docs for more)",
  "l": "print additional source context",
  "h": "print this help",
  "v": "print variables and values",
  ":": "evaluate expression - see `v`",
  "+": "add watch expression (`+:<expr>`)",
  "-": "remove watch expression (-:<expr>)",
  "?": "list existing watch expressions and breakpoints",
  "b": "add breakpoint (`b [[<source-file>:]<line-number>]`; see docs for more)",
  "B": "remove breakpoint (similar to adding, or `B all` to remove all)",
  "c": "continue until breakpoint",
  "q": "quit",
  "r": "reset",
  "t": "load new transaction",
  "T": "unload transaction",
  "s": "print stacktrace",
  "g": "turn on generated sources",
  "G": "turn off generated sources except via `;`"
};

const shortCommandReference = {
  "o": "step over",
  "i": "step into",
  "u": "step out",
  "n": "step next",
  ";": "step instruction",
  "p": "print state",
  "l": "print context",
  "h": "print help",
  "v": "print variables",
  ":": "evaluate",
  "+": "add watch",
  "-": "remove watch",
  "?": "list watches & breakpoints",
  "b": "add breakpoint",
  "B": "remove breakpoint",
  "c": "continue",
  "q": "quit",
  "r": "reset",
  "t": "load",
  "T": "unload",
  "s": "stacktrace",
  "g": "turn on generated sources",
  "G": "turn off generated sources"
};

const truffleColors = {
  mint: chalk.hex("#3FE0C5"),
  orange: chalk.hex("#E4A663"),
  pink: chalk.hex("#E911BD"),
  purple: chalk.hex("#8731E8"),
  green: chalk.hex("#00D717"),
  red: chalk.hex("#D60000"),
  yellow: chalk.hex("#F2E941"),
  blue: chalk.hex("#25A9E0"),
  comment: chalk.hsl(30, 20, 50),
  watermelon: chalk.hex("#E86591"),
  periwinkle: chalk.hex("#7F9DD1")
};

const DEFAULT_TAB_WIDTH = 8;

const trufflePalette = {
  /* base (chromafi special, not hljs) */
  "base": chalk,
  "lineNumbers": chalk,
  "trailingSpace": chalk,
  /* classes hljs-solidity actually uses */
  "keyword": truffleColors.mint,
  "number": truffleColors.red,
  "string": truffleColors.green,
  "params": truffleColors.pink,
  "builtIn": truffleColors.watermelon,
  "built_in": truffleColors.watermelon, //just to be sure
  "literal": truffleColors.watermelon,
  "function": truffleColors.orange,
  "title": truffleColors.orange,
  "class": truffleColors.orange,
  "comment": truffleColors.comment,
  "doctag": truffleColors.comment,
  /* classes it might soon use! */
  "meta": truffleColors.pink,
  "metaString": truffleColors.green,
  "meta-string": truffleColors.green, //similar
  /* classes it doesn't currently use but notionally could */
  "type": truffleColors.orange,
  "symbol": truffleColors.orange,
  "metaKeyword": truffleColors.mint,
  "meta-keyword": truffleColors.mint, //again, to be sure
  /* classes that don't make sense for Solidity */
  "regexp": chalk, //solidity does not have regexps
  "subst": chalk, //or string interpolation
  "name": chalk, //or s-expressions
  "builtInName": chalk, //or s-expressions, again
  "builtin-name": chalk, //just to be sure
  /* classes for config, markup, CSS, templates, diffs (not programming) */
  "section": chalk,
  "tag": chalk,
  "attr": chalk,
  "attribute": chalk,
  "variable": chalk,
  "bullet": chalk,
  "code": chalk,
  "emphasis": chalk,
  "strong": chalk,
  "formula": chalk,
  "link": chalk,
  "quote": chalk,
  "selectorAttr": chalk, //lotta redundancy follows
  "selector-attr": chalk,
  "selectorClass": chalk,
  "selector-class": chalk,
  "selectorId": chalk,
  "selector-id": chalk,
  "selectorPseudo": chalk,
  "selector-pseudo": chalk,
  "selectorTag": chalk,
  "selector-tag": chalk,
  "templateTag": chalk,
  "template-tag": chalk,
  "templateVariable": chalk,
  "template-variable": chalk,
  "addition": chalk,
  "deletion": chalk
};

var DebugUtils = {
  truffleColors, //make these externally available

  //panicCode may be either a number or a BN
  panicString: function (panicCode, verbose = false) {
    const unknownString = "Unknown panic";
    const verboseUnknownString = "A panic occurred of unrecognized type.";
    if (BN.isBN(panicCode)) {
      try {
        panicCode = panicCode.toNumber();
      } catch (_) {
        return verbose ? verboseUnknownString : unknownString;
      }
    }
    return verbose
      ? verbosePanicTable[panicCode] || verboseUnknownString
      : panicTable[panicCode] || unknownString;
  },

  //attempts to test whether a given compilation is a real compilation,
  //i.e., was compiled all at once.
  //if it is real, it will definitely pass this test, barring a Solidity bug.
  //(anyway worst case failing it just results in a recompilation)
  //if it isn't real, but passes this test anyway... well, I'm hoping it should
  //still be usable all the same!
  isUsableCompilation: function (compilation) {
    //check #1: is the source order reliable?
    if (compilation.unreliableSourceOrder) {
      debug("unreliable source order");
      return false;
    }

    //check #2: are (user) source indices consecutive?
    //(while nonconsecutivity should not be a problem by itself, this probably
    //indicates a name collision of a sort that will be fatal for other
    //reasons)
    //NOTE: oddly, empty spots in an array will cause array.includes(undefined)
    //to return true!  So I'm doing it this way even though it looks wrong
    //(since the real concern is empty spots, not undefined, yet this turns
    //this up anyhow)
    if (compilation.sources.includes(undefined)) {
      debug("nonconsecutive sources");
      return false;
    }

    const lowestInternalIndex = Math.min(
      ...compilation.contracts.map(contract => {
        //find first defined index
        let lowestConstructor = (contract.generatedSources || []).findIndex(
          x => x !== undefined
        );
        if (lowestConstructor === -1) {
          lowestConstructor = Infinity;
        }
        let lowestDeployed = (
          contract.deployedGeneratedSources || []
        ).findIndex(x => x !== undefined);
        if (lowestDeployed === -1) {
          lowestDeployed = Infinity;
        }
        return Math.min(lowestConstructor, lowestDeployed);
      })
    );
    if (lowestInternalIndex !== Infinity) {
      //Infinity would mean there were none
      if (lowestInternalIndex !== compilation.sources.length) {
        //if it's a usable compilation, these should be equal,
        //as length = 1 + last user source
        debug("gap before internal sources");
        return false;
      }
    }

    //check #4: are there any AST ID collisions?
    let astIds = new Set();

    let allIDsUnseenSoFar = node => {
      if (Array.isArray(node)) {
        return node.every(allIDsUnseenSoFar);
      } else if (node !== null && typeof node === "object") {
        if (node.id !== undefined) {
          if (astIds.has(node.id)) {
            debug("id occured twice: %o", node.id);
            return false;
          } else {
            astIds.add(node.id);
          }
        }
        return Object.values(node).every(allIDsUnseenSoFar);
      } else {
        return true;
      }
    };

    //now: walk each Solidity AST
    //(and don't bother checking generated sources as they're
    //never Solidity)
    debug("checking Solidity ASTs for collisions");
    return compilation.sources.every(source =>
      !source || source.language !== "Solidity" || allIDsUnseenSoFar(source.ast)
    );
  },

  formatStartMessage: function (withTransaction) {
    if (withTransaction) {
      return "Gathering information about your project and the transaction...";
    } else {
      return "Gathering information about your project...";
    }
  },

  formatTransactionStartMessage: function () {
    return "Gathering information about the transaction...";
  },

  formatCommandDescription: function (commandId) {
    return (
      truffleColors.mint(`(${commandId})`) + " " + commandReference[commandId]
    );
  },

  formatPrompt: function (network, txHash) {
    return txHash !== undefined
      ? `debug(${network}:${txHash.substring(0, 10)}...)> `
      : `debug(${network})> `;
  },

  formatAffectedInstances: function (instances) {
    var hasAllSource = true;

    var lines = Object.keys(instances).map(function (address) {
      var instance = instances[address];

      if (instance.contractName) {
        return " " + address + " - " + instance.contractName;
      }

      if (!instance.source) {
        hasAllSource = false;
      }

      return " " + address + "(UNKNOWN)";
    });

    if (lines.length === 0) {
      lines.push("No affected addresses found.");
    }

    if (!hasAllSource) {
      lines.push("");
      lines.push(
        `${chalk.bold(
          "Warning:"
        )} The source code for one or more contracts could not be found.`
      );
    }

    return lines.join(OS.EOL);
  },

  formatHelp: function (lastCommand = "n") {
    var prefix = [
      "Commands:",
      truffleColors.mint("(enter)") +
        " last command entered (" +
        shortCommandReference[lastCommand] +
        ")"
    ];

    var commandSections = [
      ["o", "i", "u", "n"],
      ["c"],
      [";"],
      ["g", "G"],
      ["p"],
      ["l", "s", "h"],
      ["q", "r", "t", "T"],
      ["b"],
      ["B"],
      ["+", "-"],
      ["?"],
      ["v", ":"]
    ].map(function (shortcuts) {
      return shortcuts.map(DebugUtils.formatCommandDescription).join(", ");
    });

    var suffix = [""];

    var lines = prefix.concat(commandSections).concat(suffix);

    return lines.join(OS.EOL);
  },

  tabsToSpaces: function (inputLine, tabLength = DEFAULT_TAB_WIDTH) {
    //note: I'm going to assume for these purposes that everything is
    //basically ASCII and I don't have to worry about astral planes or
    //grapheme clusters.  Sorry. :-/
    let line = "";
    let counter = 0;
    for (let i = 0; i < inputLine.length; i++) {
      if (inputLine[i] === "\t") {
        const remaining = tabLength - counter;
        line += " ".repeat(remaining);
        counter = 0;
      } else if (inputLine[i] === "\n") {
        line += "\n";
        counter = 0;
      } else if (inputLine[i] === "\r" && inputLine[i + 1] === "\n") {
        line += "\n";
        counter = 0;
        i++;
      } else {
        line += inputLine[i];
        counter++;
        if (counter === tabLength) {
          counter = 0;
        }
      }
    }
    return line;
  },

  formatLineNumberPrefix: function (line, number, cols) {
    const prefix = String(number).padStart(cols) + ": ";

    return prefix + line;
  },

  formatLinePointer: function (
    line,
    startCol,
    endCol,
    padding,
    tabLength = DEFAULT_TAB_WIDTH
  ) {
    const prefix = " ".repeat(padding + 2); //account for ": "

    let output = "";
    let counter = 0;
    for (let i = 0; i < line.length; i++) {
      let pointedAt = i >= startCol && i < endCol;

      let additional;
      if (line[i] === "\t") {
        const remaining = tabLength - counter;
        additional = " ".repeat(remaining);
        debug("advancing %d", remaining);
        counter = 0;
      } else {
        additional = " "; // just a space
        counter++;
        if (counter === tabLength) {
          counter = 0;
        }
      }

      if (pointedAt) {
        additional = additional.replace(/./g, "^");
      }

      output += additional;
    }

    return truffleColors.purple(prefix + output);
  },

  //NOTE: source and uncolorizedSource here have already
  //been split into lines here, they're not the raw text
  //ALSO: assuming here that colorized source has been detabbed
  //but that uncolorized source has not
  formatRangeLines: function (
    source,
    range,
    uncolorizedSource,
    contextBefore = 2,
    contextAfter = 0
  ) {
    // range is {
    //   start: { line, column },
    //   end: { line, column}
    // }
    //

    var startIndex = Math.max(range.start.line - contextBefore, 0);
    var endIndex = Math.min(range.start.line + contextAfter, source.length - 1);

    var prefixLength = (endIndex + 1 + "").length; //+1 to account for 0-index

    //note: beforeLines now includes the line itself
    var beforeLines = source
      .slice(startIndex, range.start.line + 1)
      .map((line, index) => {
        let number = startIndex + index + 1; // 1 to account for 0-index
        return DebugUtils.formatLineNumberPrefix(line, number, prefixLength);
      });
    var afterLines = source
      .slice(range.start.line + 1, endIndex + 1)
      .map((line, index) => {
        let number = range.start.line + 1 + index + 1; // 1 to account for 0-index
        return DebugUtils.formatLineNumberPrefix(line, number, prefixLength);
      });

    var pointerStart = range.start.column;
    var pointerEnd;

    let uncolorizedLine = uncolorizedSource[range.start.line];

    // range.end is undefined in some cases
    // null/undefined check to avoid exceptions
    if (range.end && range.start.line === range.end.line) {
      // start and end are same line: pointer ends at column
      pointerEnd = range.end.column;
    } else {
      pointerEnd = uncolorizedLine.length;
    }

    var allLines = beforeLines.concat(
      [
        DebugUtils.formatLinePointer(
          //the line-pointer formatter doesn't work right with colorized
          //lines, so we pass in the uncolored version
          uncolorizedLine,
          pointerStart,
          pointerEnd,
          prefixLength
        )
      ],
      afterLines
    );

    return allLines.join(OS.EOL);
  },

  formatBreakpointLocation: function (
    breakpoint,
    here,
    currentSourceId,
    sourceNames
  ) {
    let baseMessage;
    if (breakpoint.node !== undefined) {
      baseMessage = here
        ? `this point in line ${breakpoint.line + 1}`
        : `a point in line ${breakpoint.line + 1}`;
      //note we always add 1 to adjust for zero-indexing
    } else {
      baseMessage = `line ${breakpoint.line + 1}`;
    }
    if (breakpoint.sourceId !== currentSourceId) {
      const sourceName = sourceNames[breakpoint.sourceId];
      return baseMessage + ` in ${sourceName}`;
    } else {
      return baseMessage;
    }
  },

  formatInstruction: function (traceIndex, traceLength, instruction) {
    return (
      "(" +
      traceIndex +
      "/" +
      traceLength +
      ") " +
      truffleColors.mint(instruction.name + " " + (instruction.pushData || ""))
    );
  },

  formatPC: function (pc) {
    let hex = pc.toString(16);
    if (hex.length % 2 !== 0) {
      hex = "0" + hex; //ensure even length
    }
    return "  PC = " + pc.toString() + " = 0x" + hex;
  },

  formatStack: function (stack) {
    //stack here is an array of hex words (no "0x")
    var formatted = stack.map((item, index) => {
      item = truffleColors.orange(item);
      item = "  " + item;
      if (index === stack.length - 1) {
        item += " (top)";
      } else {
        item += ` (${stack.length - index - 1} from top)`;
      }

      return item;
    });

    if (stack.length === 0) {
      formatted.unshift("  No data on stack.");
    } else {
      formatted.unshift("Stack:");
    }

    return formatted.join(OS.EOL);
  },

  formatMemory: function (memory) {
    //note memory here is an array of hex words (no "0x"),
    //not a single long hex string

    //get longest prefix needed;
    //minimum of 2 so always show at least 2 hex digits
    let maxPrefixLength = Math.max(
      2,
      ((memory.length - 1) * Codec.Evm.Utils.WORD_SIZE).toString(16).length
    );
    if (maxPrefixLength % 2 !== 0) {
      maxPrefixLength++; //make sure to use even # of hex digits
    }

    let formatted = memory.map((word, index) => {
      let address = (index * Codec.Evm.Utils.WORD_SIZE)
        .toString(16)
        .padStart(maxPrefixLength, "0");
      return `  0x${address}:  ${truffleColors.pink(word)}`;
    });

    if (memory.length === 0) {
      formatted.unshift("  No data in memory.");
    } else {
      formatted.unshift("Memory:");
    }

    return formatted.join(OS.EOL);
  },

  formatStorage: function (storage) {
    //storage here is an object mapping hex words to hex words (no 0x)

    //first: sort the keys (slice to clone as sort is in-place)
    //note: we can use the default sort here; it will do the righ thing
    let slots = Object.keys(storage).slice().sort();

    let formatted = slots.map((slot, index) => {
      if (
        index === 0 ||
        !Codec.Conversion.toBN(slot).eq(
          Codec.Conversion.toBN(slots[index - 1]).addn(1)
        )
      ) {
        return `0x${slot}:\n` + `  ${truffleColors.blue(storage[slot])}`;
      } else {
        return `  ${truffleColors.blue(storage[slot])}`;
      }
    });

    if (slots.length === 0) {
      formatted.unshift("  No known relevant data found in storage.");
    } else {
      formatted.unshift("Storage (partial view):");
    }

    return formatted.join(OS.EOL);
  },

  formatCalldata: function (calldata) {
    //takes a Uint8Array
    let selector = calldata.slice(0, Codec.Evm.Utils.SELECTOR_SIZE);
    let words = [];
    for (
      let wordIndex = Codec.Evm.Utils.SELECTOR_SIZE;
      wordIndex < calldata.length;
      wordIndex += Codec.Evm.Utils.WORD_SIZE
    ) {
      words.push(
        calldata.slice(wordIndex, wordIndex + Codec.Evm.Utils.WORD_SIZE)
      );
    }
    let maxWordIndex =
      (words.length - 1) * Codec.Evm.Utils.WORD_SIZE +
      Codec.Evm.Utils.SELECTOR_SIZE;
    let maxPrefixLength = Math.max(2, maxWordIndex.toString(16).length);
    if (maxPrefixLength % 2 !== 0) {
      maxPrefixLength++;
    }
    let formattedSelector;
    if (selector.length > 0) {
      formattedSelector =
        "Calldata:\n" +
        `  0x${"00".padStart(maxPrefixLength, "0")}:  ` +
        truffleColors.pink(
          Codec.Conversion.toHexString(selector)
            .slice(2)
            .padStart(2 * Codec.Evm.Utils.WORD_SIZE, "  ")
        );
    } else {
      formattedSelector = "  No data in calldata.";
    }

    let formatted = words.map((word, index) => {
      let address = (
        index * Codec.Evm.Utils.WORD_SIZE +
        Codec.Evm.Utils.SELECTOR_SIZE
      )
        .toString(16)
        .padStart(maxPrefixLength, "0");
      let data = Codec.Conversion.toHexString(word)
        .slice(2)
        .padEnd(2 * Codec.Evm.Utils.WORD_SIZE);
      return `  0x${address}:  ${truffleColors.pink(data)}`;
    });

    formatted.unshift(formattedSelector);

    return formatted.join(OS.EOL);
  },

  formatValue: function (value, indent = 0, nativized = false) {
    let inspectOptions = {
      colors: true,
      depth: null,
      maxArrayLength: null,
      breakLength: 30
    };
    let valueToInspect = nativized
      ? value
      : new Codec.Format.Utils.Inspect.ResultInspector(value);
    return util
      .inspect(valueToInspect, inspectOptions)
      .split(/\r?\n/g)
      .map((line, i) => {
        // don't indent first line
        const padding = i > 0 ? Array(indent).join(" ") : "";
        return padding + line;
      })
      .join(OS.EOL);
  },

  formatStacktrace: function (stacktrace, indent = 2) {
    //get message or panic code from stacktrace
    const { message, panic } = stacktrace[0];
    //we want to print inner to outer, so first, let's
    //reverse
    stacktrace = stacktrace.slice().reverse(); //reverse is in-place so clone first
    let lines = stacktrace.map(
      ({ functionName, contractName, address, location, type }) => {
        let name;
        if (contractName && functionName) {
          name = `${contractName}.${functionName}`;
        } else if (contractName) {
          name = contractName;
        } else if (functionName) {
          name = functionName;
        } else {
          name = "unknown function";
        }
        let locationString;
        if (location) {
          let {
            source: { sourcePath },
            sourceRange: {
              lines: {
                start: { line, column }
              }
            }
          } = location;
          locationString = sourcePath
            ? `${sourcePath}:${line + 1}:${column + 1}` //add 1 to account for 0-indexing
            : "unknown location";
        } else {
          locationString = "unknown location";
        }
        let addressString =
          type === "external"
            ? address !== undefined
              ? ` [address ${address}]`
              : " [unknown address]"
            : "";
        return `at ${name}${addressString} (${locationString})`;
      }
    );
    let status = stacktrace[0].status;
    if (status != undefined) {
      let statusLine;
      if (message !== undefined) {
        statusLine = status
          ? `Error: Improper return (caused message: ${message})`
          : `Error: Revert (message: ${message})`;
      } else if (panic !== undefined) {
        statusLine = status
          ? `Panic: Improper return (caused ${DebugUtils.panicString(
              panic
            ).toLowerCase()} (code 0x${panic.toString(16)}))`
          : `Panic: ${DebugUtils.panicString(panic)} (code 0x${panic.toString(
              16
            )})`;
      } else {
        statusLine = status
          ? "Error: Improper return (may be an unexpected self-destruct)"
          : "Error: Revert or exceptional halt";
      }
      lines.unshift(statusLine);
    }
    let indented = lines.map((line, index) =>
      index === 0 ? line : " ".repeat(indent) + line
    );
    return indented.join(OS.EOL);
  },

  colorize: function (code, language = "Solidity") {
    const options = {
      lang: "solidity",
      colors: trufflePalette,
      //we want to turn off basically everything else, as we're
      //handling padding & numbering manually
      lineNumbers: false,
      stripIndent: false,
      codePad: 0,
      tabsToSpaces: false, //we handle this ourself and don't
      //want chromafi's padding
      lineEndPad: false
      //NOTE: you might think you should pass highlight: true,
      //but you'd be wrong!  I don't understand this either
    };
    switch (language) {
      case "Solidity":
        return chromafi(code, options);
      case "Yul":
        //HACK: stick the code in an assembly block since we don't
        //have a separate Yul language for HLJS at the moment,
        //colorize it there, then extract it after colorization
        const wrappedCode = "assembly {\n" + code + "\n}";
        const colorizedWrapped = chromafi(wrappedCode, options);
        const firstNewLine = colorizedWrapped.indexOf("\n");
        const lastNewLine = colorizedWrapped.lastIndexOf("\n");
        return colorizedWrapped.slice(firstNewLine + 1, lastNewLine);
      case "Vyper":
        options.lang = "python"; //HACK -- close enough for now!
        return chromafi(code, options);
      default:
        //don't highlight
        return code;
    }
  },

  //HACK
  cleanThis: function (variables, replacement) {
    return Object.assign(
      {},
      ...Object.entries(variables).map(([variable, value]) =>
        variable === "this" ? { [replacement]: value } : { [variable]: value }
      )
    );
  },

  /**
   * HACK warning!  This function modifies the debugger state
   * and should only be used in light mode, at startup, in a very specific way!
   *
   * let bugger = await Debugger.forTx(txHash, { lightMode: true, ... });
   * const sources = await getTransactionSourcesBeforeStarting(bugger);
   * await bugger.startFullMode();
   *
   * Don't go switching transactions after doing this, because there's no
   * way at the moment to switch back into light mode in order to re-run
   * this function.  You do *not* want to run this in full mode.
   */
  getTransactionSourcesBeforeStarting: async function (bugger) {
    await bugger.reset();
    let sources = {};
    const { controller } = bugger.selectors;
    while (!bugger.view(controller.current.trace.finished)) {
      const source = bugger.view(controller.current.location.source);
      const { compilationId, id, internal } = source;
      //stepInto should skip internal sources, but there still might be
      //one at the end
      if (!internal && compilationId !== undefined && id !== undefined) {
        sources[compilationId] = {
          ...sources[compilationId],
          [id]: source
        };
      }
      await bugger.stepInto();
    }
    await bugger.reset();
    //flatten sources before returning
    return [].concat(...Object.values(sources).map(Object.values));
  }
};

module.exports = DebugUtils;


/***/ }),

/***/ 595532:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ContractInstanceDecoder = exports.ContractDecoder = exports.WireDecoder = void 0;
const debug_1 = __importDefault(__webpack_require__(968082));
const debug = debug_1.default("decoder:decoders");
const Abi = __importStar(__webpack_require__(207651));
const Codec = __importStar(__webpack_require__(20102));
const codec_1 = __webpack_require__(20102);
const Utils = __importStar(__webpack_require__(379550));
const web3_1 = __importDefault(__webpack_require__(503283));
const bn_js_1 = __importDefault(__webpack_require__(213550));
const errors_1 = __webpack_require__(613552);
//sorry for the untyped imports, but...
const { Shims } = __webpack_require__(529833);
const SourceMapUtils = __webpack_require__(832731);
/**
 * The WireDecoder class.  Decodes transactions and logs.  See below for a method listing.
 * @category Decoder
 */
class WireDecoder {
    /**
     * @protected
     */
    constructor(compilations, provider) {
        this.contexts = {}; //all contexts
        this.deployedContexts = {};
        this.contractsAndContexts = [];
        this.codeCache = {};
        this.web3 = new web3_1.default(provider);
        this.compilations = compilations;
        for (const compilation of this.compilations) {
            for (const contract of compilation.contracts) {
                const node = codec_1.Compilations.Utils.getContractNode(contract, compilation);
                let deployedContext = undefined;
                let constructorContext = undefined;
                const deployedBytecode = Shims.NewToLegacy.forBytecode(contract.deployedBytecode);
                const bytecode = Shims.NewToLegacy.forBytecode(contract.bytecode);
                if (deployedBytecode && deployedBytecode !== "0x") {
                    deployedContext = Utils.makeContext(contract, node, compilation);
                    this.contexts[deployedContext.context] = deployedContext;
                    //note that we don't set up deployedContexts until after normalization!
                }
                if (bytecode && bytecode !== "0x") {
                    constructorContext = Utils.makeContext(contract, node, compilation, true);
                    this.contexts[constructorContext.context] = constructorContext;
                }
                this.contractsAndContexts.push({
                    contract,
                    node,
                    deployedContext,
                    constructorContext,
                    compilationId: compilation.id
                });
            }
        }
        debug("known contexts: %o", Object.keys(this.contexts));
        this.contexts = codec_1.Contexts.Utils.normalizeContexts(this.contexts);
        this.deployedContexts = Object.assign({}, ...Object.values(this.contexts).map(context => !context.isConstructor ? { [context.context]: context } : {}));
        for (const contractAndContexts of this.contractsAndContexts) {
            //change everything to normalized version
            if (contractAndContexts.deployedContext) {
                contractAndContexts.deployedContext = this.contexts[contractAndContexts.deployedContext.context]; //get normalized version
            }
            if (contractAndContexts.constructorContext) {
                contractAndContexts.constructorContext = this.contexts[contractAndContexts.constructorContext.context]; //get normalized version
            }
        }
        ({
            definitions: this.referenceDeclarations,
            types: this.userDefinedTypes
        } = this.collectUserDefinedTypes());
        const allocationInfo = this.contractsAndContexts.map(({ contract: { abi, compiler, immutableReferences }, compilationId, node, deployedContext, constructorContext }) => ({
            abi: Abi.normalize(abi),
            compilationId,
            compiler,
            contractNode: node,
            deployedContext,
            constructorContext,
            immutableReferences
        }));
        this.allocations = {};
        this.allocations.abi = codec_1.AbiData.Allocate.getAbiAllocations(this.userDefinedTypes);
        this.allocations.storage = codec_1.Storage.Allocate.getStorageAllocations(this.userDefinedTypes); //not used by wire decoder itself, but used by contract decoder
        this.allocations.calldata = codec_1.AbiData.Allocate.getCalldataAllocations(allocationInfo, this.referenceDeclarations, this.userDefinedTypes, this.allocations.abi);
        this.allocations.event = codec_1.AbiData.Allocate.getEventAllocations(allocationInfo, this.referenceDeclarations, this.userDefinedTypes, this.allocations.abi);
        this.allocations.state = codec_1.Storage.Allocate.getStateAllocations(allocationInfo, this.referenceDeclarations, this.userDefinedTypes, this.allocations.storage);
        debug("done with allocation");
    }
    collectUserDefinedTypes() {
        let references = {};
        let types = {};
        for (const compilation of this.compilations) {
            references[compilation.id] = {};
            for (const source of compilation.sources) {
                if (!source) {
                    continue; //remember, sources could be empty if shimmed!
                }
                const { ast, compiler, language } = source;
                if (language === "Solidity" && ast) {
                    //don't check Yul or Vyper sources!
                    for (const node of ast.nodes) {
                        if (node.nodeType === "StructDefinition" ||
                            node.nodeType === "EnumDefinition" ||
                            node.nodeType === "ContractDefinition") {
                            references[compilation.id][node.id] = node;
                            //we don't have all the references yet, but we actually don't need them :)
                            const dataType = codec_1.Ast.Import.definitionToStoredType(node, compilation.id, compiler, references[compilation.id]);
                            types[dataType.id] = dataType;
                        }
                        if (node.nodeType === "ContractDefinition") {
                            for (const subNode of node.nodes) {
                                if (subNode.nodeType === "StructDefinition" ||
                                    subNode.nodeType === "EnumDefinition") {
                                    references[compilation.id][subNode.id] = subNode;
                                    //we don't have all the references yet, but we only need the
                                    //reference to the defining contract, which we just added above!
                                    const dataType = codec_1.Ast.Import.definitionToStoredType(subNode, compilation.id, compiler, references[compilation.id]);
                                    types[dataType.id] = dataType;
                                }
                            }
                        }
                    }
                }
            }
        }
        return { definitions: references, types };
    }
    /**
     * @protected
     */
    getCode(address, block) {
        return __awaiter(this, void 0, void 0, function* () {
            //if pending, ignore the cache
            if (block === "pending") {
                return codec_1.Conversion.toBytes(yield this.web3.eth.getCode(address, block));
            }
            //otherwise, start by setting up any preliminary layers as needed
            if (this.codeCache[block] === undefined) {
                this.codeCache[block] = {};
            }
            //now, if we have it cached, just return it
            if (this.codeCache[block][address] !== undefined) {
                return this.codeCache[block][address];
            }
            //otherwise, get it, cache it, and return it
            let code = codec_1.Conversion.toBytes(yield this.web3.eth.getCode(address, block));
            this.codeCache[block][address] = code;
            return code;
        });
    }
    /**
     * @protected
     */
    regularizeBlock(block) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof block === "number" || block === "pending") {
                return block;
            }
            if (block === null) {
                return "pending";
            }
            return (yield this.web3.eth.getBlock(block)).number;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Takes a [[Transaction]] object and decodes it.  The result is a
     * [[CalldataDecoding]]; see the documentation on that interface for more.
     *
     * Note that decoding of transactions sent to libraries is presently not
     * supported and may have unreliable results.  Limited support for this is
     * planned for future versions.
     * @param transaction The transaction to be decoded.
     */
    decodeTransaction(transaction) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.decodeTransactionWithAdditionalContexts(transaction);
        });
    }
    /**
     * @protected
     */
    decodeTransactionWithAdditionalContexts(transaction, additionalContexts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const block = transaction.blockNumber;
            const blockNumber = yield this.regularizeBlock(block);
            const isConstructor = transaction.to === null;
            const context = yield this.getContextByAddress(transaction.to, blockNumber, transaction.input, additionalContexts);
            const data = codec_1.Conversion.toBytes(transaction.input);
            const info = {
                state: {
                    storage: {},
                    calldata: data
                },
                userDefinedTypes: this.userDefinedTypes,
                allocations: this.allocations,
                contexts: Object.assign(Object.assign({}, this.deployedContexts), additionalContexts),
                currentContext: context
            };
            const decoder = codec_1.decodeCalldata(info, isConstructor);
            let result = decoder.next();
            while (result.done === false) {
                let request = result.value;
                let response;
                switch (request.type) {
                    case "code":
                        response = yield this.getCode(request.address, blockNumber);
                        break;
                    //not writing a storage case as it shouldn't occur here!
                }
                result = decoder.next(response);
            }
            //at this point, result.value holds the final value
            return result.value;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Takes a [[Log]] object and decodes it.  Logs can be ambiguous, so this so
     * this function returns an array of [[LogDecoding|LogDecodings]].
     *
     * Note that logs are decoded in strict mode, so (with one exception) none of the decodings should
     * contain errors; if a decoding would contain an error, instead it is simply excluded from the
     * list of possible decodings.  The one exception to this is that indexed parameters of reference
     * type cannot meaningfully be decoded, so those will decode to an error.
     *
     * If there are multiple possible decodings, they will always be listed in the following order:
     *
     * 1. Non-anonymous events coming from the contract itself (these will moreover be ordered
     *   from most derived to most base)
     * 2. Non-anonymous events coming from libraries
     * 3. Anonymous events coming from the contract itself (again, ordered from most derived
     *   to most base)
     * 4. Anonymous events coming from libraries
     *
     * You can check the kind and class.contractKind fields to distinguish between these.
     *
     * If no possible decodings are found, the returned array of decodings will be empty.
     *
     * Note that different decodings may use different decoding modes.
     *
     * Changing `options.extras = "on"` or `options.extras = "necessary"` will change the
     * above behavior; see the documentation on [[ExtrasAllowed]] for more.
     *
     * @param log The log to be decoded.
     * @param options Options for controlling decoding.
     */
    decodeLog(log, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.decodeLogWithAdditionalOptions(log, options);
        });
    }
    /**
     * @protected
     */
    decodeLogWithAdditionalOptions(log, options = {}, additionalContexts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const block = log.blockNumber;
            const blockNumber = yield this.regularizeBlock(block);
            const data = codec_1.Conversion.toBytes(log.data);
            const topics = log.topics.map(codec_1.Conversion.toBytes);
            const info = {
                state: {
                    storage: {},
                    eventdata: data,
                    eventtopics: topics
                },
                userDefinedTypes: this.userDefinedTypes,
                allocations: this.allocations,
                contexts: Object.assign(Object.assign({}, this.deployedContexts), additionalContexts)
            };
            const decoder = codec_1.decodeEvent(info, log.address, options);
            let result = decoder.next();
            while (result.done === false) {
                let request = result.value;
                let response;
                switch (request.type) {
                    case "code":
                        response = yield this.getCode(request.address, blockNumber);
                        break;
                    //not writing a storage case as it shouldn't occur here!
                }
                result = decoder.next(response);
            }
            //at this point, result.value holds the final value
            return result.value;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Gets all events meeting certain conditions and decodes them.
     * This function is fairly rudimentary at the moment but more functionality
     * will be added in the future.
     * @param options Used to determine what events to fetch and how to decode
     *   them; see the documentation on the [[EventOptions]] type for more.
     * @return An array of [[DecodedLog|DecodedLogs]].
     *   These consist of a log together with its possible decodings; see that
     *   type for more info.  And see [[decodeLog]] for more info on how log
     *   decoding works in general.
     * @example `events({name: "TestEvent"})` -- get events named "TestEvent"
     *   from the most recent block
     */
    events(options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.eventsWithAdditionalContexts(options);
        });
    }
    /**
     * @protected
     */
    eventsWithAdditionalContexts(options = {}, additionalContexts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            let { address, name, fromBlock, toBlock } = options;
            if (fromBlock === undefined) {
                fromBlock = "latest";
            }
            if (toBlock === undefined) {
                toBlock = "latest";
            }
            const fromBlockNumber = yield this.regularizeBlock(fromBlock);
            const toBlockNumber = yield this.regularizeBlock(toBlock);
            const logs = yield this.web3.eth.getPastLogs({
                address,
                fromBlock: fromBlockNumber,
                toBlock: toBlockNumber
            });
            let events = yield Promise.all(logs.map((log) => __awaiter(this, void 0, void 0, function* () {
                return (Object.assign(Object.assign({}, log), { decodings: yield this.decodeLogWithAdditionalOptions(log, options, additionalContexts) }));
            })));
            debug("events: %o", events);
            //if a target name was specified, we'll restrict to events that decoded
            //to something with that name.  (note that only decodings with that name
            //will have been returned from decodeLogs in the first place)
            if (name !== undefined) {
                events = events.filter(event => event.decodings.length > 0);
            }
            return events;
        });
    }
    /**
     * Takes a [[CalldataDecoding]], which may have been produced in full mode or ABI mode,
     * and converts it to its ABI mode equivalent.  See the README for more information.
     *
     * Please only use on decodings produced by this same decoder instance; use
     * on decodings produced by other instances may not work consistently.
     * @param decoding The decoding to abify
     */
    abifyCalldataDecoding(decoding) {
        return Codec.abifyCalldataDecoding(decoding, this.userDefinedTypes);
    }
    /**
     * Takes a [[LogDecoding]], which may have been produced in full mode or ABI mode,
     * and converts it to its ABI mode equivalent.  See the README for more information.
     *
     * Please only use on decodings produced by this same decoder instance; use
     * on decodings produced by other instances may not work consistently.
     * @param decoding The decoding to abify
     */
    abifyLogDecoding(decoding) {
        return Codec.abifyLogDecoding(decoding, this.userDefinedTypes);
    }
    /**
     * Takes a [[ReturndataDecoding]], which may have been produced in full mode
     * or ABI mode, and converts it to its ABI mode equivalent.  See the README
     * for more information.
     *
     * Please only use on decodings produced by this same decoder instance; use
     * on decodings produced by other instances may not work consistently.
     * @param decoding The decoding to abify
     */
    abifyReturndataDecoding(decoding) {
        return Codec.abifyReturndataDecoding(decoding, this.userDefinedTypes);
    }
    //normally, this function gets the code of the given address at the given block,
    //and checks this against the known contexts to determine the contract type
    //however, if this fails and constructorBinary is passed in, it will then also
    //attempt to determine it from that
    getContextByAddress(address, block, constructorBinary, additionalContexts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            let code;
            if (address !== null) {
                code = codec_1.Conversion.toHexString(yield this.getCode(address, block));
            }
            else if (constructorBinary) {
                code = constructorBinary;
            }
            //if neither of these hold... we have a problem
            let contexts = Object.assign(Object.assign({}, this.contexts), additionalContexts);
            return codec_1.Contexts.Utils.findContext(contexts, code);
        });
    }
    //finally: the spawners!
    /**
     * **This method is asynchronous.**
     *
     * Constructs a contract decoder for a given contract artifact.
     * @param artifact The artifact for the contract.
     *
     *   A contract constructor object may be substituted for the artifact, so if
     *   you're not sure which you're dealing with, it's OK.
     *
     *   Note: The artifact must be for a contract that the decoder knows about;
     *   otherwise you will have problems.
     */
    forArtifact(artifact) {
        return __awaiter(this, void 0, void 0, function* () {
            const deployedBytecode = Shims.NewToLegacy.forBytecode(artifact.deployedBytecode);
            const bytecode = Shims.NewToLegacy.forBytecode(artifact.bytecode);
            const { compilation, contract } = this.compilations.reduce((foundSoFar, compilation) => {
                if (foundSoFar) {
                    return foundSoFar;
                }
                const contractFound = compilation.contracts.find(contract => {
                    if (bytecode) {
                        return (Shims.NewToLegacy.forBytecode(contract.bytecode) === bytecode &&
                            contract.contractName ===
                                (artifact.contractName || artifact.contract_name));
                    }
                    else if (deployedBytecode) {
                        //I'll just go by one of bytecode or deployedBytecode;
                        //no real need to check both
                        return (Shims.NewToLegacy.forBytecode(contract.deployedBytecode) ===
                            deployedBytecode &&
                            contract.contractName ===
                                (artifact.contractName || artifact.contract_name));
                    }
                    else {
                        //WARNING: better hope we don't end up here!
                        return (contract.contractName ===
                            (artifact.contractName || artifact.contract_name));
                    }
                });
                if (contractFound) {
                    return { compilation, contract: contractFound };
                }
                else {
                    return undefined;
                }
            }, undefined);
            if (contract === undefined) {
                throw new errors_1.ContractNotFoundError(artifact.contractName, bytecode, deployedBytecode, undefined);
            }
            let contractDecoder = new ContractDecoder(contract, compilation, this, artifact);
            yield contractDecoder.init();
            return contractDecoder;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Constructs a contract instance decoder for a given instance of a contract in this
     * project.
     * @param artifact The artifact for the contract.
     *
     *   A contract constructor object may be substituted for the artifact, so if
     *   you're not sure which you're dealing with, it's OK.
     *
     *   Note: The artifact must be for a contract that the decoder knows about;
     *   otherwise you will have problems.
     * @param address The address of the contract instance to decode.  If left out, it will be autodetected.
     *   If an invalid address is provided, this method will throw an exception.
     */
    forInstance(artifact, address) {
        return __awaiter(this, void 0, void 0, function* () {
            let contractDecoder = yield this.forArtifact(artifact);
            return yield contractDecoder.forInstance(address);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Constructs a contract instance decoder for a given instance of a contract in this
     * project.  Unlike [[forInstance]], this method doesn't require an artifact; it
     * will automatically detect the class of the given contract.  If it's not in
     * the project, or the decoder can't identify it, you'll get an exception.
     * @param address The address of the contract instance to decode.
     *   If an invalid address is provided, this method will throw an exception.
     * @param block You can include this argument to specify that this should be
     *   based on the addresses content's at a specific block (if say the contract
     *   has since self-destructed).
     */
    forAddress(address, block = "latest") {
        return __awaiter(this, void 0, void 0, function* () {
            if (!web3_1.default.utils.isAddress(address)) {
                throw new errors_1.InvalidAddressError(address);
            }
            address = web3_1.default.utils.toChecksumAddress(address);
            const blockNumber = yield this.regularizeBlock(block);
            const deployedBytecode = codec_1.Conversion.toHexString(yield this.getCode(address, blockNumber));
            const contractAndContexts = this.contractsAndContexts.find(({ deployedContext }) => deployedContext &&
                codec_1.Contexts.Utils.matchContext(deployedContext, deployedBytecode));
            if (!contractAndContexts) {
                throw new errors_1.ContractNotFoundError(undefined, undefined, deployedBytecode, address);
            }
            const { contract, compilationId } = contractAndContexts;
            const compilation = this.compilations.find(compilation => compilation.id === compilationId);
            let contractDecoder = new ContractDecoder(contract, compilation, this); //no artifact
            //(artifact is only used for address autodetection, and here we're supplying the
            //address, so this won't cause any problems)
            yield contractDecoder.init();
            return yield contractDecoder.forInstance(address);
        });
    }
    //the following functions are intended for internal use only
    /**
     * @protected
     */
    getReferenceDeclarations() {
        return this.referenceDeclarations;
    }
    /**
     * @protected
     */
    getUserDefinedTypes() {
        return this.userDefinedTypes;
    }
    /**
     * @protected
     */
    getAllocations() {
        return {
            abi: this.allocations.abi,
            storage: this.allocations.storage,
            state: this.allocations.state,
            calldata: this.allocations.calldata
        };
    }
    /**
     * @protected
     */
    getWeb3() {
        return this.web3;
    }
    /**
     * @protected
     */
    getDeployedContexts() {
        return this.deployedContexts;
    }
}
exports.WireDecoder = WireDecoder;
/**
 * The ContractDecoder class.  Spawns the [[ContractInstanceDecoder]] class.
 * Also, decodes transactions and logs.  See below for a method listing.
 * @category Decoder
 */
class ContractDecoder {
    /**
     * @protected
     */
    constructor(contract, compilation, wireDecoder, artifact) {
        this.artifact = artifact; //may be undefined; only used for address autodetection in instance decoder
        this.contract = contract;
        this.compilation = compilation;
        this.wireDecoder = wireDecoder;
        this.web3 = wireDecoder.getWeb3();
        this.contexts = wireDecoder.getDeployedContexts();
        this.userDefinedTypes = this.wireDecoder.getUserDefinedTypes();
        this.contractNode = codec_1.Compilations.Utils.getContractNode(this.contract, this.compilation);
        this.allocations = this.wireDecoder.getAllocations();
        //note: ordinarily this.contract.deployedBytecode should equal artifact.deployedBytecode
        //at this point, so it may seem strange that I'm using this longer version (but not
        //doing anything to handle the case we're there not).  This is basically because I don't
        //think such error handling is really necessary right now, but this way at least it won't
        //crash.
        if (this.contract.deployedBytecode &&
            this.contract.deployedBytecode !== "0x") {
            const unnormalizedContext = Utils.makeContext(this.contract, this.contractNode, this.compilation);
            this.contextHash = unnormalizedContext.context;
            //we now throw away the unnormalized context, instead fetching the correct one from
            //this.contexts (which is normalized) via the context getter below
        }
        else {
            //if there's no bytecode, allocate output data in ABI mode anyway
            const referenceDeclarations = this.wireDecoder.getReferenceDeclarations();
            const compiler = this.compilation.compiler || this.contract.compiler;
            this.noBytecodeAllocations = Object.values(codec_1.AbiData.Allocate.getCalldataAllocations([
                {
                    abi: Abi.normalize(this.contract.abi),
                    compilationId: this.compilation.id,
                    compiler,
                    contractNode: this.contractNode,
                    deployedContext: Utils.makeContext(Object.assign(Object.assign({}, this.contract), { deployedBytecode: "0x" //only time this should ever appear in a context!
                     }), this.contractNode, this.compilation)
                }
            ], referenceDeclarations, this.userDefinedTypes, this.allocations.abi).functionAllocations)[0];
        }
        if (this.contractNode) {
            //note: there used to be code here to do state allocations for the contract,
            //but now the wire decoder does this all up-front
            //(I could change this back if for some reason performance is an issue,
            //but this way is simpler TBH)
            //NOTE: does this change make this intermediate class essentially pointless?
            //Yes.  But not going to get rid of it now!
            if (this.allocations.state[this.compilation.id] &&
                this.allocations.state[this.compilation.id][this.contractNode.id]) {
                this.stateVariableReferences = this.allocations.state[this.compilation.id][this.contractNode.id].members;
            }
            //if it doesn't exist, we will leave it undefined, and then throw an exception when
            //we attempt to decode
        }
    }
    /**
     * @protected
     */
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            this.contractNetwork = (yield this.web3.eth.net.getId()).toString();
        });
    }
    get context() {
        return this.contexts[this.contextHash];
    }
    /**
     * **This method is asynchronous.**
     *
     * Decodes the return value of a call.  Return values can be ambiguous, so this so
     * this function returns an array of [[ReturndataDecoding|ReturndataDecodings]].
     *
     * Note that return values are decoded in strict mode, so none of the decodings should
     * contain errors; if a decoding would contain an error, instead it is simply excluded from the
     * list of possible decodings.
     *
     * If there are multiple possible decodings, they will always be listed in the following order:
     * 1. The decoded return value from a successful call.
     * 2. The decoded revert message from a call that reverted with a message.
     * 3. A decoding indicating that the call reverted with no message.
     * 4. A decoding indicating that the call self-destructed.
     *
     * You can check the kind and field to distinguish between these.
     *
     * If no possible decodings are found, the returned array of decodings will be empty.
     *
     * Note that different decodings may use different decoding modes.
     *
     * Decoding creation calls with this method is not supported.  If you simply
     * want to decode a revert message from an arbitrary call that you know
     * failed, you may also want to see the [[decodeRevert]] function in
     * `@truffle/codec`.
     *
     * @param abi The abi entry for the function call whose return value is being decoded.
     * @param data The data to be decoded, as a hex string (beginning with "0x").
     * @param options Additional options, such as the block the call occurred in.
     *   See [[ReturnOptions]] for more information.
     */
    decodeReturnValue(abi, data, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.decodeReturnValueWithAdditionalContexts(abi, data, options);
        });
    }
    /**
     * @protected
     */
    decodeReturnValueWithAdditionalContexts(abi, data, options = {}, additionalContexts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            abi = Abi.normalizeEntry(abi); //just to be absolutely certain!
            const block = options.block !== undefined ? options.block : "latest";
            const blockNumber = yield this.regularizeBlock(block);
            const status = options.status; //true, false, or undefined
            const selector = codec_1.AbiData.Utils.abiSelector(abi);
            let allocation;
            if (this.contextHash !== undefined) {
                allocation = this.allocations.calldata.functionAllocations[this.contextHash][selector].output;
            }
            else {
                allocation = this.noBytecodeAllocations[selector].output;
            }
            const bytes = codec_1.Conversion.toBytes(data);
            const info = {
                state: {
                    storage: {},
                    returndata: bytes
                },
                userDefinedTypes: this.userDefinedTypes,
                allocations: this.allocations,
                contexts: Object.assign(Object.assign({}, this.contexts), additionalContexts)
            };
            const decoder = codec_1.decodeReturndata(info, allocation, status);
            let result = decoder.next();
            while (result.done === false) {
                let request = result.value;
                let response;
                switch (request.type) {
                    case "code":
                        response = yield this.getCode(request.address, blockNumber);
                        break;
                    //not writing a storage case as it shouldn't occur here!
                }
                result = decoder.next(response);
            }
            //at this point, result.value holds the final value
            return result.value;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Constructs a contract instance decoder for a given instance of this contract.
     * @param address The address of the contract instance decode.  If left out, it will be autodetected.
     *   If an invalid address is provided, this method will throw an exception.
     */
    forInstance(address) {
        return __awaiter(this, void 0, void 0, function* () {
            let instanceDecoder = new ContractInstanceDecoder(this, address);
            yield instanceDecoder.init();
            return instanceDecoder;
        });
    }
    getCode(address, block) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.getCode(address, block);
        });
    }
    regularizeBlock(block) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.regularizeBlock(block);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * See [[WireDecoder.decodeTransaction]].
     * @param transaction The transaction to be decoded.
     */
    decodeTransaction(transaction) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.decodeTransaction(transaction);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * See [[WireDecoder.decodeLog]].
     * @param log The log to be decoded.
     */
    decodeLog(log, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.decodeLog(log, options);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * See [[WireDecoder.events]].
     * @param options Used to determine what events to fetch and how to decode them;
     *   see the documentation on the EventOptions type for more.
     */
    events(options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.events(options);
        });
    }
    /**
     * See [[WireDecoder.abifyCalldataDecoding]].
     */
    abifyCalldataDecoding(decoding) {
        return this.wireDecoder.abifyCalldataDecoding(decoding);
    }
    /**
     * See [[WireDecoder.abifyLogDecoding]].
     */
    abifyLogDecoding(decoding) {
        return this.wireDecoder.abifyLogDecoding(decoding);
    }
    /**
     * See [[WireDecoder.abifyReturndataDecoding]].
     */
    abifyReturndataDecoding(decoding) {
        return this.wireDecoder.abifyReturndataDecoding(decoding);
    }
    //the following functions are for internal use
    /**
     * @protected
     */
    getAllocations() {
        return this.allocations;
    }
    /**
     * @protected
     */
    getStateVariableReferences() {
        return this.stateVariableReferences;
    }
    /**
     * @protected
     */
    getWireDecoder() {
        return this.wireDecoder;
    }
    /**
     * @protected
     */
    getContractInfo() {
        return {
            compilation: this.compilation,
            contract: this.contract,
            artifact: this.artifact,
            contractNode: this.contractNode,
            contractNetwork: this.contractNetwork,
            contextHash: this.contextHash
        };
    }
}
exports.ContractDecoder = ContractDecoder;
/**
 * The ContractInstanceDecoder class.  Decodes storage for a specified
 * instance.  Also, decodes transactions and logs.  See below for a method
 * listing.
 *
 * Note that when using this class to decode transactions, logs, and return
 * values, it does have one advantage over using the WireDecoder or
 * ContractDecoder.  If the artifact for the class does not have a
 * deployedBytecode field, the WireDecoder (and therefore also the
 * ContractDecoder) will not be able to tell that this instance is of that
 * class, and so will fail to decode transactions sent to it or logs
 * originating from it, and will fall back to ABI mode when decoding return
 * values received from it.  However, the ContractInstanceDecoder has that
 * information and will make use of it, making it possible for it to decode
 * transactions sent to this instance, or logs originating from it, or decode
 * return values received from it in full mode, even if the deployedBytecode
 * field is misssing.
 * @category Decoder
 */
class ContractInstanceDecoder {
    /**
     * @protected
     */
    constructor(contractDecoder, address) {
        this.contexts = {}; //deployed contexts only
        this.additionalContexts = {}; //for passing to wire decoder when contract has no deployedBytecode
        this.mappingKeys = [];
        this.storageCache = {};
        this.contractDecoder = contractDecoder;
        this.wireDecoder = this.contractDecoder.getWireDecoder();
        this.web3 = this.wireDecoder.getWeb3();
        if (address !== undefined) {
            if (!web3_1.default.utils.isAddress(address)) {
                throw new errors_1.InvalidAddressError(address);
            }
            this.contractAddress = web3_1.default.utils.toChecksumAddress(address);
        }
        this.referenceDeclarations = this.wireDecoder.getReferenceDeclarations();
        this.userDefinedTypes = this.wireDecoder.getUserDefinedTypes();
        this.contexts = this.wireDecoder.getDeployedContexts();
        let artifact;
        ({
            compilation: this.compilation,
            contract: this.contract,
            artifact,
            contractNode: this.contractNode,
            contractNetwork: this.contractNetwork,
            contextHash: this.contextHash
        } = this.contractDecoder.getContractInfo());
        this.allocations = this.contractDecoder.getAllocations();
        this.stateVariableReferences = this.contractDecoder.getStateVariableReferences();
        //note that if we're in the null artifact case, this.contractAddress should have
        //been set by now, so we shouldn't end up here
        if (this.contractAddress === undefined) {
            this.contractAddress = artifact.networks[this.contractNetwork].address;
        }
        this.compiler = this.compilation.compiler || this.contract.compiler;
    }
    /**
     * @protected
     */
    init() {
        return __awaiter(this, void 0, void 0, function* () {
            this.contractCode = codec_1.Conversion.toHexString(yield this.getCode(this.contractAddress, yield this.web3.eth.getBlockNumber() //not "latest" because regularized
            ));
            const deployedBytecode = Shims.NewToLegacy.forBytecode(this.contract.deployedBytecode);
            if (!deployedBytecode || deployedBytecode === "0x") {
                //if this contract does *not* have the deployedBytecode field, then the decoder core
                //has no way of knowing that contracts or function pointers with its address
                //are of its class; this is an especial problem for function pointers, as it
                //won't be able to determine what the selector points to.
                //so, to get around this, we make an "additional context" for the contract,
                //based on its *actual* deployed bytecode as pulled from the blockchain.
                //This way the decoder core can recognize the address as the class, without us having
                //to make serious modifications to contract decoding.  And while sure this requires
                //a little more work, I mean, it's all cached, so, no big deal.
                const contractWithCode = Object.assign(Object.assign({}, this.contract), { deployedBytecode: this.contractCode });
                const extraContext = Utils.makeContext(contractWithCode, this.contractNode, this.compilation);
                this.contextHash = extraContext.context;
                this.additionalContexts = { [extraContext.context]: extraContext };
                //the following line only has any effect if we're dealing with a library,
                //since the code we pulled from the blockchain obviously does not have unresolved link references!
                //(it's not strictly necessary even then, but, hey, why not?)
                this.additionalContexts = codec_1.Contexts.Utils.normalizeContexts(this.additionalContexts);
                //again, since the code did not have unresolved link references, it is safe to just
                //mash these together like I'm about to
                this.contexts = Object.assign(Object.assign({}, this.contexts), this.additionalContexts);
            }
            //finally: set up internal functions table (only if source order is reliable;
            //otherwise leave as undefined)
            //unlike the debugger, we don't *demand* an answer, so we won't set up
            //some sort of fake table if we don't have a source map, or if any ASTs are missing
            //(if a whole *source* is missing, we'll consider that OK)
            //note: we don't attempt to handle Vyper source maps!
            const compiler = this.compilation.compiler || this.contract.compiler;
            if (!this.compilation.unreliableSourceOrder &&
                this.contract.deployedSourceMap &&
                compiler.name === "solc" &&
                this.compilation.sources.every(source => !source || source.ast)) {
                //WARNING: untyped code in this block!
                let asts = this.compilation.sources.map(source => source ? source.ast : undefined);
                let instructions = SourceMapUtils.getProcessedInstructionsForBinary(this.compilation.sources.map(source => source ? source.source : undefined), this.contractCode, SourceMapUtils.getHumanReadableSourceMap(this.contract.deployedSourceMap));
                try {
                    //this can fail if some of the source files are missing :(
                    this.internalFunctionsTable = SourceMapUtils.getFunctionsByProgramCounter(instructions, asts, asts.map(SourceMapUtils.makeOverlapFunction), this.compilation.id);
                }
                catch (_) {
                    //just leave the internal functions table undefined
                }
            }
        });
    }
    get context() {
        return this.contexts[this.contextHash];
    }
    checkAllocationSuccess() {
        if (!this.contractNode) {
            throw new errors_1.ContractBeingDecodedHasNoNodeError(this.contract.contractName, this.compilation.id);
        }
        if (!this.stateVariableReferences) {
            throw new errors_1.ContractAllocationFailedError(this.contractNode.id, this.contract.contractName, this.compilation.id);
        }
    }
    decodeVariable(variable, block) {
        return __awaiter(this, void 0, void 0, function* () {
            const info = {
                state: {
                    storage: {},
                    code: codec_1.Conversion.toBytes(this.contractCode)
                },
                mappingKeys: this.mappingKeys,
                userDefinedTypes: this.userDefinedTypes,
                allocations: this.allocations,
                contexts: this.contexts,
                currentContext: this.context,
                internalFunctionsTable: this.internalFunctionsTable
            };
            debug("this.contextHash: %s", this.contextHash);
            const decoder = Codec.decodeVariable(variable.definition, variable.pointer, info, this.compilation.id);
            let result = decoder.next();
            while (result.done === false) {
                let request = result.value;
                let response;
                switch (request.type) {
                    case "storage":
                        response = yield this.getStorage(this.contractAddress, request.slot, block);
                        break;
                    case "code":
                        response = yield this.getCode(request.address, block);
                        break;
                }
                result = decoder.next(response);
            }
            //at this point, result.value holds the final value
            debug("definedIn: %o", variable.definedIn);
            let classType = codec_1.Ast.Import.definitionToStoredType(variable.definedIn, this.compilation.id, this.compiler); //can skip reference decls
            return {
                name: variable.definition.name,
                class: classType,
                value: result.value
            };
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Returns information about the state of the contract, but does not include
     * information about the storage or decoded variables.  See the documentation
     * for the [[ContractState]] type for more.
     * @param block The block to inspect the contract's state at.  Defaults to latest.
     *   See [[BlockSpecifier]] for legal values.
     */
    state(block = "latest") {
        return __awaiter(this, void 0, void 0, function* () {
            let blockNumber = yield this.regularizeBlock(block);
            return {
                class: codec_1.Contexts.Import.contextToType(this.context),
                address: this.contractAddress,
                code: this.contractCode,
                balanceAsBN: new bn_js_1.default(yield this.web3.eth.getBalance(this.contractAddress, blockNumber)),
                nonceAsBN: new bn_js_1.default(yield this.web3.eth.getTransactionCount(this.contractAddress, blockNumber))
            };
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Decodes the contract's variables; returns an array of these decoded variables.
     * See the documentation of the [[DecodedVariable]] type for more.
     *
     * Note that variable decoding can only operate in full mode; if the decoder wasn't able to
     * start up in full mode, this method will throw a [[ContractAllocationFailedError]].
     *
     * Note that decoding mappings requires first watching mapping keys in order to get any results;
     * see the documentation for [[watchMappingKey]].
     * Additional methods to make mapping decoding a less manual affair are planned for the future.
     *
     * Also, due to a technical limitation, it is not currently possible to
     * usefully decode internal function pointers.  See the
     * [[Format.Values.FunctionInternalValue|FunctionInternalValue]]
     * documentation and the README for more on how these are handled.
     * @param block The block to inspect the contract's state at.  Defaults to latest.
     *   See [[BlockSpecifier]] for legal values.
     */
    variables(block = "latest") {
        return __awaiter(this, void 0, void 0, function* () {
            this.checkAllocationSuccess();
            let blockNumber = yield this.regularizeBlock(block);
            let result = [];
            for (const variable of this.stateVariableReferences) {
                debug("about to decode %s", variable.definition.name);
                const decodedVariable = yield this.decodeVariable(variable, blockNumber);
                debug("decoded");
                result.push(decodedVariable);
            }
            return result;
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Decodes an individual contract variable; returns its value as a
     * [[Format.Values.Result|Result]].  See the documentation for
     * [[variables|variables()]] for various caveats that also apply here.
     *
     * If the variable can't be located, throws an exception.
     * @param nameOrId The name (or numeric ID, if you know that) of the
     *   variable.  Can be given as a qualified name, allowing one to get at
     *   shadowed variables from base contracts.  If given by ID, can be given as a
     *   number or numeric string.
     * @param block The block to inspect the contract's state at.  Defaults to latest.
     *   See [[BlockSpecifier]] for legal values.
     * @example Consider a contract `Derived` inheriting from a contract `Base`.
     *   Suppose `Derived` has a variable `x` and `Base` has variables `x` and
     *   `y`.  One can access `Derived.x` as `variable("x")` or
     *   `variable("Derived.x")`, can access `Base.x` as `variable("Base.x")`,
     *   and can access `Base.y` as `variable("y")` or `variable("Base.y")`.
     */
    variable(nameOrId, block = "latest") {
        return __awaiter(this, void 0, void 0, function* () {
            this.checkAllocationSuccess();
            let blockNumber = yield this.regularizeBlock(block);
            let variable = this.findVariableByNameOrId(nameOrId);
            if (variable === undefined) {
                //if user put in a bad name
                throw new errors_1.VariableNotFoundError(nameOrId);
            }
            return (yield this.decodeVariable(variable, blockNumber)).value;
        });
    }
    findVariableByNameOrId(nameOrId) {
        //case 1: an ID was input
        if (typeof nameOrId === "number" || nameOrId.match(/[0-9]+/)) {
            return this.stateVariableReferences.find(({ definition }) => definition.id === nameOrId);
            //there should be exactly one; returns undefined if none
        }
        //case 2: a name was input
        else if (!nameOrId.includes(".")) {
            //we want to search *backwards*, to get most derived version;
            //we use slice().reverse() to clone before reversing since reverse modifies
            return this.stateVariableReferences
                .slice()
                .reverse()
                .find(({ definition }) => definition.name === nameOrId);
        }
        //case 3: a qualified name was input
        else {
            let [className, variableName] = nameOrId.split(".");
            //again, we'll search backwards, although, uhhh...?
            return this.stateVariableReferences
                .slice()
                .reverse()
                .find(({ definition, definedIn }) => definition.name === variableName && definedIn.name === className);
        }
    }
    getStorage(address, slot, block) {
        return __awaiter(this, void 0, void 0, function* () {
            //if pending, bypass the cache
            if (block === "pending") {
                return codec_1.Conversion.toBytes(yield this.web3.eth.getStorageAt(address, slot, block), Codec.Evm.Utils.WORD_SIZE);
            }
            //otherwise, start by setting up any preliminary layers as needed
            if (this.storageCache[block] === undefined) {
                this.storageCache[block] = {};
            }
            if (this.storageCache[block][address] === undefined) {
                this.storageCache[block][address] = {};
            }
            //now, if we have it cached, just return it
            if (this.storageCache[block][address][slot.toString()] !== undefined) {
                return this.storageCache[block][address][slot.toString()];
            }
            //otherwise, get it, cache it, and return it
            let word = codec_1.Conversion.toBytes(yield this.web3.eth.getStorageAt(address, slot, block), Codec.Evm.Utils.WORD_SIZE);
            this.storageCache[block][address][slot.toString()] = word;
            return word;
        });
    }
    getCode(address, block) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.getCode(address, block);
        });
    }
    regularizeBlock(block) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.regularizeBlock(block);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Watches a mapping key; adds it to the decoder's list of watched mapping
     * keys.  This affects the results of both [[variables|variables()]] and
     * [[variable|variable()]].  When a mapping is decoded, only the values at
     * its watched keys will be included in its value.
     *
     * Note that it is possible
     * to watch mappings that are inside structs, arrays, other mappings, etc;
     * see below for more on how to do this.
     *
     * Note that watching mapping keys is
     * only possible in full mode; if the decoder wasn't able to start up in full
     * mode, this method will throw an exception.
     *
     * **Warning**: At the moment, this function does very little to check its
     * input.  Bad input may have unpredictable results.  This will be remedied
     * in the future (by having it throw exceptions on bad input), but right now
     * essentially no checking is implemented.  Also, there may be slight changes
     * to the format of indices in the future.
     *
     * (A bad variable name will cause an exception though; that input is checked.)
     * @param variable The variable that the mapping lives under; this works like
     *   the nameOrId argument to [[variable|variable()]].  If the mapping is a
     *   top-level state variable, put the mapping itself here.  Otherwise, put the
     *   top-level state variable it lives under.
     * @param indices Further arguments to watchMappingKey, if given, will be
     *   interpreted as indices into or members of the variable identified by the
     *   variable argument; see the example.  Array indices and mapping
     *   keys are specified by value; struct members are specified by name.
     *
     *   Numeric values can be given as number, BN, or
     *   numeric string.  Bytestring values are given as hex strings.  Boolean
     *   values are given as booleans, or as the strings "true" or "false".
     *   Address values are given as hex strings; they are currently not required
     *   to be in checksum case, but this will likely change in the future, so
     *   don't rely on that.  Contract values work like address values.
     *   Enum values can be given either as a numeric value or by name;
     *   in the latter case you can use either a qualified name or just the
     *   name of the option (i.e., you can just write `"Option"` rather than
     *   `"Enum.Option"` or `"Contract.Enum.Option"`, but those will work too).
     *
     *   Note that if the path to a given mapping key
     *   includes mapping keys above it, any ancestors will also be watched
     *   automatically.
     * @example First, a simple example.  Say we have a mapping `m` of type
     *   `mapping(uint => uint)`.  You could call `watchMappingKey("m", 0)` to
     *   watch `m[0]`.
     * @example Now for a slightly more complicated example.  Say `m` is of type
     *   `mapping(uint => mapping(uint => uint))`, then to watch `m[3][5]`, you
     *   can call `watchMappingKey("m", 3, 5)`.  This will also automatically
     *   watch `m[3]`; otherwise, watching `m[3][5]` wouldn't do much of
     *   anything.
     * @example Now for a well more complicated example.  Say we have a struct
     *   type `MapStruct` with a member called `map` which is a `mapping(string => string)`,
     *   and say we have a variable `arr` of type `MapStruct[]`, then one could
     *   watch `arr[3].map["hello"]` by calling `watchMappingKey("arr", 3, "map", "hello")`.
     */
    watchMappingKey(variable, ...indices) {
        return __awaiter(this, void 0, void 0, function* () {
            this.checkAllocationSuccess();
            let slot = this.constructSlot(variable, ...indices)[0];
            //add mapping key and all ancestors
            debug("slot: %O", slot);
            while (slot !== undefined &&
                this.mappingKeys.every(existingSlot => !codec_1.Storage.Utils.equalSlots(existingSlot, slot)
                //we put the newness requirement in the while condition rather than a
                //separate if because if we hit one ancestor that's not new, the futher
                //ones won't be either
                )) {
                if (slot.key !== undefined) {
                    //only add mapping keys
                    this.mappingKeys = [...this.mappingKeys, slot];
                }
                slot = slot.path;
            }
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * Opposite of [[watchMappingKey]]; unwatches the specified mapping key.  See
     * watchMappingKey for more on how watching mapping keys works, and on how
     * the parameters work.
     *
     * Note that unwatching a mapping key will also unwatch all its descendants.
     * E.g., if `m` is of type `mapping(uint => mapping(uint => uint))`, then
     * unwatching `m[0]` will also unwatch `m[0][0]`, `m[0][1]`, etc, if these
     * are currently watched.
     *
     * This function has the same caveats as watchMappingKey.
     */
    unwatchMappingKey(variable, ...indices) {
        return __awaiter(this, void 0, void 0, function* () {
            this.checkAllocationSuccess();
            let slot = this.constructSlot(variable, ...indices)[0];
            if (slot === undefined) {
                return; //not strictly necessary, but may as well
            }
            //remove mapping key and all descendants
            this.mappingKeys = this.mappingKeys.filter(existingSlot => {
                while (existingSlot !== undefined) {
                    if (codec_1.Storage.Utils.equalSlots(existingSlot, slot)) {
                        return false; //if it matches, remove it
                    }
                    existingSlot = existingSlot.path;
                }
                return true; //if we didn't match, keep the key
            });
        });
    }
    //NOTE: if you decide to add a way to remove a mapping key *without* removing
    //all descendants, you'll need to alter watchMappingKey to use an if rather
    //than a while
    /**
     * **This method is asynchronous.**
     *
     * See [[WireDecoder.decodeTransaction]].
     */
    decodeTransaction(transaction) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.decodeTransactionWithAdditionalContexts(transaction, this.additionalContexts);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * See [[WireDecoder.decodeLog]].
     */
    decodeLog(log, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.decodeLogWithAdditionalOptions(log, options, this.additionalContexts);
        });
    }
    /**
     * **This method is asynchronous.**
     *
     * See [[ContractDecoder.decodeReturnValue]].
     *
     * If the contract artifact is missing its bytecode, using this method,
     * rather than the one in [[ContractDecoder]], can sometimes provide
     * additional decoding information.
     */
    decodeReturnValue(abi, data, options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.contractDecoder.decodeReturnValueWithAdditionalContexts(abi, data, options, this.additionalContexts);
        });
    }
    /**
     * See [[WireDecoder.abifyCalldataDecoding]].
     */
    abifyCalldataDecoding(decoding) {
        return this.wireDecoder.abifyCalldataDecoding(decoding);
    }
    /**
     * See [[WireDecoder.abifyLogDecoding]].
     */
    abifyLogDecoding(decoding) {
        return this.wireDecoder.abifyLogDecoding(decoding);
    }
    /**
     * See [[WireDecoder.abifyReturndataDecoding]].
     */
    abifyReturndataDecoding(decoding) {
        return this.wireDecoder.abifyReturndataDecoding(decoding);
    }
    /**
     * **This method is asynchronous.**
     *
     * This mostly behaves as [[WireDecoder.events]].
     * However, unlike other variants of this function, this one, by default, restricts to events originating from this instance's address.
     * If you don't want to restrict like that, you can explicitly use `address: undefined` in the options to disable this.
     * (You can also of course set a different address to restrict to that.)
     * @param options Used to determine what events to fetch; see the documentation on the [[EventOptions]] type for more.
     */
    events(options = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.wireDecoder.eventsWithAdditionalContexts(Object.assign({ address: this.contractAddress }, options), this.additionalContexts);
        });
    }
    //in addition to returning the slot we want, it also returns a Type
    //used in the recursive call
    //HOW TO USE:
    //variable may be a variable id (number or numeric string) or name (string) or qualified name (also string)
    //struct members are given by name (string)
    //array indices and numeric mapping keys may be BN, number, or numeric string
    //string mapping keys should be given as strings. duh.
    //bytes mapping keys should be given as hex strings beginning with "0x"
    //address mapping keys are like bytes; checksum case is not required
    //boolean mapping keys may be given either as booleans, or as string "true" or "false"
    constructSlot(variable, ...indices) {
        //base case: we need to locate the variable and its definition
        if (indices.length === 0) {
            let allocation = this.findVariableByNameOrId(variable);
            if (!allocation) {
                throw new errors_1.VariableNotFoundError(variable);
            }
            let dataType = codec_1.Ast.Import.definitionToType(allocation.definition, this.compilation.id, this.contract.compiler, "storage");
            let pointer = allocation.pointer;
            if (pointer.location !== "storage") {
                //i.e., if it's a constant
                return [undefined, undefined];
            }
            return [pointer.range.from.slot, dataType];
        }
        //main case
        let parentIndices = indices.slice(0, -1); //remove last index
        let [parentSlot, parentType] = this.constructSlot(variable, ...parentIndices);
        if (parentSlot === undefined) {
            return [undefined, undefined];
        }
        let rawIndex = indices[indices.length - 1];
        let index;
        let key;
        let slot;
        let dataType;
        switch (parentType.typeClass) {
            case "array":
                if (rawIndex instanceof bn_js_1.default) {
                    index = rawIndex.clone();
                }
                else {
                    index = new bn_js_1.default(rawIndex);
                }
                dataType = parentType.baseType;
                let size = codec_1.Storage.Allocate.storageSize(dataType, this.userDefinedTypes, this.allocations.storage);
                if (!codec_1.Storage.Utils.isWordsLength(size)) {
                    return [undefined, undefined];
                }
                slot = {
                    path: parentSlot,
                    offset: index.muln(size.words),
                    hashPath: parentType.kind === "dynamic"
                };
                break;
            case "mapping":
                let keyType = parentType.keyType;
                if (keyType.typeClass === "enum") {
                    keyType = (codec_1.Format.Types.fullType(keyType, this.userDefinedTypes));
                }
                key = Utils.wrapElementaryValue(rawIndex, keyType);
                dataType = parentType.valueType;
                slot = {
                    path: parentSlot,
                    key,
                    offset: new bn_js_1.default(0)
                };
                break;
            case "struct":
                //NOTE: due to the reliance on storage allocations,
                //we don't need to use fullType or what have you
                let allocation = this.allocations.storage[parentType.id].members.find(({ name }) => name === rawIndex); //there should be exactly one
                slot = {
                    path: parentSlot,
                    //need type coercion here -- we know structs don't contain constants but the compiler doesn't
                    offset: allocation.pointer.range.from.slot.offset.clone()
                };
                dataType = allocation.type;
                break;
            default:
                return [undefined, undefined];
        }
        return [slot, dataType];
    }
}
exports.ContractInstanceDecoder = ContractInstanceDecoder;
//# sourceMappingURL=decoders.js.map

/***/ }),

/***/ 613552:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoProjectInfoError = exports.VariableNotFoundError = exports.InvalidAddressError = exports.ContractAllocationFailedError = exports.ContractNotFoundError = exports.ContractBeingDecodedHasNoNodeError = void 0;
/**
 * This error indicates that the contract you are attempting to decode does not have AST
 * information associated with it, or that the decoder cannot find it.  This error will
 * be thrown if you attempt to use functions that require AST information with such a contract.
 * @category Exception
 */
class ContractBeingDecodedHasNoNodeError extends Error {
    constructor(contractName, compilationId) {
        const message = `Contract ${contractName} does not appear to have been compiled with Solidity (cannot locate contract node)`;
        super(message);
        this.contractName = contractName;
        this.compilationId = compilationId;
        this.name = "ContractBeingDecodedHasNoNodeError";
    }
}
exports.ContractBeingDecodedHasNoNodeError = ContractBeingDecodedHasNoNodeError;
/**
 * This error indicates that the contract you are attempting to decode could not be found in
 * the project info.  This error will be thrown if you attempt to spawn a contract decoder or
 * contract instance decoder for a contract not appearing in the project info.
 * @category Exception
 */
class ContractNotFoundError extends Error {
    constructor(contractName, bytecode, deployedBytecode, address) {
        let message;
        if (contractName) {
            message = `Contract ${contractName} could not be found in the project information`;
        }
        else {
            message = `Contract at ${address} could not be found in the project information`;
        }
        super(message);
        this.contractName = contractName;
        this.bytecode = bytecode;
        this.deployedBytecode = deployedBytecode;
        this.address = address;
        this.name = "ContractNotFoundError";
    }
}
exports.ContractNotFoundError = ContractNotFoundError;
/**
 * This error indicates that something went wrong while attempting to determine the location
 * of this contract's state variables.  This error will be thrown if you attempt to use
 * decoding functions after something went wrong during setup.  Unfortunately, we can't
 * always avoid this at the moment; we're hoping to make this more robust in the future
 * with Truffle DB.  In the meantime, it is at least worth noting that you should not encounter
 * this error if your entire project was written in Solidity and all compiled at once.  Sorry.
 * @category Exception
 */
class ContractAllocationFailedError extends Error {
    constructor(id, contractName, compilationId) {
        super(`No allocation found for contract ID ${id} (${contractName}) in compilation ${compilationId}`);
        this.id = id;
        this.contractName = contractName;
        this.compilationId = compilationId;
        this.name = "ContractAllocationFailedError";
    }
}
exports.ContractAllocationFailedError = ContractAllocationFailedError;
/**
 * This error indicates that an invalid address was passed to one of the
 * contract instance decoder spawners ([[forContractInstance]], etc).  Valid
 * addresses are those that Web3 accepts; i.e., either those with correct
 * checksums, or those that are all-lowercase or all-uppercase to deliberately
 * circumvent the checksum.
 * @category Exception
 */
class InvalidAddressError extends Error {
    constructor(address) {
        super(`Invalid address ${address}`);
        this.address = address;
        this.name = "InvalidAddressError";
    }
}
exports.InvalidAddressError = InvalidAddressError;
/**
 * This error indicates that the user requested a variable that does not exist.
 * @category Exception
 */
class VariableNotFoundError extends Error {
    constructor(nameOrId) {
        super(`No such variable ${nameOrId}`);
        this.nameOrId = nameOrId;
        this.name = "VariableNotFoundError";
    }
}
exports.VariableNotFoundError = VariableNotFoundError;
/**
 * This error indicates that the user attempted to instantiate a decoder
 * with no project information (by explicitly overriding the default).
 * @category Exception
 */
class NoProjectInfoError extends Error {
    constructor() {
        super("No project information specified.");
        this.name = "NoProjectInfoError";
    }
}
exports.NoProjectInfoError = NoProjectInfoError;
//# sourceMappingURL=errors.js.map

/***/ }),

/***/ 18852:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/**
# Truffle Decoder

This module provides an interface for decoding contract state, transaction
calldata, events, and return values and revert strings.  It's an interface to
the same low-level decoding functionality that Truffle Debugger uses.  However,
it has additional functionality that the debugger does not need, and the
debugger has additional functionality that this decoder does not need.

The interface is split into three classes: The wire decoder, the contract
decoder, and the contract instance decoder.  The wire decoder is associated to
the project as a whole and decodes transaction calldata and events.  The
contract decoder is associated to a specific contract class.  It has all the
capabilities of the wire decoder, but in addition it acts as a factory for
contract instance decoders.  The contract instance decoder is associated to a
specific contract instance; it too has all the capabilities of the wire decoder,
but it can also decode the state variables for the specific instance.  (In
addition, in the case that the contract does not include a `deployedBytecode`
field in its artifact, which can hinder decoding certain things, the contract
instance decoder can sometimes work around this where the other decoders
cannot.)

This documentation describes the current state of the decoder, but you should
expect to see improvements soon.

## Usage

### Initialization

Create a decoder with one of the various constructor functions.

For a wire decoder, use the [[forProject|`forProject`]] function.

For a contract decoder, use the [[forArtifact|`forArtifact`]] or
[[forContract|`forContract`]] function.

For a contract instance decoder, use one of the following:
* [[forDeployedArtifact|`forDeployedArtifact`]]
* [[forDeployedContract|`forDeployedContract`]]
* [[forArtifactAt|`forArtifactAt`]]
* [[forContractAt|`forContractAt`]]
* [[forContractInstance|`forContractInstance`]]
* [[forAddress|`forAddress`]]

See the documentation of these functions for details, or below for usage
examples.

All of these functions take a final argument in which information about the
project is specified; currently only a few methods for specifying project
information are allowed, but more are planned.

One can also spawn decoders from other decoders by supplying additional
information.  See the documentation for the individual decoder classes for a
method listing.

### Decoder methods

See the documentation for the individual decoder classes for a method listing.

### Output format information

The decoder outputs lossless, machine-readable [[Format.Values.Result]] objects
containing individual decoded values. See the [[Format|format documentation]]
for an overview and complete module listing.

### Decoding modes, abification, and caveats

The decoder runs in either of two modes: full mode or ABI mode. Full mode
requires some additional constraints but returns substantially more detailed
information. Please see the notes on [decoding modes](../#decoding-modes) for
more about this distinction.

See also the notes about [decoding state variables](../#additional-notes-on-decoding-state-variables) for additional
caveats about what may or may not be fully decodable.

### Basic usage examples

#### Decoding a log with the wire decoder

This usage example is for a project with two contracts, `Contract1` and
`Contract2`.

```typescript
import { forProject } from "@truffle/decoder";
const contract1 = artifacts.require("Contract1");
const contract2 = artifacts.require("Contract2");
const provider = web3.currentProvider;
const decoder = await Decoder.forProject(provider, [contract1, contract2]);
const decodings = await decoder.decodeLog(log);
```

The usage of [[WireDecoder.decodeTransaction|decodeTransaction]] is similar.

For getting already-decoded logs meeting appropriate conditions, see
[[WireDecoder.events]].

#### Decoding state variables with the contract instance decoder

This usage example is for decoding the state variables of a contract `Contract`
in a project that also contains a contract `OtherContract`.

```typescript
import { forContract } from "@truffle/decoder";
const contract = artifacts.require("Contract");
const otherContract = artifacts.require("OtherContract");
const decoder = await Decoder.forContract(contract, [otherContract]);
const instanceDecoder = await decoder.forInstance();
const variables = await instanceDecoder.variables();
```

In this example, we use the deployed version of `Contract`.  If we wanted an
instance at a different address, we could pass the address to `forInstance`.

In addition, rather than using `forContract` and then `forInstance`, we could
also use [[forDeployedContract|`forContractInstance`]] to perform both of these
in one step.  If we wanted to do this with a specified address, we could use
[[forContractAt|`forContractAt`]].

Yet another way would be:
```typescript
import { forContractInstance } from "@truffle/decoder";
const contract = artifacts.require("Contract");
const otherContract = artifacts.require("OtherContract");
const deployedContract = await contract.deployed();
const instanceDecoder = await Decoder.forContractInstance(deployedContract, [otherContract]);
const variables = await instanceDecoder.variables();
```

These examples are not exhaustive.

One can find more advanced decoding examples with
[[ContractInstanceDecoder.variable|`variable`]] and
[[ContractInstanceDecoder.watchMappingKey|`watchMappingKey`]] at the
documentation for these individual functions.
 *
 * @module @truffle/decoder
 */ /** */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.forAddress = exports.forContractInstance = exports.forContractAt = exports.forArtifactAt = exports.forDeployedContract = exports.forDeployedArtifact = exports.forContract = exports.forArtifact = exports.forProject = exports.NoProjectInfoError = exports.VariableNotFoundError = exports.InvalidAddressError = exports.ContractAllocationFailedError = exports.ContractNotFoundError = exports.ContractBeingDecodedHasNoNodeError = exports.WireDecoder = exports.ContractInstanceDecoder = exports.ContractDecoder = void 0;
const decoders_1 = __webpack_require__(595532);
Object.defineProperty(exports, "ContractDecoder", ({ enumerable: true, get: function () { return decoders_1.ContractDecoder; } }));
Object.defineProperty(exports, "ContractInstanceDecoder", ({ enumerable: true, get: function () { return decoders_1.ContractInstanceDecoder; } }));
Object.defineProperty(exports, "WireDecoder", ({ enumerable: true, get: function () { return decoders_1.WireDecoder; } }));
var errors_1 = __webpack_require__(613552);
Object.defineProperty(exports, "ContractBeingDecodedHasNoNodeError", ({ enumerable: true, get: function () { return errors_1.ContractBeingDecodedHasNoNodeError; } }));
Object.defineProperty(exports, "ContractNotFoundError", ({ enumerable: true, get: function () { return errors_1.ContractNotFoundError; } }));
Object.defineProperty(exports, "ContractAllocationFailedError", ({ enumerable: true, get: function () { return errors_1.ContractAllocationFailedError; } }));
Object.defineProperty(exports, "InvalidAddressError", ({ enumerable: true, get: function () { return errors_1.InvalidAddressError; } }));
Object.defineProperty(exports, "VariableNotFoundError", ({ enumerable: true, get: function () { return errors_1.VariableNotFoundError; } }));
const errors_2 = __webpack_require__(613552);
Object.defineProperty(exports, "NoProjectInfoError", ({ enumerable: true, get: function () { return errors_2.NoProjectInfoError; } }));
const codec_1 = __webpack_require__(20102);
const fs_1 = __importDefault(__webpack_require__(935747));
const path_1 = __importDefault(__webpack_require__(385622));
/**
 * **This function is asynchronous.**
 *
 * Constructs a wire decoder for the project.
 * @param provider The Web3 provider object to use.
 * @param projectInfo Information about the project or contracts being decoded.
 *   This may come in several forms; see the [[ProjectInfo]] documentation for
 *   more information.
 *
 *   Alternatively, instead of a [[ProjectInfo]], one may simply pass a list of
 *   artifacts.  Contract constructor objects may be substituted for artifacts,
 *   so if you're not sure which you're dealing with, it's OK.  If this parameter
 *   is omitted, it's treated as if one had passed `[]`.
 * @category Provider-based Constructor
 */
function forProject(provider, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let compilations = infoToCompilations(projectInfo);
        return new decoders_1.WireDecoder(compilations, provider);
    });
}
exports.forProject = forProject;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract decoder for a given contract artifact.
 * @param artifact The artifact for the contract.
 *
 *   A contract constructor object may be substituted for the artifact, so if
 *   you're not sure which you're dealing with, it's OK.
 * @param provider The Web3 provider object to use.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms; see the [[ProjectInfo]] documentation for more
 *   information.
 *
 *   Alternatively, instead of a [[ProjectInfo]], one may simply pass a list of
 *   artifacts.  Contract constructor objects may be substituted for artifacts,
 *   so if you're not sure which you're dealing with, it's OK.
 *
 *   If this latter option is used, one may omit `artifact` itself from the
 *   list of artifacts and only include the *other* relevant artifacts; note
 *   that omission this is not allowed when passing a `ProjectInfo`.
 *
 *   If this parameter is omitted, it's treated as if one had passed `[]`.
 * @category Provider-based Constructor
 */
function forArtifact(artifact, provider, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let compilations = infoToCompilations(projectInfo, artifact);
        let wireDecoder = yield forProject(provider, { compilations });
        return yield wireDecoder.forArtifact(artifact);
    });
}
exports.forArtifact = forArtifact;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract decoder for a given contract.
 * @param contract The contract constructor object corresponding to the type of the contract.
 * @param artifacts A list of artifacts for other contracts in the project that may be relevant
 *   (e.g., providing needed struct or enum definitions, or appearing as a contract type).
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. See the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Truffle Contract-based Constructor
 */
function forContract(contract, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield forArtifact(contract, contract.web3.currentProvider, projectInfo);
    });
}
exports.forContract = forContract;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a deployed contract instance.
 * @param artifact The artifact corresponding to the type of the contract.
 *
 *   A contract constructor object may be substituted for the artifact, so if
 *   you're not sure which you're dealing with, it's OK.
 * @param provider The Web3 provider object to use.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. see the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Provider-based Constructor
 */
function forDeployedArtifact(artifact, provider, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let contractDecoder = yield forArtifact(artifact, provider, projectInfo);
        let instanceDecoder = yield contractDecoder.forInstance();
        return instanceDecoder;
    });
}
exports.forDeployedArtifact = forDeployedArtifact;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a deployed contract instance.
 * @param contract The contract constructor object corresponding to the type of the contract.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. see the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Truffle Contract-based Constructor
 */
function forDeployedContract(contract, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let contractDecoder = yield forContract(contract, projectInfo);
        let instanceDecoder = yield contractDecoder.forInstance();
        return instanceDecoder;
    });
}
exports.forDeployedContract = forDeployedContract;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a contract instance at a given address.
 * @param artifact The artifact corresponding to the type of the contract.
 *
 *   A contract constructor object may be substituted for the artifact, so if
 *   you're not sure which you're dealing with, it's OK.
 * @param provider The Web3 provider object to use.
 * @param address The address of the contract instance to decode.
 *
 *   Address must either be checksummed, or in all one case to circumvent the checksum.
 *   Mixed-case with bad checksum will cause this function to throw an exception.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. see the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Provider-based Constructor
 */
function forArtifactAt(artifact, provider, address, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let contractDecoder = yield forArtifact(artifact, provider, projectInfo);
        let instanceDecoder = yield contractDecoder.forInstance(address);
        return instanceDecoder;
    });
}
exports.forArtifactAt = forArtifactAt;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a contract instance at a given address.
 * @param contract The contract constructor object corresponding to the type of the contract.
 * @param address The address of the contract instance to decode.
 *
 *   Address must either be checksummed, or in all one case to circumvent the checksum.
 *   Mixed-case with bad checksum will cause this function to throw an exception.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. see the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Truffle Contract-based Constructor
 */
function forContractAt(contract, address, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let contractDecoder = yield forContract(contract, projectInfo);
        let instanceDecoder = yield contractDecoder.forInstance(address);
        return instanceDecoder;
    });
}
exports.forContractAt = forContractAt;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a given contract instance.
 * @param contract The contract abstraction object corresponding to the contract instance.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. see the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forArtifact]]
 *   for more detail.
 * @category Truffle Contract-based Constructor
 */
function forContractInstance(contract, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield forContractAt(contract.constructor, contract.address, projectInfo);
    });
}
exports.forContractInstance = forContractInstance;
/**
 * **This function is asynchronous.**
 *
 * Constructs a contract instance decoder for a given instance of a contract in this
 * project.  Unlike the other functions, this method doesn't require giving an
 * artifact for the address itself; however, the address had better correspond to
 * a contract of a type given in the project info, or you'll get an exception.
 * @param address The address of the contract instance to decode.
 *   If an invalid address is provided, this method will throw an exception.
 * @param provider The Web3 provider object to use.
 * @param projectInfo Information about the project being decoded, or just the
 *   contracts relevant to the contract being decoded (e.g., by providing struct
 *   or enum definitions, or even just appearing as a contract type).  This may
 *   come in several forms. See the [[ProjectInfo]] documentation for more
 *   information.  See the projectInfo parameter documentation on [[forProject]]
 *   for more detail.
 * @category Provider-based Constructor
 */
function forAddress(address, provider, projectInfo) {
    return __awaiter(this, void 0, void 0, function* () {
        let wireDecoder = yield forProject(provider, projectInfo);
        return yield wireDecoder.forAddress(address);
    });
}
exports.forAddress = forAddress;
//Note: this function doesn't actually go in this category, but
//I don't want an unsightly "Other functions" thing appearing,
//so I'm hiding it here :)
/**
 * @category Provider-based Constructor
 */
function infoToCompilations(info, primaryArtifact) {
    if (!info) {
        info = [];
    }
    if (Array.isArray(info)) {
        let artifacts = info;
        if (primaryArtifact &&
            !artifacts.find(artifact => artifact === primaryArtifact ||
                artifact.contractName === primaryArtifact.contractName)) {
            artifacts = [primaryArtifact, ...artifacts];
        }
        return codec_1.Compilations.Utils.shimArtifacts(artifacts);
    }
    else {
        let projectInfo = info;
        if (projectInfo.compilations) {
            return projectInfo.compilations;
        }
        else if (projectInfo.artifacts) {
            return codec_1.Compilations.Utils.shimArtifacts(projectInfo.artifacts);
        }
        else if (projectInfo.config) {
            //NOTE: This will be expanded in the future so that it's not just
            //using the build directory
            if (projectInfo.config.contracts_build_directory !== undefined) {
                let files = fs_1.default
                    .readdirSync(projectInfo.config.contracts_build_directory)
                    .filter(file => path_1.default.extname(file) === ".json");
                let data = files.map(file => fs_1.default.readFileSync(path_1.default.join(projectInfo.config.contracts_build_directory, file), "utf8"));
                let artifacts = data.map(json => JSON.parse(json));
                return codec_1.Compilations.Utils.shimArtifacts(artifacts);
            }
            else {
                throw new errors_2.NoProjectInfoError();
            }
        }
        else {
            throw new errors_2.NoProjectInfoError();
        }
    }
}
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 379550:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.wrapElementaryValue = exports.makeContext = exports.unsafeNativizeDecoderVariables = void 0;
const debug_1 = __importDefault(__webpack_require__(968082));
const debug = debug_1.default("decoder:utils");
const web3_1 = __importDefault(__webpack_require__(503283));
const bn_js_1 = __importDefault(__webpack_require__(213550));
const Codec = __importStar(__webpack_require__(20102));
const Abi = __importStar(__webpack_require__(207651));
//sorry for the untyped import, but...
const { Shims } = __webpack_require__(529833);
//NOTE: Definitely do not use this in real code!  For tests only!
//for convenience: invokes the nativize method on all the given variables, and changes them to
//the old format
function unsafeNativizeDecoderVariables(variables) {
    return Object.assign({}, ...variables.map(({ name, value }) => ({
        [name]: Codec.Format.Utils.Inspect.unsafeNativize(value)
    })));
    //note that the assignments are processed in order, so if multiple have same name, later
    //(i.e. more derived) will overwrite earlier (i.e. baser)... be aware!  I mean, this is the
    //right way to do overwriting, but it's still overwriting so still dangerous.
    //Again, don't use this in real code!
}
exports.unsafeNativizeDecoderVariables = unsafeNativizeDecoderVariables;
function makeContext(contract, node, compilation, isConstructor = false) {
    const abi = Abi.normalize(contract.abi);
    const bytecode = isConstructor
        ? contract.bytecode
        : contract.deployedBytecode;
    const binary = Shims.NewToLegacy.forBytecode(bytecode);
    const hash = Codec.Conversion.toHexString(Codec.Evm.Utils.keccak256({
        type: "string",
        value: binary
    }));
    debug("hash: %s", hash);
    const fallback = abi.find(abiEntry => abiEntry.type === "fallback") ||
        null; //TS is failing at inference here
    const receive = abi.find(abiEntry => abiEntry.type === "receive") || null; //and here
    return {
        context: hash,
        contractName: contract.contractName,
        binary,
        contractId: node ? node.id : undefined,
        linearizedBaseContracts: node ? node.linearizedBaseContracts : undefined,
        contractKind: contractKind(contract, node),
        immutableReferences: isConstructor
            ? undefined
            : contract.immutableReferences,
        isConstructor,
        abi: Codec.AbiData.Utils.computeSelectors(abi),
        payable: Codec.AbiData.Utils.abiHasPayableFallback(abi),
        fallbackAbi: { fallback, receive },
        compiler: compilation.compiler || contract.compiler,
        compilationId: compilation.id
    };
}
exports.makeContext = makeContext;
//attempts to determine if the given contract is a library or not
function contractKind(contract, node) {
    //first: if we have a node, use its listed contract kind
    if (node) {
        return node.contractKind;
    }
    //next: check the contract kind field on the contract object itself, if it exists.
    //however this isn't implemented yet so we'll skip it.
    //next: if we have no direct info on the contract kind, but we do
    //have the deployed bytecode, we'll use a HACK:
    //we'll assume it's an ordinary contract, UNLESS its deployed bytecode begins with
    //PUSH20 followed by 20 0s, in which case we'll assume it's a library
    //(note: this will fail to detect libraries from before Solidity 0.4.20)
    if (contract.deployedBytecode) {
        const deployedBytecode = Shims.NewToLegacy.forBytecode(contract.deployedBytecode);
        const pushAddressInstruction = (0x60 +
            Codec.Evm.Utils.ADDRESS_SIZE -
            1).toString(16); //"73"
        const libraryString = "0x" + pushAddressInstruction + "00".repeat(Codec.Evm.Utils.ADDRESS_SIZE);
        return deployedBytecode.startsWith(libraryString) ? "library" : "contract";
    }
    //finally, in the absence of anything to go on, we'll assume it's an ordinary contract
    return "contract";
}
//Function for wrapping a value as an ElementaryValue
//(note: assumes any enum types are the full type)
//WARNING: this function does not check its inputs! Please check before using!
//How to use:
//numbers may be BN, number, or numeric string
//strings should be given as strings. duh.
//bytes should be given as hex strings beginning with "0x"
//addresses and contracts are like bytes; checksum case is not required
//booleans may be given either as booleans, or as string "true" or "false"
//enums may be given by name or by numeric value
//[NOTE: in the future this function will:
//1. check its inputs,
//2. take a slightly different input format,
//3. also be named differently and... it'll be different :P ]
function wrapElementaryValue(value, dataType) {
    switch (dataType.typeClass) {
        case "string":
            return {
                type: dataType,
                kind: "value",
                value: {
                    kind: "valid",
                    asString: value
                }
            };
        case "bytes":
            //NOTE: in the future should add padding for static case
            return {
                //TS is so bad at unions
                type: dataType,
                kind: "value",
                value: {
                    asHex: value
                }
            };
        case "address":
            value = web3_1.default.utils.toChecksumAddress(value);
            return {
                type: dataType,
                kind: "value",
                value: {
                    asAddress: value
                }
            };
        case "contract":
            value = web3_1.default.utils.toChecksumAddress(value);
            return {
                type: dataType,
                kind: "value",
                value: {
                    kind: "unknown",
                    address: value
                }
            };
        case "uint":
        case "int":
            if (bn_js_1.default.isBN(value)) {
                value = value.clone();
            }
            else {
                value = new bn_js_1.default(value);
            }
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBN: value
                }
            };
        case "bool":
            if (typeof value === "string") {
                value = value !== "false";
            }
            return {
                type: dataType,
                kind: "value",
                value: {
                    asBoolean: value
                }
            };
        case "enum":
            let name;
            let numeric;
            if (typeof value === "string" && !value.match(/^[0-9]*$/)) {
                //string case
                //first: let's strip off any type prefixes
                //(dangerous, I know! to be revised when this whole
                //function is)
                let splitName = value.split(".");
                name = splitName[splitName.length - 1];
                numeric = new bn_js_1.default(dataType.options.indexOf(name));
            }
            else {
                //numeric case
                if (bn_js_1.default.isBN(value)) {
                    numeric = value.clone();
                }
                else {
                    numeric = new bn_js_1.default(value);
                }
                name = dataType.options[numeric.toNumber()];
            }
            return {
                type: dataType,
                kind: "value",
                value: {
                    name,
                    numericAsBN: numeric
                }
            };
        //fixed and ufixed are not handled for now!
    }
}
exports.wrapElementaryValue = wrapElementaryValue;
//# sourceMappingURL=utils.js.map

/***/ }),

/***/ 771861:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const ENSJS = __webpack_require__(297442);
const contract = __webpack_require__(378883);
const { sha3 } = __webpack_require__(118269);
const { hash } = __webpack_require__(159873);

class ENS {
  constructor({ provider, ensSettings }) {
    this.ensSettings = ensSettings;
    this.provider = provider;
    this.devRegistry = null;
  }

  determineENSRegistryAddress() {
    if (this.ensSettings.registryAddress) {
      return this.ensSettings.registryAddress;
    } else if (
      this.ensjs &&
      this.ensjs.registryPromise._rejectionHandler0._address
    ) {
      return this.ensjs.registryPromise._rejectionHandler0._address;
    } else {
      const message =
        `Truffle could not locate the address of the ENS ` +
        `registry for the network you are using. You must either be on a` +
        `known network or a development blockchain.`;
      throw new Error(message);
    }
  }

  async deployNewDevENSRegistry(from) {
    const ENSRegistryArtifact = __webpack_require__(535842).ENSRegistry;
    const ENSRegistry = contract(ENSRegistryArtifact);
    ENSRegistry.setProvider(this.provider);
    const ensRegistry = await ENSRegistry.new({ from });
    this.ensSettings.registryAddress = ensRegistry.address;
    this.devRegistry = ensRegistry;
    this.setENSJS();
    return ensRegistry;
  }

  async ensureRegistryExists(from) {
    // See if registry exists on network by resolving an arbitrary address
    // If no registry exists then deploy one
    try {
      await this.ensjs.owner("0x0");
    } catch (error) {
      const noRegistryFound =
        error.message ===
        "This contract object doesn't have address set yet, please set an address first.";
      if (noRegistryFound) {
        await this.deployNewDevENSRegistry(from);
        this.setENSJS();
      } else {
        throw error;
      }
    }
  }

  async ensureResolverExists({ from, name }) {
    // See if the resolver is set, if not then set it
    let resolvedAddress, publicResolver;
    try {
      resolvedAddress = await this.ensjs.resolver(name).addr();
      return { resolvedAddress };
    } catch (error) {
      if (error.message !== "ENS name not found") throw error;
      const PublicResolverArtifact = __webpack_require__(298121).PublicResolver;
      const PublicResolver = contract(PublicResolverArtifact);
      PublicResolver.setProvider(this.provider);

      let registryAddress = this.determineENSRegistryAddress();

      publicResolver = await PublicResolver.new(registryAddress, { from });
      await this.ensjs.setResolver(name, publicResolver.address, { from });
      return { resolvedAddress: null };
    }
  }

  async setAddress(name, addressOrContract, { from }) {
    this.validateSetAddressInputs({ addressOrContract, name, from });
    const address = this.parseAddress(addressOrContract);
    this.setENSJS();
    await this.ensureRegistryExists(from);

    // In the case where there is a registry deployed by the user,
    // set permissions so that the resolver can be set by the user
    if (this.devRegistry) await this.setNameOwner({ from, name });

    // Find the owner of the name and compare it to the "from" field
    const nameOwner = await this.ensjs.owner(name);

    if (nameOwner !== from) {
      const message =
        `The default address or address provided in the "from" ` +
        `field for registering does not own the specified ENS name. The ` +
        `"from" field address must match the owner of the name.` +
        `\n> Failed to register ENS name ${name}` +
        `\n> Address in "from" field - ${from}` +
        `\n> Current owner of '${name}' - ${nameOwner}`;
      throw new Error(message);
    }

    const { resolvedAddress } = await this.ensureResolverExists({ from, name });
    // If the resolver points to a different address or is not set,
    // then set it to the specified address
    if (resolvedAddress !== address) {
      await this.ensjs.resolver(name).setAddr(address);
    }
  }

  async setNameOwner({ name, from }) {
    const nameLabels = name.split(".").reverse();

    // Set top-level name
    let builtName = nameLabels[0];
    await this.devRegistry.setSubnodeOwner("0x0", sha3(builtName), from, {
      from
    });

    // If name is only one label, stop here
    if (nameLabels.length === 1) return;

    for (const label of nameLabels.slice(1)) {
      await this.devRegistry.setSubnodeOwner(
        hash(builtName),
        sha3(label),
        from,
        { from }
      );
      builtName = label.concat(`.${builtName}`);
    }
  }

  parseAddress(addressOrContract) {
    if (typeof addressOrContract === "string") return addressOrContract;
    try {
      return addressOrContract.address;
    } catch (error) {
      const message =
        `You have not entered a valid address or contract ` +
        `object with an address property. Please ensure that you enter a ` +
        `valid address or pass in a valid artifact.`;
      throw new Error(message);
    }
  }

  validateSetAddressInputs({ addressOrContract, name, from }) {
    if (
      !addressOrContract ||
      !name ||
      !from ||
      (typeof addressOrContract !== "string" &&
        typeof addressOrContract !== "object") ||
      typeof name !== "string" ||
      typeof from !== "string"
    ) {
      const message =
        `The 'address', 'name', or 'from' parameter is invalid for ` +
        `the call to the setAddress function. Please ensure that you are ` +
        `passing valid values. The received input values were the ` +
        `following:\n   - address: ${addressOrContract}\n   - name: ${name}\n   - from: ` +
        `${from}\n`;
      throw new Error(message);
    }
  }

  setENSJS() {
    this.ensjs = new ENSJS(this.provider, this.ensSettings.registryAddress);
  }
}

module.exports = ENS;


/***/ }),

/***/ 400669:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const expect = __webpack_require__(139883);
const Emittery = __webpack_require__(148);
const DeferredChain = __webpack_require__(917162);
const Deployment = __webpack_require__(891432);
const link = __webpack_require__(813690);
const create = __webpack_require__(963218);
const ENS = __webpack_require__(771861);

class Deployer extends Deployment {
  constructor(options) {
    options = options || {};
    expect.options(options, ["provider", "networks", "network", "network_id"]);

    const emitter = new Emittery();
    super(emitter, options);

    this.emitter = emitter;
    this.chain = new DeferredChain();
    this.logger = options.logger || { log: function() {} };
    this.network = options.network;
    this.networks = options.networks;
    this.network_id = options.network_id;
    this.provider = options.provider;
    this.basePath = options.basePath || process.cwd();
    this.known_contracts = {};
    if (options.ens && options.ens.enabled) {
      this.ens = new ENS({
        provider: options.provider,
        ensSettings: options.ens
      });
    }

    (options.contracts || []).forEach(
      contract => (this.known_contracts[contract.contract_name] = contract)
    );
  }

  // Note: In all code below we overwrite this.chain every time .then() is used
  // in order to ensure proper error processing.
  start() {
    return this.chain.start();
  }

  link(library, destinations) {
    return this.queueOrExec(link(library, destinations, this));
  }

  deploy() {
    const args = Array.prototype.slice.call(arguments);
    const contract = args.shift();

    return this.queueOrExec(this.executeDeployment(contract, args, this));
  }

  new() {
    const args = Array.prototype.slice.call(arguments);
    const contract = args.shift();

    return this.queueOrExec(create(contract, args, this));
  }

  then(fn) {
    return this.queueOrExec(function() {
      return fn(this);
    });
  }

  queueOrExec(fn) {
    return this.chain.started == true
      ? new Promise(accept => accept()).then(fn)
      : this.chain.then(fn);
  }

  finish() {
    this.emitter.clearListeners();
    this.close();
  }
}

module.exports = Deployer;


/***/ }),

/***/ 813690:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var Linker = __webpack_require__(506227);

module.exports = function(library, destinations, deployer) {
  return async function() {
    await Linker.link(library, destinations, deployer);
  };
};


/***/ }),

/***/ 963218:
/***/ ((module) => {

module.exports = function(contract, args, deployer) {
  return async function() {
    deployer.logger.log("Creating new instance of " + contract.contract_name);
    // Evaluate any arguments if they're promises
    await Promise.all(args);
    return contract.new.apply(contract, args);
  };
};


/***/ }),

/***/ 917162:
/***/ ((module) => {

function DeferredChain() {
  var self = this;
  this.chain = new Promise(function(accept, reject) {
    self._accept = accept;
    self._reject = reject;
  });

  this.await = new Promise(function() {
    self._done = arguments[0];
    self._error = arguments[1];
  });
  this.started = false;
}

DeferredChain.prototype.then = function(fn) {
  var self = this;
  this.chain = this.chain.then(function() {
    var args = Array.prototype.slice.call(arguments);

    return fn.apply(null, args);
  });
  this.chain = this.chain.catch(function(e) {
    self._error(e);
  });

  return this;
};

DeferredChain.prototype.catch = function(fn) {
  this.chain = this.chain.catch(function() {
    var args = Array.prototype.slice.call(arguments);

    return fn.apply(null, args);
  });

  return this;
};

DeferredChain.prototype.start = function() {
  this.started = true;
  this.chain = this.chain.then(this._done);
  this._accept();
  return this.await;
};

module.exports = DeferredChain;


/***/ }),

/***/ 891432:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(615158)("deployer:deployment"); // eslint-disable-line no-unused-vars

/**
 * @class  Deployment
 */
class Deployment {
  /**
   * constructor
   * @param  {Object} emitter         async `Emittery` emitter
   * @param  {Number} confirmations   confirmations needed to resolve an instance
   */
  constructor(emitter, options) {
    const networkConfig = options.networks[options.network] || {};
    this.confirmations = options.confirmations || 0;
    this.timeoutBlocks = options.timeoutBlocks || 0;
    this.pollingInterval = networkConfig.deploymentPollingInterval || 4000;
    this.emitter = emitter;
    this.promiEventEmitters = [];
    this.confirmationsMap = {};
    this.blockPoll;
  }

  // ------------------------------------  Utils ---------------------------------------------------

  /**
   * Stub for future error code assignments on process.exit
   * @private
   * @param  {String} name contract name
   * @return {Number}      code to exit
   */
  _errors() {
    return `Migrations failure`;
  }

  /**
   * Helper to parse a deploy statement's overwrite option
   * @private
   * @param  {Arry}    args        arguments passed to deploy
   * @param  {Boolean} isDeployed  is contract deployed?
   * @return {Boolean}             true if overwrite is ok
   */
  _canOverwrite(args, isDeployed) {
    const lastArg = args[args.length - 1];
    const isObject = typeof lastArg === "object";

    const overwrite = isObject && isDeployed && lastArg.overwrite === false;

    isObject && delete lastArg.overwrite;
    return !overwrite;
  }

  /**
   * Gets arbitrary values from constructor params, if they exist.
   * @private
   * @param  {Array}              args constructor params
   * @return {Any|Undefined}      gas value
   */
  _extractFromArgs(args, key) {
    let value;

    args.forEach(arg => {
      const hasKey =
        !Array.isArray(arg) &&
        typeof arg === "object" &&
        Object.keys(arg).includes(key);

      if (hasKey) value = arg[key];
    });
    return value;
  }

  /**
   * Emits a `block` event on each new block heard. This polling is
   * meant to be cancelled immediately on resolution of the
   * contract instance or on error. (See stopBlockPolling)
   * @private
   * @param  {Object}    interfaceAdapter
   */
  async _startBlockPolling(interfaceAdapter) {
    const self = this;
    const startTime = new Date().getTime();

    let secondsWaited = 0;
    let blocksWaited = 0;
    let currentBlock = await interfaceAdapter.getBlockNumber();

    self.blockPoll = setInterval(async () => {
      const newBlock = await interfaceAdapter.getBlockNumber();

      blocksWaited = newBlock - currentBlock + blocksWaited;
      currentBlock = newBlock;
      secondsWaited = Math.floor((new Date().getTime() - startTime) / 1000);

      const eventArgs = {
        blockNumber: newBlock,
        blocksWaited: blocksWaited,
        secondsWaited: secondsWaited
      };

      await self.emitter.emit("block", eventArgs);
    }, self.pollingInterval);
  }

  /**
   * Clears the interval timer initiated by `startBlockPolling
   * @private
   */
  _stopBlockPolling() {
    clearInterval(this.blockPoll);
  }

  /**
   * Waits `n` blocks after a tx is mined, firing a pseudo
   * 'confirmation' event for each one.
   * @private
   * @param  {Number} blocksToWait
   * @param  {Object} receipt
   * @param  {Object} interfaceAdapter
   * @return {Promise}             Resolves after `blockToWait` blocks
   */
  async _waitBlocks(blocksToWait, state, interfaceAdapter) {
    const self = this;
    let currentBlock = await interfaceAdapter.getBlockNumber();

    return new Promise(accept => {
      let blocksHeard = 0;

      const poll = setInterval(async () => {
        const newBlock = await interfaceAdapter.getBlockNumber();

        if (newBlock > currentBlock) {
          blocksHeard = newBlock - currentBlock + blocksHeard;
          currentBlock = newBlock;

          const eventArgs = {
            contractName: state.contractName,
            receipt: state.receipt,
            num: blocksHeard,
            block: currentBlock
          };

          await self.emitter.emit("confirmation", eventArgs);
        }

        if (blocksHeard >= blocksToWait) {
          clearInterval(poll);
          accept();
        }
      }, self.pollingInterval);
    });
  }

  /**
   * Sanity checks catch-all:
   * Are we connected?
   * Is contract deployable?
   * @private
   * @param  {Object} contract TruffleContract
   * @return {Promise}         throws on error
   */
  async _preFlightCheck(contract) {
    // Check that contract is not array
    if (Array.isArray(contract)) {
      const message = await this.emitter.emit("error", {
        type: "noBatches",
        contract: null
      });

      throw new Error(message);
    }

    // Check bytecode
    if (contract.bytecode === "0x") {
      const message = await this.emitter.emit("error", {
        type: "noBytecode",
        contract: contract
      });

      throw new Error(message);
    }

    // Check network
    await contract.detectNetwork();
  }

  /**
   * Handler for contract's `transactionHash` event. Rebroadcasts as a deployer event
   * @private
   * @param  {Object} parent Deployment instance. Local `this` belongs to promievent
   * @param  {String} hash   tranactionHash
   */
  async _hashCb(parent, state, hash) {
    const eventArgs = {
      contractName: state.contractName,
      transactionHash: hash
    };
    state.transactionHash = hash;
    await parent.emitter.emit("transactionHash", eventArgs);
    this.removeListener("transactionHash", parent._hashCb);
  }

  /**
   * Handler for contract's `receipt` event. Rebroadcasts as a deployer event
   * @private
   * @param  {Object} parent  Deployment instance. Local `this` belongs to promievent
   * @param  {Object} state   store for the receipt value
   * @param  {Object} receipt
   */
  async _receiptCb(parent, state, receipt) {
    const eventArgs = {
      contractName: state.contractName,
      receipt: receipt
    };

    // We want this receipt available for the post-deploy event
    // so gas reporting is at hand there.
    state.receipt = receipt;
    await parent.emitter.emit("receipt", eventArgs);
    this.removeListener("receipt", parent._receiptCb);
  }

  // ----------------- Confirmations Handling (temporarily disabled) -------------------------------
  /**
   * There are outstanding issues at both geth (with websockets) & web3 (with confirmation handling
   * over RPC) that impair the confirmations handlers' reliability. In the interim we're using
   * simple block polling instead. (See also _confirmationCb )
   *
   * Queries the confirmations mapping periodically to see if we have
   * heard enough confirmations for a given tx to allow `deploy` to complete.
   * Resolves when this is true.
   *
   * @private
   * @param  {String} hash contract creation tx hash
   * @return {Promise}
   */
  async _waitForConfirmations(hash) {
    let interval;
    const self = this;

    return new Promise(accept => {
      interval = setInterval(() => {
        if (self.confirmationsMap[hash] >= self.confirmations) {
          clearInterval(interval);
          accept();
        }
      }, self.pollingInterval);
    });
  }

  /**
   * Handler for contract's `confirmation` event. Rebroadcasts as a deployer event
   * and maintains a table of txHashes & their current confirmation number. This
   * table gets polled if the user needs to wait a few blocks before getting
   * an instance back.
   * @private
   * @param  {Object} parent  Deployment instance. Local `this` belongs to promievent
   * @param  {Number} num     Confirmation number
   * @param  {Object} receipt transaction receipt
   */
  async _confirmationCb(parent, state, num, receipt) {
    const eventArgs = {
      contractName: state.contractName,
      num: num,
      receipt: receipt
    };

    parent.confirmationsMap[receipt.transactionHash] = num;
    await parent.emitter.emit("confirmation", eventArgs);
  }

  // ------------------------------------ Methods --------------------------------------------------
  /**
   *
   * @param  {Object} contract  Contract abstraction
   * @param  {Array}  args      Constructor arguments
   * @return {Promise}          Resolves an instance
   */
  executeDeployment(contract, args) {
    const self = this;

    return async function() {
      await self._preFlightCheck(contract);

      let instance;
      let eventArgs;
      let shouldDeploy = true;
      let state = {
        contractName: contract.contractName
      };

      const isDeployed = contract.isDeployed();
      const newArgs = await Promise.all(args);
      const currentBlock = await contract.interfaceAdapter.getBlock("latest");

      // Last arg can be an object that tells us not to overwrite.
      if (newArgs.length > 0) {
        shouldDeploy = self._canOverwrite(newArgs, isDeployed);
      }

      // Case: deploy:
      if (shouldDeploy) {
        /*
          Set timeout override. If this value is zero,
          @truffle/contract will defer to web3's defaults:
          - 50 blocks (websockets) OR 50 * 15sec (http)
        */
        contract.timeoutBlocks = self.timeoutBlocks;

        eventArgs = {
          state: state,
          contract: contract,
          deployed: isDeployed,
          blockLimit: currentBlock.gasLimit,
          gas: self._extractFromArgs(newArgs, "gas") || contract.defaults().gas,
          gasPrice:
            self._extractFromArgs(newArgs, "gasPrice") ||
            contract.defaults().gasPrice,
          from:
            self._extractFromArgs(newArgs, "from") || contract.defaults().from
        };

        // Get an estimate for previews / detect constructor revert
        // NB: web3 does not strip the revert msg here like it does for `deploy`
        try {
          eventArgs.estimate = await contract.new.estimateGas.apply(
            contract,
            newArgs
          );
        } catch (err) {
          eventArgs.estimateError = err;
        }

        // Emit `preDeploy` & send transaction
        await self.emitter.emit("preDeploy", eventArgs);
        const promiEvent = contract.new.apply(contract, newArgs);

        // Track emitters for cleanup on exit
        self.promiEventEmitters.push(promiEvent);

        // Subscribe to contract events / rebroadcast them to any reporters
        promiEvent
          .on("transactionHash", self._hashCb.bind(promiEvent, self, state))
          .on("receipt", self._receiptCb.bind(promiEvent, self, state));

        await self._startBlockPolling(contract.interfaceAdapter);

        // Get instance (or error)
        try {
          instance = await promiEvent;
          self._stopBlockPolling();
        } catch (err) {
          self._stopBlockPolling();
          eventArgs.error = err.error || err;
          let message = await self.emitter.emit("deployFailed", eventArgs);

          // Reporter might not be enabled (via Migrate.launchReporter) so
          // message is a (potentially empty) array of results from the emitter
          if (!message.length) {
            message = `while migrating ${contract.contractName}: ${
              eventArgs.error.message
            }`;
          }

          self.close();
          throw new Error(message);
        }

        // Case: already deployed
      } else {
        instance = await contract.deployed();
      }

      // Emit `postDeploy`
      eventArgs = {
        contract: contract,
        instance: instance,
        deployed: shouldDeploy,
        receipt: state.receipt
      };

      await self.emitter.emit("postDeploy", eventArgs);

      // Wait for `n` blocks
      if (self.confirmations !== 0 && shouldDeploy) {
        await self._waitBlocks(
          self.confirmations,
          state,
          contract.interfaceAdapter
        );
      }
      // Finish: Ensure the address and tx-hash are set on the contract.
      contract.address = instance.address;
      contract.transactionHash = instance.transactionHash;
      return instance;
    };
  }

  /**
   * Cleans up promiEvents' emitter listeners
   */
  close() {
    this.emitter.clearListeners();
    this.promiEventEmitters.forEach(item => {
      item.removeAllListeners();
    });
  }
}

module.exports = Deployment;


/***/ }),

/***/ 506227:
/***/ ((module) => {

module.exports = {
  link: async function(library, destinations, deployer) {
    let eventArgs;

    // Validate name
    if (library.contract_name == null) {
      eventArgs = {
        type: "noLibName"
      };

      const message = await deployer.emitter.emit("error", eventArgs);
      throw new Error(message);
    }

    // Validate address: don't want to use .address directly because it will throw.
    let hasAddress;

    typeof library.isDeployed
      ? (hasAddress = library.isDeployed())
      : (hasAddress = library.address != null);

    if (!hasAddress) {
      eventArgs = {
        type: "noLibAddress",
        contract: library
      };

      const message = await deployer.emitter.emit("error", eventArgs);
      throw new Error(message);
    }

    // Link all destinations
    if (!Array.isArray(destinations)) {
      destinations = [destinations];
    }

    for (let destination of destinations) {
      // Don't link if result will have no effect.
      const alreadyLinked =
        destination.links[library.contract_name] === library.address;
      const noLinkage =
        destination.unlinked_binary.indexOf(library.contract_name) < 0;

      if (alreadyLinked || noLinkage) continue;

      eventArgs = {
        libraryName: library.contractName,
        libraryAddress: library.address,
        contractName: destination.contractName,
        contractAddress: destination.contractAddress
      };

      await deployer.emitter.emit("linking", eventArgs);
      destination.link(library);
    }
  }
};


/***/ }),

/***/ 296412:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

"use strict";


const debug = __webpack_require__(255407)("external-compile");
const { exec, execSync } = __webpack_require__(63129);
const resolve = __webpack_require__(385622).resolve;
const { promisify } = __webpack_require__(431669);
const glob = promisify(__webpack_require__(312884));
const fs = __webpack_require__(935747);
const expect = __webpack_require__(139883);
const Schema = __webpack_require__(418370);
const web3Utils = __webpack_require__(118269);
const { Shims } = __webpack_require__(529833);
const Config = __webpack_require__(120553);

const DEFAULT_ABI = [
  {
    payable: true,
    stateMutability: "payable",
    type: "fallback"
  }
];

/**
 * buffer a line of data, yielding each full line
 *
 * returned generator alternates between two states:
 * 1. reset
 * 2. read/write
 *
 * usage:
 *
 *   let gen = bufferLines();
 *
 *   // first reset
 *   gen.next(); // reset
 *
 *   // pass string data with zero or more new lines
 *   // or pass `null` to signal EOF
 *   let { value, done } = gen.next(data);
 *
 *   // if done, value possibly contains string value with unterminated output
 *   // otherwise, value contains any/all complete lines
 */
function* bufferLines() {
  let buffer = [];

  while (true) {
    // read input string or null as eof
    const input = yield;

    // eof returns buffer
    if (input == null) {
      const unterminated = buffer.join("");

      return unterminated ? [`${unterminated}%`] : [];
    }

    // split lines
    // last element is always partial line
    const data = input.split("\n");

    // add first element to buffer
    let [first] = data.slice(0);
    buffer.push(first);

    if (data.length > 1) {
      // split off partial line to save as new buffer
      const [last] = data.slice(-1);
      const [...middle] = data.slice(1, -1);

      // use buffer as first element (now complete line)
      // and yield all complete lines
      const lines = [buffer.join(""), ...middle];
      yield lines;

      // reset buffer
      buffer = [last];
    } else {
      // nothing to see yet
      yield [];
    }
  }
}

/**
 * run a command, forwarding data to arbitrary logger.
 * invokes callback when process exits, error on nonzero exit code.
 */
const runCommand = promisify(function (command, options, callback) {
  const { cwd, logger, input } = options;
  const child = exec(command, { cwd, input });

  // wrap buffer generator for easy use
  const buffer = func => {
    const gen = bufferLines();

    return data => {
      gen.next();

      let { value: lines } = gen.next(data);
      for (let line of lines) {
        func(line);
      }
    };
  };

  const log = buffer(logger.log);
  const warn = buffer(logger.warn || logger.log);

  child.stdout.on("data", data => log(data.toString()));
  child.stderr.on("data", data => warn(data.toString()));

  child.on("close", function (code) {
    // close streams to flush unterminated lines
    log(null);
    warn(null);

    // If the command didn't exit properly, show the output and throw.
    if (code !== 0) {
      var err = new Error("Unknown exit code: " + code);
      return callback(err);
    }

    callback();
  });
});

/**
 * identify and process contents as one of:
 * 1. JSON literal
 * 2. Hex string
 * 3. Raw binary data
 */
function decodeContents(contents) {
  // JSON
  try {
    return JSON.parse(contents);
  } catch (e) {
    /* no-op */
  }

  // hex string
  if (contents.toString().startsWith("0x")) {
    return contents.toString();
  }

  // raw binary
  return web3Utils.bytesToHex(contents);
}

async function processTargets(targets, cwd, logger) {
  const contracts = [];
  for (let target of targets) {
    let targetContracts = await processTarget(target, cwd, logger);
    for (let contract of Object.values(targetContracts)) {
      contracts.push(Schema.validate(contract));
    }
  }

  return contracts;
}

async function processTarget(target, cwd, logger) {
  const usesPath = target.path != undefined;
  const usesCommand = target.command != undefined;
  const usesStdin = target.stdin || target.stdin == undefined; // default true
  const usesProperties = target.properties || target.fileProperties;

  if (usesProperties && usesPath) {
    throw new Error(
      "External compilation target cannot define both properties and path"
    );
  }

  if (usesProperties && usesCommand) {
    throw new Error(
      "External compilation target cannot define both properties and command"
    );
  }

  if (usesCommand && !usesPath) {
    // just run command
    const output = execSync(target.command, { cwd });
    const contract = JSON.parse(output);
    return { [contract.contractName]: contract };
  }

  if (usesPath && !glob.hasMagic(target.path)) {
    // individual file
    const filename = resolve(cwd, target.path);
    let input, command, execOptions;
    if (usesStdin) {
      input = fs.readFileSync(filename).toString();
      command = target.command;
      execOptions = { cwd, input };
    } else {
      command = `${target.command} ${filename}`;
      execOptions = { cwd };
    }

    const output = usesCommand ? execSync(command, execOptions) : input;

    const contract = JSON.parse(output);
    return { [contract.contractName]: contract };
  }

  if (usesPath && glob.hasMagic(target.path)) {
    // glob expression, recurse after expansion
    let paths = await glob(target.path, { cwd, follow: true });
    // copy target properties, overriding path with expanded form
    let targets = paths.map(path => Object.assign({}, target, { path }));
    return await processTargets(targets, cwd, logger);
  }

  if (usesProperties) {
    // contract properties listed individually
    const contract = Object.assign({}, target.properties || {});

    for (let [key, path] of Object.entries(target.fileProperties || {})) {
      const contents = fs.readFileSync(resolve(cwd, path));
      const value = decodeContents(contents);

      contract[key] = value;
    }

    if (!contract.contractName) {
      throw new Error("External compilation target must specify contractName");
    }

    if (!contract.abi) {
      contract.abi = DEFAULT_ABI;
    }

    if (!contract.bytecode && logger) {
      logger.log(
        "Warning: contract " +
          contract.contractName +
          " does not specify bytecode. You won't be able to deploy it."
      );
    }

    return { [contract.contractName]: contract };
  }
}

const Compile = {
  async all(options) {
    return await Compile.sources({
      // currently you cannot specify sources here
      sources: undefined,
      options
    });
  },

  async necessary(options) {
    return await Compile.sources({
      // currently you cannot specify sources here
      sources: undefined,
      options
    });
  },

  // compile-common defines object argument to include `sources`, but this is
  // unused as the user is responsible for dealing with compiling their sources
  async sources({ options }) {
    options = Config.default().merge(options);
    if (options.logger == null) {
      options.logger = console;
    }

    expect.options(options, ["compilers"]);
    expect.options(options.compilers, ["external"]);
    expect.options(options.compilers.external, ["command", "targets"]);

    const { command, targets } = options.compilers.external;
    const cwd =
      options.compilers.external.workingDirectory ||
      options.compilers.external.working_directory || // just in case
      options.working_directory;
    const logger = options.logger;

    debug("running compile command: %s", command);
    await runCommand(command, { cwd, logger });

    const contracts = await processTargets(targets, cwd, logger);
    return {
      compilations: [
        {
          contracts: contracts.map(Shims.LegacyToNew.forContract),
          // sourceIndexes is empty because we have no way of
          // knowing for certain the source paths for the contracts
          sourceIndexes: [],
          // since we don't know the sourcePaths, we can't really provide
          // the source info reliably
          sources: [],
          compiler: {
            name: "external",
            version: undefined
          }
        }
      ]
    };
  },

  async sourcesWithDependencies({ options }) {
    return await Compile.sources({ options });
  }
};

module.exports = {
  Compile,
  DEFAULT_ABI,
  processTarget
};


/***/ }),

/***/ 219798:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(615158)("migrate:Migration");
const path = __webpack_require__(385622);
const Deployer = __webpack_require__(400669);
const Require = __webpack_require__(868992);
const Emittery = __webpack_require__(148);
const {
  Web3Shim,
  createInterfaceAdapter
} = __webpack_require__(936339);

let Db;
try {
  Db = __webpack_require__(168060);
} catch {}

const ResolverIntercept = __webpack_require__(112715);

class Migration {
  constructor(file, reporter, config) {
    this.file = path.resolve(file);
    this.reporter = reporter;
    this.number = parseInt(path.basename(file));
    this.emitter = new Emittery();
    this.isFirst = false;
    this.isLast = false;
    this.dryRun = config.dryRun;
    this.interactive = config.interactive;
    this.config = config || {};
  }

  // ------------------------------------- Private -------------------------------------------------
  /**
   * Loads & validates migration, then runs it.
   * @param  {Object}   options  config and command-line
   * @param  {Object}   context  web3 & interfaceAdapter
   * @param  {Object}   deployer truffle module
   * @param  {Object}   resolver truffle module
   */
  async _load(options, context, deployer, resolver) {
    // Load assets and run `execute`
    const accounts = await context.interfaceAdapter.getAccounts();
    const requireOptions = {
      file: this.file,
      context: context,
      resolver: resolver,
      args: [deployer]
    };

    const fn = Require.file(requireOptions);

    const unRunnable = !fn || !fn.length || fn.length == 0;

    if (unRunnable) {
      const msg = `Migration ${this.file} invalid or does not take any parameters`;
      throw new Error(msg);
    }

    // `migrateFn` might be sync or async. We negotiate that difference in
    // `execute` through the deployer API.
    const migrateFn = fn(deployer, options.network, accounts);
    await this._deploy(options, deployer, resolver, migrateFn);
  }

  /**
   * Initiates deployer sequence, then manages migrations info
   * publication to chain / artifact saving.
   * @param  {Object}   options     config and command-line
   * @param  {Object}   deployer    truffle module
   * @param  {Object}   resolver    truffle module
   * @param  {[type]}   migrateFn   module.exports of a migrations.js
   */
  async _deploy(options, deployer, resolver, migrateFn) {
    try {
      await deployer.start();

      // Allow migrations method to be async and
      // deploy to use await
      if (migrateFn && migrateFn.then !== undefined) {
        await deployer.then(() => migrateFn);
      }

      // Migrate without saving
      if (options.save === false) return;

      let Migrations;

      // Attempt to write migrations record to chain
      try {
        Migrations = resolver.require("Migrations");
      } catch (error) {
        // do nothing, Migrations contract optional
      }

      if (Migrations && Migrations.isDeployed()) {
        const message = `Saving migration to chain.`;

        if (!this.dryRun) {
          const data = { message: message };
          await this.emitter.emit("startTransaction", data);
        }

        const migrations = await Migrations.deployed();
        const receipt = await migrations.setCompleted(this.number);

        if (!this.dryRun) {
          const data = { receipt: receipt, message: message };
          await this.emitter.emit("endTransaction", data);
        }
      }

      await this.emitter.emit("postMigrate", this.isLast);

      let artifacts = resolver
        .contracts()
        .map(abstraction => abstraction._json);
      if (
        Db &&
        this.config.db &&
        this.config.db.enabled &&
        artifacts.length > 0
      ) {
        const db = Db.connect(this.config.db);
        const project = await Db.Project.initialize({
          db,
          project: {
            directory: this.config.working_directory
          }
        });

        const result = await project
          .connect({ provider: this.config.provider })
          .loadMigrate({
            network: {
              name: this.config.network
            },
            artifacts
          });

        ({ artifacts } = result);

        await project.assignNames({
          assignments: {
            networks: [result.network]
          }
        });
      }

      // Save artifacts to local filesystem
      await options.artifactor.saveAll(artifacts);

      deployer.finish();

      // Cleanup
      if (this.isLast) {
        this.emitter.clearListeners();

        // Exiting w provider-engine appears to be hopeless. This hack on
        // our fork just swallows errors from eth-block-tracking
        // as we unwind the handlers downstream from here.
        if (this.config.provider && this.config.provider.engine) {
          this.config.provider.engine.silent = true;
        }
      }
    } catch (error) {
      const payload = {
        type: "migrateErr",
        error: error
      };

      await this.emitter.emit("error", payload);
      deployer.finish();
      throw error;
    }
  }

  // ------------------------------------- Public -------------------------------------------------
  /**
   * Instantiates a deployer, connects this migration and its deployer to the reporter
   * and launches a migration file's deployment sequence
   * @param  {Object}   options  config and command-line
   */
  async run(options) {
    const {
      interfaceAdapter,
      resolver,
      context,
      deployer
    } = this.prepareForMigrations(options);

    // Connect reporter to this migration
    if (this.reporter) {
      this.reporter.setMigration(this);
      this.reporter.setDeployer(deployer);
      this.reporter.confirmations = options.confirmations || 0;
      this.reporter.listen();
    }

    // Get file path and emit pre-migration event
    const file = path.relative(options.migrations_directory, this.file);
    const block = await interfaceAdapter.getBlock("latest");

    const preMigrationsData = {
      file: file,
      number: this.number,
      isFirst: this.isFirst,
      network: options.network,
      networkId: options.network_id,
      blockLimit: block.gasLimit
    };

    await this.emitter.emit("preMigrate", preMigrationsData);
    await this._load(options, context, deployer, resolver);
  }

  prepareForMigrations(options) {
    const logger = options.logger;
    const interfaceAdapter = createInterfaceAdapter({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });
    const web3 = new Web3Shim({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });

    const resolver = new ResolverIntercept(options.resolver);

    // Initial context.
    const context = { web3, interfaceAdapter, config: this.config };

    const deployer = new Deployer({
      logger,
      confirmations: options.confirmations,
      timeoutBlocks: options.timeoutBlocks,
      networks: options.networks,
      network: options.network,
      network_id: options.network_id,
      provider: options.provider,
      basePath: path.dirname(this.file),
      ens: options.ens
    });

    return { interfaceAdapter, resolver, context, deployer };
  }

  /**
   * Returns a serializable version of `this`
   * @returns  {Object}
   */
  serializeable() {
    return {
      file: this.file,
      number: this.number,
      isFirst: this.isFirst,
      isLast: this.isLast,
      dryRun: this.dryRun,
      interactive: this.interactive
    };
  }
}

module.exports = Migration;


/***/ }),

/***/ 112715:
/***/ ((module) => {

class ResolverIntercept {
  constructor(resolver) {
    this.resolver = resolver;
    this.cache = [];
  }

  require(contractName) {
    // remove file extension if present on name
    const sanitizedContractName = contractName
      .replace(/^\.\//, "")
      .replace(/\.sol$/i, "");

    // there may be more than one contract of the same name which will be
    // problematic - only return the first one found in the cache for now
    for (const contract of this.cache) {
      if (contract.contract_name === sanitizedContractName) {
        return contract;
      }
    }

    // Note, will error if nothing is found.
    const resolved = this.resolver.require(sanitizedContractName);

    this.cache.push(resolved);

    // During migrations, we could be on a network that takes a long time to accept
    // transactions (i.e., contract deployment close to block size). Because successful
    // migration is more important than wait time in those cases, we'll synchronize "forever".
    resolved.synchronization_timeout = 0;

    return resolved;
  }

  contracts() {
    return this.cache;
  }
}

module.exports = ResolverIntercept;


/***/ }),

/***/ 523459:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const fs = __webpack_require__(935747);
const path = __webpack_require__(385622);
const glob = __webpack_require__(312884);
const expect = __webpack_require__(139883);
const Config = __webpack_require__(120553);
const Reporter = __webpack_require__(895950).migrationsV5;
const Migration = __webpack_require__(219798);
const Emittery = __webpack_require__(148);

/**
 *  This API is consumed by `@truffle/core` at the `migrate` and `test` commands via
 *  the `.runMigrations` method.
 */
const Migrate = {
  Migration: Migration,
  reporter: null,
  emitter: new Emittery(),
  logger: null,

  launchReporter: function (config) {
    Migrate.reporter = new Reporter(config.describeJson || false);
    this.logger = config.logger;
  },

  acceptDryRun: async function () {
    return Migrate.reporter.acceptDryRun();
  },

  assemble: function (options) {
    const config = Config.detect(options);
    if (
      !fs.existsSync(config.migrations_directory) ||
      !fs.readdirSync(config.migrations_directory).length > 0
    ) {
      return [];
    }

    const migrationsDir = config.migrations_directory;
    const directoryContents = glob.sync(`${migrationsDir}${path.sep}*`);
    const files = directoryContents.filter(item => fs.statSync(item).isFile());

    if (files.length === 0) return [];

    let migrations = files
      .filter(file => isNaN(parseInt(path.basename(file))) === false)
      .filter(
        file =>
          path.extname(file).match(config.migrations_file_extension_regexp) !=
          null
      )
      .map(file => new Migration(file, Migrate.reporter, config));

    // Make sure to sort the prefixes as numbers and not strings.
    migrations = migrations.sort((a, b) => {
      if (a.number > b.number) return 1;
      if (a.number < b.number) return -1;
      return 0;
    });
    return migrations;
  },

  run: async function (options, callback) {
    const callbackPassed = typeof callback === "function";
    try {
      expect.options(options, [
        "working_directory",
        "migrations_directory",
        "contracts_build_directory",
        "provider",
        "artifactor",
        "resolver",
        "network",
        "network_id",
        "logger",
        "from", // address doing deployment
      ]);

      if (options.reset === true) {
        await this.runAll(options);
        if (callbackPassed) return callback();
        return;
      }

      const lastMigration = await this.lastCompletedMigration(options);

      // Don't rerun the last completed migration.
      await this.runFrom(lastMigration + 1, options);

      if (callbackPassed) return callback();
      return;
    } catch (error) {
      if (callbackPassed) return callback(error);
      throw error;
    }
  },

  runFrom: async function (number, options) {
    let migrations = this.assemble(options);

    while (migrations.length > 0) {
      if (migrations[0].number >= number) break;
      migrations.shift();
    }

    if (options.to) {
      migrations = migrations.filter(
        migration => migration.number <= options.to
      );
    }
    return await this.runMigrations(migrations, options);
  },

  runAll: async function (options) {
    return await this.runFrom(0, options);
  },

  runMigrations: async function (migrations, options) {
    // Perform a shallow clone of the options object
    // so that we can override the provider option without
    // changing the original options object passed in.
    const clone = {};

    Object.keys(options).forEach(key => (clone[key] = options[key]));

    if (options.quiet) clone.logger = { log: function () {} };

    clone.resolver = this.wrapResolver(options.resolver, clone.provider);

    // Make migrations aware of their position in sequence
    const total = migrations.length;
    if (total) {
      migrations[0].isFirst = true;
      migrations[total - 1].isLast = true;
    }

    if (this.reporter) {
      this.reporter.setMigrator(this);
      this.reporter.listenMigrator();
    }

    await this.emitter.emit("preAllMigrations", {
      dryRun: options.dryRun,
      migrations,
    });

    try {
      global.artifacts = clone.resolver;
      global.config = clone;
      for (const migration of migrations) {
        await migration.run(clone);
      }
      await this.emitter.emit("postAllMigrations", {
        dryRun: options.dryRun,
        error: null,
      });
      return;
    } catch (error) {
      await this.emitter.emit("postAllMigrations", {
        dryRun: options.dryRun,
        error: error.toString(),
      });
      throw error;
    } finally {
      delete global.artifacts;
      delete global.config;
    }
  },

  wrapResolver: function (resolver, provider) {
    return {
      require: function (import_path, search_path) {
        const abstraction = resolver.require(import_path, search_path);
        abstraction.setProvider(provider);
        return abstraction;
      },
      resolve: resolver.resolve,
    };
  },

  lastCompletedMigration: async function (options) {
    let Migrations;

    try {
      Migrations = options.resolver.require("Migrations");
    } catch (error) {
      // don't throw, Migrations contract optional
      return 0;
    }

    if (Migrations.isDeployed() === false) return 0;

    const migrationsOnChain = async migrationsAddress => {
      return (
        (await Migrations.interfaceAdapter.getCode(migrationsAddress)) !== "0x"
      );
    };

    // Two possible Migrations.sol's (lintable/unlintable)
    const lastCompletedMigration = migrationsInstance => {
      try {
        return migrationsInstance.last_completed_migration.call();
      } catch (error) {
        if (error instanceof TypeError)
          return migrationsInstance.lastCompletedMigration.call();
        throw new Error(error);
      }
    };

    const migrations = await Migrations.deployed();
    let completedMigration;
    if (await migrationsOnChain(migrations.address)) {
      completedMigration = await lastCompletedMigration(migrations);
    } else {
      completedMigration = 0;
    }
    return parseInt(completedMigration);
  },

  needsMigrating: function (options) {
    return new Promise((resolve, reject) => {
      if (options.reset === true) return resolve(true);

      return this.lastCompletedMigration(options)
        .then(number => {
          const migrations = this.assemble(options);
          while (migrations.length > 0) {
            if (migrations[0].number >= number) break;
            migrations.shift();
          }

          return resolve(
            migrations.length > 1 || (migrations.length && number === 0)
          );
        })
        .catch(error => reject(error));
    });
  },
};

module.exports = Migrate;


/***/ }),

/***/ 207702:
/***/ ((module) => {

"use strict";

const provision = (contractAbstraction, truffleConfig) => {
    if (truffleConfig.provider) {
        contractAbstraction.setProvider(truffleConfig.provider);
    }
    if (truffleConfig.network_id) {
        contractAbstraction.setNetwork(truffleConfig.network_id);
    }
    if (truffleConfig.network && truffleConfig.networks) {
        contractAbstraction.setNetworkType(truffleConfig.networks[truffleConfig.network].type);
        // this is a workaround to allow users to opt out of the block polling that
        // web3 performs when we listen for confirmations which causes problems in testing
        if (truffleConfig.networks[truffleConfig.network]) {
            const { disableConfirmationListener } = truffleConfig.networks[truffleConfig.network];
            contractAbstraction.disableConfirmationListener = disableConfirmationListener;
        }
    }
    contractAbstraction.ens = truffleConfig.ens;
    ["from", "gas", "gasPrice"].forEach(key => {
        if (truffleConfig[key]) {
            const obj = {};
            obj[key] = truffleConfig[key];
            contractAbstraction.defaults(obj);
        }
    });
    return contractAbstraction;
};
module.exports = provision;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 895950:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const migrationsV5 = __webpack_require__(494339);

module.exports = {
  migrationsV5: migrationsV5
};


/***/ }),

/***/ 555402:
/***/ ((module) => {

module.exports = {
  interval: 80,
  frames: [
    "   ⠋",
    "   ⠙",
    "   ⠹",
    "   ⠸",
    "   ⠼",
    "   ⠴",
    "   ⠦",
    "   ⠧",
    "   ⠇",
    "   ⠏"
  ]
};


/***/ }),

/***/ 998489:
/***/ ((module) => {

/**
 *  A module that formats output for the Migrations reporter.
 */
class MigrationsMessages {
  constructor(reporter) {
    this.reporter = reporter;
    this.describeJson = reporter.describeJson;
  }

  // ----------------------------------- Utilities -------------------------------------------------

  underline(msg) {
    return typeof msg === "number"
      ? `   ${"-".repeat(msg)}`
      : `\n   ${msg}\n   ${"-".repeat(msg.length)}`;
  }

  doubleline(msg) {
    const ul = "=".repeat(msg.length);
    return `\n${msg}\n${ul}`;
  }

  // Emoji alternative
  onMissing() {
    return "**";
  }

  migrationStatus(msg) {
    return `MIGRATION_STATUS:${JSON.stringify(msg)}`;
  }

  decAndHex(num) {
    return `${Number(num).toString(10)} (0x${Number(num).toString(16)})`;
  }

  // ----------------------------------- Interactions ----------------------------------------------

  questions(kind) {
    const prompt = " >> (y/n): ";
    const kinds = {
      acceptDryRun:
        `Dry-run successful. ` +
        `Do you want to proceed with real deployment? ${prompt}`
    };

    return kinds[kind];
  }

  exitLines(kind) {
    const kinds = {
      acceptDryRun: "\nExiting without migrating...\n\n"
    };

    return kinds[kind];
  }

  // ----------------------------------  Errors ----------------------------------------------------

  errors(kind, data) {
    const prefix = " *** Deployment Failed ***\n\n";

    const kinds = {
      migrateErr: () =>
        `\nExiting: Review successful transactions manually by checking the transaction hashes ` +
        `above on Etherscan.\n`,

      noLibName: () => `${prefix}Cannot link a library with no name.\n`,

      noLibAddress: () =>
        `${prefix}"${
          data.contract.contractName
        }" has no address. Has it been deployed?\n`,

      noBytecode: () =>
        `${prefix}"${data.contract.contractName}" ` +
        `is an abstract contract or an interface and cannot be deployed.\n` +
        `   * Import abstractions into the '.sol' file that uses them instead of deploying them separately.\n` +
        `   * Contracts that inherit an abstraction must implement all its method signatures exactly.\n` +
        `   * A contract that only implements part of an inherited abstraction is also considered abstract.\n`,

      noBatches: () =>
        `Support for batch deployments (array syntax) is deprecated. ` +
        `Please deploy each contract individually.`,

      intWithGas: () =>
        `${prefix}"${data.contract.contractName}" ran out of gas ` +
        `(using a value you set in your network config or deployment parameters.)\n` +
        `   * Block limit:  ${this.decAndHex(data.blockLimit)}\n` +
        `   * Gas sent:     ${this.decAndHex(data.gas)}\n`,

      intNoGas: () =>
        `${prefix}"${data.contract.contractName}" ran out of gas ` +
        `(using Truffle's estimate.)\n` +
        `   * Block limit:  ${this.decAndHex(data.blockLimit)}\n` +
        `   * Gas sent:     ${this.decAndHex(data.estimate)}\n` +
        `   * Try:\n` +
        `      + Setting a higher gas estimate multiplier for this contract\n` +
        `      + Using the solc optimizer settings in 'truffle-config.js'\n` +
        `      + Making your contract smaller\n` +
        `      + Making your contract constructor more efficient\n` +
        `      + Setting a higher network block limit if you are on a\n` +
        `        private network or test client (like ganache).\n`,

      oogNoGas: () =>
        `${prefix}"${
          data.contract.contractName
        }" ran out of gas. Something in the constructor ` +
        `(ex: infinite loop) caused gas estimation to fail. Try:\n` +
        `   * Making your contract constructor more efficient\n` +
        `   * Setting the gas manually in your config or as a deployment parameter\n` +
        `   * Using the solc optimizer settings in 'truffle-config.js'\n` +
        `   * Setting a higher network block limit if you are on a\n` +
        `     private network or test client (like ganache).\n`,

      rvtReason: () =>
        `${prefix}"${
          data.contract.contractName
        }" hit a require or revert statement ` +
        `with the following reason given:\n` +
        `   * ${data.reason}\n`,

      rvtNoReason: () =>
        `${prefix}"${
          data.contract.contractName
        }" hit a require or revert statement ` +
        `somewhere in its constructor. Try:\n` +
        `   * Verifying that your constructor params satisfy all require conditions.\n` +
        `   * Adding reason strings to your require statements.\n`,

      asrtNoReason: () =>
        `${prefix}"${
          data.contract.contractName
        }" hit an invalid opcode while deploying. Try:\n` +
        `   * Verifying that your constructor params satisfy all assert conditions.\n` +
        `   * Verifying your constructor code doesn't access an array out of bounds.\n` +
        `   * Adding reason strings to your assert statements.\n`,

      noMoney: () =>
        `${prefix}"${
          data.contract.contractName
        }" could not deploy due to insufficient funds\n` +
        `   * Account:  ${data.from}\n` +
        `   * Balance:  ${data.balance} wei\n` +
        `   * Message:  ${data.error.message}\n` +
        `   * Try:\n` +
        `      + Using an adequately funded account\n` +
        `      + If you are using a local Geth node, verify that your node is synced.\n`,

      blockWithGas: () =>
        `${prefix}"${data.contract.contractName}" exceeded the block limit ` +
        `(with a gas value you set).\n` +
        `   * Block limit:  ${this.decAndHex(data.blockLimit)}\n` +
        `   * Gas sent:     ${this.decAndHex(data.gas)}\n` +
        `   * Try:\n` +
        `      + Sending less gas.\n` +
        `      + Setting a higher network block limit if you are on a\n` +
        `        private network or test client (like ganache).\n`,

      blockNoGas: () =>
        `${prefix}"${data.contract.contractName}" exceeded the block limit ` +
        `(using Truffle's estimate).\n` +
        `   * Block limit: ${this.decAndHex(data.blockLimit)}\n` +
        `   * Report this error in the Truffle issues on Github. It should not happen.\n` +
        `   * Try: setting gas manually in 'truffle-config.js' or as parameter to 'deployer.deploy'\n`,

      nonce: () =>
        `${prefix}"${data.contract.contractName}" received: ${
          data.error.message
        }.\n` +
        `   * This error is common when Infura is under heavy network load.\n` +
        `   * Try: setting the 'confirmations' key in your network config\n` +
        `          to wait for several block confirmations between each deployment.\n`,

      geth: () =>
        `${prefix}"${
          data.contract.contractName
        }" received a generic error from Geth that\n` +
        `can be caused by hitting revert in a contract constructor or running out of gas.\n` +
        `   * ${data.estimateError.message}.\n` +
        `   * Try: + using the '--dry-run' option to reproduce this failure with clearer errors.\n` +
        `          + verifying that your gas is adequate for this deployment.\n`,

      default: () =>
        `${prefix}"${data.contract.contractName}" -- ${data.error.message}.\n`
    };

    return kinds[kind]();
  }

  // ----------------------------------  Steps ----------------------------------------------------

  steps(kind, data) {
    const self = this;
    const reporter = self.reporter;

    const kinds = {
      // Deployments
      deploying: () => {
        let output = "";

        if (self.describeJson) {
          output +=
            self.migrationStatus({
              status: "deploying",
              data: {
                contractName: data.contract.contractName
              }
            }) + "\n";
        }

        output += self.underline(`Deploying '${data.contract.contractName}'`);

        return output;
      },

      replacing: () => {
        let output = "";

        if (self.describeJson) {
          output +=
            self.migrationStatus({
              status: "replacing",
              data: {
                contractName: data.contract.contractName,
                priorAddress: data.contract.address
              }
            }) + "\n";
        }

        output += self.underline(`Replacing '${data.contract.contractName}'`);

        return output;
      },

      reusing: () => {
        let output = "";

        if (self.describeJson) {
          output +=
            self.migrationStatus({
              status: "reusing",
              data: {
                contractName: data.contract.contractName,
                address: data.contract.address
              }
            }) + "\n";
        }

        output +=
          self.underline(`Re-using deployed '${data.contract.contractName}'`) +
          "\n" +
          `   > ${"contract address:".padEnd(20)} ${data.contract.address}\n`;

        return output;
      },

      deployed: () => {
        if (reporter.blockSpinner) {
          reporter.blockSpinner.stop();
          const stopText = `   > ${reporter.currentBlockWait}`;
          reporter.deployer.logger.log(stopText);
        }

        let output = "";

        if (!reporter.migration.dryRun)
          output += `   > ${"contract address:".padEnd(20)} ${
            data.receipt.contractAddress
          }\n`;

        output += `   > ${"block number:".padEnd(20)} ${
          data.receipt.blockNumber
        }\n`;

        output += `   > ${"block timestamp:".padEnd(20)} ${data.timestamp}\n`;

        output +=
          `   > ${"account:".padEnd(20)} ${data.from}\n` +
          `   > ${"balance:".padEnd(20)} ${data.balance}\n` +
          `   > ${"gas used:".padEnd(20)} ${self.decAndHex(data.gas)}\n` +
          `   > ${"gas price:".padEnd(20)} ${data.gasPrice} gwei\n` +
          `   > ${"value sent:".padEnd(20)} ${data.value} ETH\n` +
          `   > ${"total cost:".padEnd(20)} ${data.cost} ETH\n`;

        if (reporter.confirmations !== 0)
          output += self.underline(
            `Pausing for ${reporter.confirmations} confirmations...`
          );

        if (this.describeJson) {
          output += self.migrationStatus({
            status: "deployed",
            data: Object.assign({}, data, {
              contract: {
                contractName: data.contract.contractName,
                address: data.receipt.contractAddress
              },
              instance: undefined,
              receipt: {
                transactionHash: data.receipt.transactionHash,
                gasUsed: data.receipt.gasUsed
              }
            })
          });
        }

        return output;
      },

      // Transactions
      endTransaction: () => {
        if (reporter.blockSpinner) reporter.blockSpinner.stop();

        return `   > ${data.message}`;
      },

      // Libraries
      linking: () => {
        let output =
          self.underline(`Linking`) +
          `\n   * Contract: ${data.contractName} <--> Library: ${
            data.libraryName
          } `;

        if (!reporter.migration.dryRun)
          output += `(at address: ${data.libraryAddress})`;

        return output;
      },

      // PromiEvents
      hash: () =>
        `   > ${"transaction hash:".padEnd(20)} ` + data.transactionHash,

      receipt: () => `   > ${"gas usage:".padEnd(20)} ` + data.gas,

      confirmation: () =>
        `   > ${"confirmation number:".padEnd(20)} ` +
        `${data.num} (block: ${data.block})`,

      // Migrator
      preAllMigrations: () => {
        let output = "";

        if (self.describeJson) {
          const migrations = data.migrations.map(migration =>
            migration.serializeable()
          );
          output += self.migrationStatus({
            status: "preAllMigrations",
            data: Object.assign({}, data, {
              migrations
            })
          });
        }

        return output;
      },

      postAllMigrations: () => {
        let output = "";

        if (self.describeJson) {
          output += self.migrationStatus({
            status: "postAllMigrations",
            data
          });
        }

        return output;
      },

      // Migrations
      preMigrate: () => {
        let output = "";
        if (self.describeJson) {
          output +=
            self.migrationStatus({
              status: "preMigrate",
              data
            }) + "\n";
        }

        output += self.doubleline(`${data.file}`);

        return output;
      },

      saving: () => `\n   * Saving migration`,

      firstMigrate: () => {
        let output = ``;

        reporter.migration.dryRun
          ? (output +=
              self.doubleline(`Migrations dry-run (simulation)`) + "\n")
          : (output += self.doubleline(`Starting migrations...`) + "\n");

        output +=
          `> Network name:    '${data.network}'\n` +
          `> Network id:      ${data.networkId}\n` +
          `> Block gas limit: ${self.decAndHex(data.blockLimit)}\n`;

        return output;
      },

      postMigrate: () => {
        let output = "";
        let deployments =
          reporter.summary[reporter.currentFileIndex].deployments;

        if (!reporter.migration.dryRun && deployments.length)
          output += `   > Saving artifacts\n`;

        output +=
          self.underline(37) +
          "\n" +
          `   > ${"Total cost:".padEnd(15)} ${data.cost.padStart(15)} ETH\n`;

        if (self.describeJson) {
          output +=
            "\n" +
            self.migrationStatus({
              status: "postMigrate",
              data
            }) +
            "\n";
        }

        return output;
      },

      lastMigrate: () => {
        let output = "";

        output +=
          self.doubleline("Summary") +
          "\n" +
          `> ${"Total deployments:".padEnd(20)} ${data.totalDeployments}\n` +
          `> ${"Final cost:".padEnd(20)} ${data.finalCost} ETH\n`;

        if (self.describeJson) {
          output +=
            "\n" +
            self.migrationStatus({
              status: "lastMigrate",
              data: {
                totalDeployments: data.totalDeployments,
                finalCost: data.finalCost
              }
            }) +
            "\n";
        }

        return output;
      },

      // Batch
      many: () => self.underline(`Deploying Batch`),

      listMany: () => `   * ${data.contractName}`
    };

    return kinds[kind]();
  }
}

module.exports = MigrationsMessages;


/***/ }),

/***/ 494339:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(615158)("reporters:migrations:reporter"); // eslint-disable-line no-unused-vars
const web3Utils = __webpack_require__(118269);
const readline = __webpack_require__(251058);
const ora = __webpack_require__(963395);

const indentedSpinner = __webpack_require__(555402);
const MigrationsMessages = __webpack_require__(998489);

/**
 *  Reporter consumed by a migrations sequence which iteself consumes a series of Migration and
 *  Deployer instances that emit both async `Emittery` events and conventional EventEmitter
 *  events (from Web3PromiEvent). This reporter is designed to track the execution of
 *  several migrations files in sequence and is analagous to the Mocha reporter in that:
 *
 *  test:: deployment
 *  suite:: deployer.start to deployer.finish
 *  test file:: migrations file
 *
 *  Each time a new migrations file loads, the reporter needs the following properties
 *  updated to reflect the current emitter source:
 *  + `this.migration`
 *  + `this.deployer`
 */
class Reporter {
  constructor(describeJson) {
    this.migrator = null;
    this.deployer = null;
    this.migration = null;
    this.currentGasTotal = new web3Utils.BN(0);
    this.currentCostTotal = new web3Utils.BN(0);
    this.finalCostTotal = new web3Utils.BN(0);
    this.deployments = 0;
    this.separator = "\n";
    this.summary = [];
    this.currentFileIndex = -1;
    this.blockSpinner = null;
    this.currentBlockWait = "";
    this.describeJson = describeJson;

    this.messages = new MigrationsMessages(this);
  }

  // ------------------------------------  Utilities -----------------------------------------------

  /**
   * Sets a Migrator instance to be the current master migrator events emitter source
   * @param {Migration} migrator
   */
  setMigrator(migrator) {
    this.migrator = migrator;
  }

  /**
   * Sets a Migration instance to be the current migrations events emitter source
   * @param {Migration} migration
   */
  setMigration(migration) {
    this.migration = migration;
  }

  /**
   * Sets a Deployer instance as the current deployer events emitter source
   * @param {Deployer} deployer
   */
  setDeployer(deployer) {
    this.deployer = deployer;
  }

  /**
   * Registers emitter handlers for the migrator
   */
  listenMigrator() {
    // Migrator
    if (this.migrator && this.migrator.emitter) {
      this.migrator.emitter.on(
        "preAllMigrations",
        this.preAllMigrations.bind(this)
      );
      this.migrator.emitter.on(
        "postAllMigrations",
        this.postAllMigrations.bind(this)
      );
    }
  }

  /**
   * Registers emitter handlers for a migration/deployment
   */
  listen() {
    // Migration
    if (this.migration && this.migration.emitter) {
      this.migration.emitter.on("preMigrate", this.preMigrate.bind(this));
      this.migration.emitter.on(
        "startTransaction",
        this.startTransaction.bind(this)
      );
      this.migration.emitter.on(
        "endTransaction",
        this.endTransaction.bind(this)
      );
      this.migration.emitter.on("postMigrate", this.postMigrate.bind(this));
      this.migration.emitter.on("error", this.error.bind(this));
    }

    // Deployment
    if (this.deployer && this.deployer.emitter) {
      this.deployer.emitter.on("preDeploy", this.preDeploy.bind(this));
      this.deployer.emitter.on("postDeploy", this.postDeploy.bind(this));
      this.deployer.emitter.on("deployFailed", this.deployFailed.bind(this));
      this.deployer.emitter.on("linking", this.linking.bind(this));
      this.deployer.emitter.on("error", this.error.bind(this));
      this.deployer.emitter.on("transactionHash", this.hash.bind(this));
      this.deployer.emitter.on("confirmation", this.confirmation.bind(this));
      this.deployer.emitter.on("block", this.block.bind(this));
      this.deployer.emitter.on(
        "startTransaction",
        this.startTransaction.bind(this)
      );
      this.deployer.emitter.on(
        "endTransaction",
        this.endTransaction.bind(this)
      );
    }
  }

  /**
   * Retrieves gas usage totals per migrations file / totals since the reporter
   * started running. Calling this method resets the gas counters for migrations totals
   */
  getTotals() {
    const gas = this.currentGasTotal.clone();
    const cost = web3Utils.fromWei(this.currentCostTotal, "ether");
    this.finalCostTotal = this.finalCostTotal.add(this.currentCostTotal);

    this.currentGasTotal = new web3Utils.BN(0);
    this.currentCostTotal = new web3Utils.BN(0);

    return {
      gas: gas.toString(10),
      cost: cost,
      finalCost: web3Utils.fromWei(this.finalCostTotal, "ether"),
      deployments: this.deployments.toString()
    };
  }

  /**
   * Queries the user for a true/false response and resolves the result.
   * @param  {String} type identifier the reporter consumes to format query
   * @return {Promise}
   */
  askBoolean(type) {
    const self = this;
    const question = this.messages.questions(type);
    const exitLine = this.messages.exitLines(type);

    // NB: We need direct access to a writeable stream here.
    // This ignores `quiet` - but we only use that mode for `truffle test`.
    const input = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    const affirmations = ["y", "yes", "YES", "Yes"];

    return new Promise(resolve => {
      input.question(question, answer => {
        if (affirmations.includes(answer.trim())) {
          input.close();
          return resolve(true);
        }

        input.close();
        self.deployer && self.deployer.logger.log(exitLine);
        resolve(false);
      });
    });
  }

  /**
   * Error dispatcher. Parses the error returned from web3 and outputs a more verbose error after
   * doing what it can to evaluate the failure context from data passed to it.
   * @param  {Object} data info collected during deployment attempt
   */
  async processDeploymentError(data) {
    const error = data.estimateError || data.error;

    data.reason = data.error ? data.error.reason : null;

    const errors = {
      ETH: error.message.includes("funds"),
      OOG: error.message.includes("out of gas"),
      INT:
        error.message.includes("base fee") ||
        error.message.includes("intrinsic"),
      RVT: error.message.includes("revert"),
      BLK: error.message.includes("block gas limit"),
      NCE: error.message.includes("nonce"),
      INV: error.message.includes("invalid opcode"),
      GTH: error.message.includes("always failing transaction")
    };

    let type = Object.keys(errors).find(key => errors[key]);

    switch (type) {
      // `Intrinsic gas too low`
      case "INT":
        return data.gas
          ? this.messages.errors("intWithGas", data)
          : this.messages.errors("intNoGas", data);

      // `Out of gas`
      case "OOG":
        return data.gas && !(data.gas === data.blockLimit)
          ? this.messages.errors("intWithGas", data)
          : this.messages.errors("oogNoGas", data);

      // `Revert`
      case "RVT":
        return data.reason
          ? this.messages.errors("rvtReason", data)
          : this.messages.errors("rvtNoReason", data);

      // `Invalid opcode`
      case "INV":
        return data.reason
          ? this.messages.errors("asrtReason", data)
          : this.messages.errors("asrtNoReason", data);

      // `Exceeds block limit`
      case "BLK":
        return data.gas
          ? this.messages.errors("blockWithGas", data)
          : this.messages.errors("blockNoGas", data);

      // `Insufficient funds`
      case "ETH":
        const balance = await data.contract.interfaceAdapter.getBalance(
          data.from
        );
        data.balance = balance.toString();
        return this.messages.errors("noMoney", data);

      // `Invalid nonce`
      case "NCE":
        return this.messages.errors("nonce", data);

      // Generic geth error
      case "GTH":
        return this.messages.errors("geth", data);

      default:
        return this.messages.errors("default", data);
    }
  }

  // ---------------------------- Interaction Handlers ---------------------------------------------

  async acceptDryRun() {
    return this.askBoolean("acceptDryRun");
  }

  // -------------------------  Migrator File Handlers --------------------------------------------

  /**
   * Run when before any migration has started
   * @param  {Object} data
   */
  async preAllMigrations(data) {
    const message = this.messages.steps("preAllMigrations", data);
    this.migrator.logger.log(message);
  }

  /**
   * Run after all migrations have finished
   * @param  {Object} data
   */
  async postAllMigrations(data) {
    const message = this.messages.steps("postAllMigrations", data);
    this.migrator.logger.log(message);
  }

  // -------------------------  Migration File Handlers --------------------------------------------

  /**
   * Run when a migrations file is loaded, before deployments begin
   * @param  {Object} data
   */
  async preMigrate(data) {
    let message;
    if (data.isFirst) {
      message = this.messages.steps("firstMigrate", data);
      this.deployer.logger.log(message);
    }

    this.summary.push({
      file: data.file,
      number: data.number,
      deployments: []
    });

    this.currentFileIndex++;

    message = this.messages.steps("preMigrate", data);
    this.deployer.logger.log(message);
  }

  /**
   * Run after a migrations file has completed and the migration has been saved.
   * @param  {Boolean} isLast  true if this the last file in the sequence.
   */
  async postMigrate(isLast) {
    let data = {};
    data.number = this.summary[this.currentFileIndex].number;
    data.cost = this.getTotals().cost;
    this.summary[this.currentFileIndex].totalCost = data.cost;

    let message = this.messages.steps("postMigrate", data);
    this.deployer.logger.log(message);

    if (isLast) {
      data.totalDeployments = this.getTotals().deployments;
      data.finalCost = this.getTotals().finalCost;

      this.summary.totalDeployments = data.totalDeployments;
      this.summary.finalCost = data.finalCost;

      message = this.messages.steps("lastMigrate", data);
      this.deployer.logger.log(message);
    }
  }

  // ----------------------------  Deployment Handlers --------------------------------------------

  /**
   * Runs after pre-flight estimate has executed, before the sendTx is attempted
   * @param  {Object} data
   */
  async preDeploy(data) {
    let message;
    data.deployed
      ? (message = this.messages.steps("replacing", data))
      : (message = this.messages.steps("deploying", data));

    !this.deployingMany && this.deployer.logger.log(message);
  }

  /**
   * Run at intervals after the sendTx has executed, before the deployment resolves
   * @param  {Object} data
   */
  async block(data) {
    this.currentBlockWait =
      `Blocks: ${data.blocksWaited}`.padEnd(21) +
      `Seconds: ${data.secondsWaited}`;
    if (this.blockSpinner) {
      this.blockSpinner.text = this.currentBlockWait;
    }
  }

  /**
   * Run after a deployment instance has resolved. This handler collects deployment cost
   * data and stores it a `summary` map so that it can later be replayed in an interactive
   * preview (e.g. dry-run --> real). Also passes this data to the messaging utility for
   * output formatting.
   * @param  {Object} data
   */
  async postDeploy(data) {
    let message;
    if (data.deployed) {
      const tx = await data.contract.interfaceAdapter.getTransaction(
        data.receipt.transactionHash
      );

      const block = await data.contract.interfaceAdapter.getBlock(
        data.receipt.blockNumber
      );

      // if geth returns null, try again!
      if (!block) return this.postDeploy(data);

      data.timestamp = block.timestamp;

      const balance = await data.contract.interfaceAdapter.getBalance(tx.from);

      const gasPrice = new web3Utils.BN(tx.gasPrice);
      const gas = new web3Utils.BN(data.receipt.gasUsed);
      const value = new web3Utils.BN(tx.value);
      const cost = gasPrice.mul(gas).add(value);

      data.gasPrice = web3Utils.fromWei(gasPrice, "gwei");
      data.gas = gas.toString(10);
      data.from = tx.from;
      data.value = web3Utils.fromWei(value, "ether");
      data.cost = web3Utils.fromWei(cost, "ether");
      data.balance = web3Utils.fromWei(balance, "ether");

      this.currentGasTotal = this.currentGasTotal.add(gas);
      this.currentCostTotal = this.currentCostTotal.add(cost);
      this.currentAddress = this.from;
      this.deployments++;

      if (this.summary[this.currentFileIndex]) {
        this.summary[this.currentFileIndex].deployments.push(data);
      }

      message = this.messages.steps("deployed", data);
    } else {
      message = this.messages.steps("reusing", data);
    }

    this.deployer.logger.log(message);
  }

  /**
   * Runs on deployment error. Forwards err to the error parser/dispatcher after shutting down
   * any `pending` UI.any `pending` UI. Returns the error message OR logs it out from the reporter
   * if data.log is true.
   * @param  {Object}  data  event args
   * @return {Promise}       resolves string error message
   */
  async deployFailed(data) {
    if (this.blockSpinner) {
      this.blockSpinner.stop();
    }

    const message = await this.processDeploymentError(data);

    return data.log ? this.deployer.logger.error(message) : message;
  }

  // --------------------------  Transaction Handlers  ------------------------------------------

  /**
   * Run on `startTransaction` event. This is fired by migrations on save
   * but could also be fired within a migrations script by a user.
   * @param  {Object} data
   */
  async startTransaction(data) {
    const message = data.message || "Starting unknown transaction...";
    this.deployer.logger.log();

    this.blockSpinner = new ora({
      text: message,
      spinner: indentedSpinner,
      color: "red"
    });

    this.blockSpinner.start();
  }

  /**
   * Run after a start transaction
   * @param  {Object} data
   */
  async endTransaction(data) {
    data.message = data.message || "Ending unknown transaction....";
    const message = this.messages.steps("endTransaction", data);
    this.deployer.logger.log(message);
  }

  // ----------------------------  Library Event Handlers ------------------------------------------
  linking(data) {
    let message = this.messages.steps("linking", data);
    this.deployer.logger.log(message);
  }

  // ----------------------------  PromiEvent Handlers --------------------------------------------

  /**
   * For misc error reporting that requires no context specific UI mgmt
   * @param  {Object} data
   */
  async error(data) {
    const message = this.messages.errors(data.type, data);

    return data.log ? this.deployer.logger.error(message) : message;
  }

  /**
   * Fired on Web3Promievent 'transactionHash' event. Begins running a UI
   * a block / time counter.
   * @param  {Object} data
   */
  async hash(data) {
    if (this.migration.dryRun) return;

    let message = this.messages.steps("hash", data);
    this.deployer.logger.log(message);

    this.currentBlockWait = `Blocks: 0`.padEnd(21) + `Seconds: 0`;

    this.blockSpinner = new ora({
      text: this.currentBlockWait,
      spinner: indentedSpinner,
      color: "red"
    });

    this.blockSpinner.start();
  }

  /**
   * Fired on Web3Promievent 'confirmation' event.
   * @param  {Object} data
   */
  async confirmation(data) {
    let message = this.messages.steps("confirmation", data);
    this.deployer.logger.log(message);
  }
}

module.exports = Reporter;


/***/ }),

/***/ 868992:
/***/ ((module, exports, __webpack_require__) => {

const fs = __webpack_require__(935747);
const path = __webpack_require__(385622);
const Module = __webpack_require__(132282);
const vm = __webpack_require__(492184);
const originalrequire = __webpack_require__(588277);
const expect = __webpack_require__(139883);
const {
  Web3Shim,
  createInterfaceAdapter
} = __webpack_require__(936339);
const Config = __webpack_require__(120553);

// options.file: path to file to execute. Must be a module that exports a function.
// options.args: arguments passed to the exported function within file. If a callback
//   is not included in args, exported function is treated as synchronous.
// options.context: Object containing any global variables you'd like set when this
//   function is run.
const Require = {
  file: function(options) {
    let source;
    const file = options.file;
    const config = options.config;

    expect.options(options, ["file"]);

    options = Config.default().with(options);

    source = fs.readFileSync(options.file, { encoding: "utf8" });

    // Modified from here: https://gist.github.com/anatoliychakkaev/1599423
    const m = new Module(file);

    // Provide all the globals listed here: https://nodejs.org/api/globals.html
    const context = {
      __dirname: path.dirname(file),
      __filename: file,
      Buffer,
      clearImmediate,
      clearInterval,
      clearTimeout,
      console,
      exports,
      global,
      process,
      setImmediate,
      setInterval,
      setTimeout,
      config,
      module: m,
      artifacts: options.resolver,
      require: pkgPath => {
        // Ugh. Simulate a full require function for the file.
        pkgPath = pkgPath.trim();

        // If absolute, just require.
        if (path.isAbsolute(pkgPath)) return originalrequire(pkgPath);

        // If relative, it's relative to the file.
        if (pkgPath[0] === ".") {
          return originalrequire(path.join(path.dirname(file), pkgPath));
        } else {
          // Not absolute, not relative, must be a globally or locally installed module.
          // Try local first.
          // Here we have to require from the node_modules directory directly.

          var moduleDir = path.dirname(file);
          while (true) {
            try {
              return originalrequire(
                path.join(moduleDir, "node_modules", pkgPath)
              );
            } catch (e) {}
            var oldModuleDir = moduleDir;
            moduleDir = path.join(moduleDir, "..");
            if (moduleDir === oldModuleDir) break;
          }

          // Try global, and let the error throw.
          return originalrequire(pkgPath);
        }
      }
    };

    // Now add contract names.
    Object.keys(options.context || {}).forEach(key => {
      context[key] = options.context[key];
    });

    const old_cwd = process.cwd();

    process.chdir(path.dirname(file));

    const script = vm.createScript(source, file);
    script.runInNewContext(context);

    process.chdir(old_cwd);

    return m.exports;
  },

  exec: function(options, done) {
    expect.options(options, [
      "contracts_build_directory",
      "file",
      "resolver",
      "provider",
      "network",
      "network_id"
    ]);

    const interfaceAdapter = createInterfaceAdapter({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });
    const web3 = new Web3Shim({
      provider: options.provider,
      networkType: options.networks[options.network].type
    });

    try {
      const fn = this.file({
        file: options.file,
        context: { web3, interfaceAdapter },
        resolver: options.resolver,
        config: options
      });
      fn(done);
    } catch (error) {
      done(error);
    }
  }
};

module.exports = Require;


/***/ }),

/***/ 648511:
/***/ ((module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Resolver = void 0;
const resolver_1 = __webpack_require__(629931);
Object.defineProperty(exports, "Resolver", ({ enumerable: true, get: function () { return resolver_1.Resolver; } }));
module.exports = resolver_1.Resolver;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 629931:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Resolver = void 0;
const debug_1 = __importDefault(__webpack_require__(227062));
const debug = debug_1.default("resolver");
const contract = __webpack_require__(378883);
const expect = __webpack_require__(139883);
const provision = __webpack_require__(207702);
const sources_1 = __webpack_require__(912493);
const defaultResolverOptions = {
    includeTruffleSources: false,
    translateJsonToSolidity: true,
    resolveVyperMoudles: false,
};
class Resolver {
    constructor(options, resolverOptions = {}) {
        expect.options(options, ["working_directory", "contracts_build_directory", "contracts_directory"]);
        resolverOptions = Object.assign(Object.assign({}, defaultResolverOptions), resolverOptions);
        const { includeTruffleSources, translateJsonToSolidity, resolveVyperModules } = resolverOptions;
        this.options = options;
        this.sources = [
            new sources_1.EthPMv1(options.working_directory),
            new sources_1.NPM(options.working_directory),
            new sources_1.GlobalNPM(),
            new sources_1.FS(options.working_directory, options.contracts_build_directory)
        ];
        if (includeTruffleSources) {
            this.sources.unshift(new sources_1.Truffle(options));
        }
        if (translateJsonToSolidity) {
            this.sources = [].concat(...this.sources.map(source => [new sources_1.ABI(source), source]));
        }
        if (resolveVyperModules) {
            this.sources = [new sources_1.Vyper(this.sources, options.contracts_directory)];
        }
    }
    // This function might be doing too much. If so, too bad (for now).
    require(import_path, search_path) {
        let abstraction;
        this.sources.forEach((source) => {
            const result = source.require(import_path, search_path);
            if (result) {
                abstraction = contract(result);
                provision(abstraction, this.options);
            }
        });
        if (abstraction)
            return abstraction;
        throw new Error("Could not find artifacts for " + import_path + " from any sources");
    }
    resolve(importPath, importedFrom) {
        return __awaiter(this, void 0, void 0, function* () {
            let body = null;
            let filePath = null;
            let source = null;
            for (source of this.sources) {
                ({ body, filePath } = yield source.resolve(importPath, importedFrom));
                if (body !== undefined) {
                    break;
                }
            }
            if (body === undefined) {
                let message = `Could not find ${importPath} from any sources`;
                if (importedFrom) {
                    message += "; imported from " + importedFrom;
                }
                throw new Error(message);
            }
            return {
                body,
                filePath,
                source
            };
        });
    }
}
exports.Resolver = Resolver;
//# sourceMappingURL=resolver.js.map

/***/ }),

/***/ 769136:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ABI = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const abi_to_sol_1 = __webpack_require__(276824);
class ABI {
    constructor(wrappedSource) {
        this.wrappedSource = wrappedSource;
    }
    // requiring artifacts is out of scope for this ResolverSource
    // just return `null` here and let another ResolverSource handle it
    require() {
        return null;
    }
    resolve(importPath, importedFrom = "") {
        return __awaiter(this, void 0, void 0, function* () {
            let filePath;
            let body;
            if (!importPath.endsWith(".json")) {
                return { filePath, body };
            }
            const resolution = yield this.wrappedSource.resolve(importPath, importedFrom);
            if (resolution.body === undefined) {
                return { filePath, body };
            }
            ({ filePath, body } = resolution);
            // extract basename twice to support .json and .abi.json
            const name = path_1.default.basename(path_1.default.basename(filePath, ".json"), ".abi");
            try {
                const abi = JSON.parse(body);
                const soliditySource = abi_to_sol_1.generateSolidity({
                    name,
                    abi,
                    license: "MIT" // as per the rest of Truffle
                });
                return {
                    filePath,
                    body: soliditySource
                };
            }
            catch (_) {
                //we use this not-quite-empty Solidity to avoid warnings
                //pragma statement introduced in 0.4.0 so can't go earlier
                //than that :)
                const emptySolidity = `
        // SPDX-License-Identifier: MIT
        pragma solidity >=0.4.0;
      `;
                return {
                    filePath,
                    body: emptySolidity
                };
            }
        });
    }
    resolveDependencyPath(importPath, dependencyPath) {
        return __awaiter(this, void 0, void 0, function* () {
            //just defer to wrapped source
            return yield this.wrappedSource.resolveDependencyPath(importPath, dependencyPath);
        });
    }
}
exports.ABI = ABI;
//# sourceMappingURL=abi.js.map

/***/ }),

/***/ 310680:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.EthPMv1 = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const fs_1 = __importDefault(__webpack_require__(935747));
class EthPMv1 {
    constructor(workingDirectory) {
        this.workingDirectory = workingDirectory;
    }
    require(importPath) {
        if (importPath.indexOf(".") === 0 || importPath.indexOf("/") === 0) {
            return null;
        }
        // Look to see if we've compiled our own version first.
        var contract_name = path_1.default.basename(importPath, ".sol");
        // We haven't compiled our own version. Assemble from data in the lockfile.
        var separator = importPath.indexOf("/");
        var package_name = importPath.substring(0, separator);
        var install_directory = path_1.default.join(this.workingDirectory, "installed_contracts");
        var lockfile = path_1.default.join(install_directory, package_name, "lock.json");
        try {
            lockfile = fs_1.default.readFileSync(lockfile, "utf8");
        }
        catch (e) {
            return null;
        }
        lockfile = JSON.parse(lockfile);
        // TODO: contracts that reference other types
        // TODO: contract types that specify a hash as their key
        // TODO: imported name doesn't match type but matches deployment name
        var contract_types = lockfile.contract_types || {};
        var type = contract_types[contract_name];
        // No contract name of the type asked.
        if (!type)
            return null;
        var json = {
            abi: type.abi,
            contract_name: contract_name,
            networks: {},
            unlinked_binary: type.bytecode
        };
        // Go through deployments and save all of them
        Object.keys(lockfile.deployments || {}).forEach(function (blockchain) {
            var deployments = lockfile.deployments[blockchain];
            Object.keys(deployments).forEach(function (name) {
                var deployment = deployments[name];
                if (deployment.contract_type === contract_name) {
                    json.networks[blockchain] = {
                        events: {},
                        links: {},
                        address: deployment.address
                    };
                }
            });
        });
        return json;
    }
    resolve(importPath) {
        return __awaiter(this, void 0, void 0, function* () {
            var separator = importPath.indexOf("/");
            var package_name = importPath.substring(0, separator);
            var internal_path = importPath.substring(separator + 1);
            var installDir = this.workingDirectory;
            // If nothing's found, body returns `undefined`
            var body;
            while (true) {
                var file_path = path_1.default.join(installDir, "installed_contracts", importPath);
                try {
                    body = fs_1.default.readFileSync(file_path, { encoding: "utf8" });
                    break;
                }
                catch (err) { }
                file_path = path_1.default.join(installDir, "installed_contracts", package_name, "contracts", internal_path);
                try {
                    body = fs_1.default.readFileSync(file_path, { encoding: "utf8" });
                    break;
                }
                catch (err) { }
                // Recurse outwards until impossible
                var oldInstallDir = installDir;
                installDir = path_1.default.join(installDir, "..");
                if (installDir === oldInstallDir) {
                    break;
                }
            }
            return { body, filePath: importPath };
        });
    }
    // We're resolving package paths to other package paths, not absolute paths.
    // This will ensure the source fetcher conintues to use the correct sources for packages.
    // i.e., if some_module/contracts/MyContract.sol imported "./AnotherContract.sol",
    // we're going to resolve it to some_module/contracts/AnotherContract.sol, ensuring
    // that when this path is evaluated this source is used again.
    resolveDependencyPath(importPath, dependencyPath) {
        if (!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))) {
            //if it's *not* a relative path, return it unchanged
            return dependencyPath;
        }
        var dirname = path_1.default.dirname(importPath);
        var resolved_dependency_path = path_1.default.join(dirname, dependencyPath);
        // Note: We use `path.join()` here to take care of path idiosyncrasies
        // like joining "something/" and "./something_else.sol". However, this makes
        // paths OS dependent, and on Windows, makes the separator "\". Solidity
        // needs the separator to be a forward slash. Let's massage that here.
        resolved_dependency_path = resolved_dependency_path.replace(/\\/g, "/");
        return resolved_dependency_path;
    }
}
exports.EthPMv1 = EthPMv1;
//# sourceMappingURL=ethpm-v1.js.map

/***/ }),

/***/ 303224:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FS = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const fs_1 = __importDefault(__webpack_require__(935747));
class FS {
    constructor(workingDirectory, contractsBuildDirectory) {
        this.workingDirectory = workingDirectory;
        this.contractsBuildDirectory = contractsBuildDirectory;
    }
    require(importPath, searchPath = this.contractsBuildDirectory) {
        const normalizedImportPath = path_1.default.normalize(importPath);
        const contractName = this.getContractName(normalizedImportPath, searchPath);
        // If we have an absolute path, only check the file if it's a child of the workingDirectory.
        if (path_1.default.isAbsolute(normalizedImportPath)) {
            if (normalizedImportPath.indexOf(this.workingDirectory) !== 0) {
                return null;
            }
        }
        try {
            const result = fs_1.default.readFileSync(path_1.default.join(searchPath, `${contractName}.json`), "utf8");
            return JSON.parse(result);
        }
        catch (e) {
            return null;
        }
    }
    getContractName(sourcePath, searchPath = this.contractsBuildDirectory) {
        const contractsBuildDirFiles = fs_1.default.readdirSync(searchPath);
        const filteredBuildArtifacts = contractsBuildDirFiles.filter((file) => file.match(".json") != null);
        for (const buildArtifact of filteredBuildArtifacts) {
            const artifact = JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(searchPath, buildArtifact)).toString());
            if (artifact.sourcePath === sourcePath) {
                return artifact.contractName;
            }
        }
        // fallback
        return path_1.default.basename(sourcePath, ".sol");
    }
    resolve(importPath, importedFrom) {
        return __awaiter(this, void 0, void 0, function* () {
            importedFrom = importedFrom || "";
            const possiblePaths = [
                importPath,
                path_1.default.join(path_1.default.dirname(importedFrom), importPath)
            ];
            let body, filePath;
            for (const possiblePath of possiblePaths) {
                try {
                    const resolvedSource = fs_1.default.readFileSync(possiblePath, {
                        encoding: "utf8"
                    });
                    body = resolvedSource;
                    filePath = possiblePath;
                    return { body, filePath };
                }
                catch (error) {
                    // do nothing
                }
            }
            return { body, filePath };
        });
    }
    // Here we're resolving from local files to local files, all absolute.
    resolveDependencyPath(importPath, dependencyPath) {
        if (!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))) {
            //if it's *not* a relative path, return it unchanged
            return dependencyPath;
        }
        const dirname = path_1.default.dirname(importPath);
        return path_1.default.resolve(path_1.default.join(dirname, dependencyPath));
    }
}
exports.FS = FS;
//# sourceMappingURL=fs.js.map

/***/ }),

/***/ 382776:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.GlobalNPM = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const fs_1 = __importDefault(__webpack_require__(935747));
const detectInstalled = __webpack_require__(409790);
const getInstalledPath = __webpack_require__(239975);
class GlobalNPM {
    require(importPath) {
        if (importPath.indexOf(".") === 0 || path_1.default.isAbsolute(importPath)) {
            return null;
        }
        const contractName = path_1.default.basename(importPath, ".sol");
        let [packageName] = importPath.split("/", 1);
        if (detectInstalled.sync(packageName)) {
            const regex = new RegExp(`/${packageName}$`);
            const globalPackagePath = getInstalledPath
                .getInstalledPathSync(packageName)
                .replace(regex, "");
            const result = this.resolveAndParse(globalPackagePath, packageName, contractName);
            // result is null if it fails to resolve
            if (result) {
                return result;
            }
        }
        return null;
    }
    resolveAndParse(basePath, packageName, contractName) {
        const packagePath = path_1.default.join(basePath, packageName);
        const subDirs = [`build${path_1.default.sep}contracts`, "build"];
        for (const subDir of subDirs) {
            const possiblePath = path_1.default.join(packagePath, subDir, `${contractName}.json`);
            try {
                const result = fs_1.default.readFileSync(possiblePath, "utf8");
                return JSON.parse(result);
            }
            catch (e) {
                continue;
            }
        }
        return null;
    }
    resolve(importPath) {
        return __awaiter(this, void 0, void 0, function* () {
            let [packageName] = importPath.split("/", 1);
            let body;
            if (detectInstalled.sync(packageName)) {
                const regex = new RegExp(`/${packageName}$`);
                const globalPackagePath = getInstalledPath
                    .getInstalledPathSync(packageName)
                    .replace(regex, "");
                const expectedPath = path_1.default.join(globalPackagePath, importPath);
                try {
                    body = fs_1.default.readFileSync(expectedPath, { encoding: "utf8" });
                }
                catch (err) { }
            }
            // If nothing's found, body returns `undefined`
            return { body, filePath: importPath };
        });
    }
    // We're resolving package paths to other package paths, not absolute paths.
    // This will ensure the source fetcher conintues to use the correct sources for packages.
    // i.e., if some_module/contracts/MyContract.sol imported "./AnotherContract.sol",
    // we're going to resolve it to some_module/contracts/AnotherContract.sol, ensuring
    // that when this path is evaluated this source is used again.
    resolveDependencyPath(importPath, dependencyPath) {
        if (!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))) {
            //if it's *not* a relative path, return it unchanged
            return dependencyPath;
        }
        var dirname = path_1.default.dirname(importPath);
        return path_1.default.join(dirname, dependencyPath);
    }
}
exports.GlobalNPM = GlobalNPM;
//# sourceMappingURL=globalnpm.js.map

/***/ }),

/***/ 912493:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Vyper = exports.ABI = exports.Truffle = exports.FS = exports.GlobalNPM = exports.NPM = exports.EthPMv1 = void 0;
var ethpm_v1_1 = __webpack_require__(310680);
Object.defineProperty(exports, "EthPMv1", ({ enumerable: true, get: function () { return ethpm_v1_1.EthPMv1; } }));
var npm_1 = __webpack_require__(48854);
Object.defineProperty(exports, "NPM", ({ enumerable: true, get: function () { return npm_1.NPM; } }));
var globalnpm_1 = __webpack_require__(382776);
Object.defineProperty(exports, "GlobalNPM", ({ enumerable: true, get: function () { return globalnpm_1.GlobalNPM; } }));
var fs_1 = __webpack_require__(303224);
Object.defineProperty(exports, "FS", ({ enumerable: true, get: function () { return fs_1.FS; } }));
var truffle_1 = __webpack_require__(203785);
Object.defineProperty(exports, "Truffle", ({ enumerable: true, get: function () { return truffle_1.Truffle; } }));
var abi_1 = __webpack_require__(769136);
Object.defineProperty(exports, "ABI", ({ enumerable: true, get: function () { return abi_1.ABI; } }));
var vyper_1 = __webpack_require__(404320);
Object.defineProperty(exports, "Vyper", ({ enumerable: true, get: function () { return vyper_1.Vyper; } }));
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 48854:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NPM = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const fs_1 = __importDefault(__webpack_require__(935747));
class NPM {
    constructor(workingDirectory) {
        this.workingDirectory = workingDirectory;
    }
    require(importPath, searchPath) {
        if (importPath.indexOf(".") === 0 || importPath.indexOf("/") === 0) {
            return null;
        }
        const contractName = path_1.default.basename(importPath, ".sol");
        const regex = new RegExp(`(.*)/${contractName}`);
        let packageName = "";
        const matched = regex.exec(importPath);
        if (matched) {
            packageName = matched[1];
        }
        // during testing a temp dir is passed as search path - we need to check the
        // working dir in case a built contract was not copied over to it
        for (const basePath of [searchPath, this.workingDirectory]) {
            if (!basePath) {
                continue;
            }
            const result = this.resolveAndParse(basePath, packageName, contractName);
            // result is null if it fails to resolve
            if (result) {
                return result;
            }
            continue;
        }
        return null;
    }
    resolve(import_path, _imported_from) {
        return __awaiter(this, void 0, void 0, function* () {
            // If nothing's found, body returns `undefined`
            var body;
            var modulesDir = this.workingDirectory;
            while (true) {
                var expected_path = path_1.default.join(modulesDir, "node_modules", import_path);
                try {
                    var body = fs_1.default.readFileSync(expected_path, { encoding: "utf8" });
                    break;
                }
                catch (err) { }
                // Recurse outwards until impossible
                var oldModulesDir = modulesDir;
                modulesDir = path_1.default.join(modulesDir, "..");
                if (modulesDir === oldModulesDir) {
                    break;
                }
            }
            return { body, filePath: import_path };
        });
    }
    resolveAndParse(basePath, packageName, contractName) {
        const packagePath = path_1.default.join(basePath, "node_modules", packageName);
        const subDirs = [`build${path_1.default.sep}contracts`, "build"];
        for (const subDir of subDirs) {
            const possiblePath = path_1.default.join(packagePath, subDir, `${contractName}.json`);
            try {
                const result = fs_1.default.readFileSync(possiblePath, "utf8");
                return JSON.parse(result);
            }
            catch (e) {
                continue;
            }
        }
        return null;
    }
    // We're resolving package paths to other package paths, not absolute paths.
    // This will ensure the source fetcher conintues to use the correct sources for packages.
    // i.e., if some_module/contracts/MyContract.sol imported "./AnotherContract.sol",
    // we're going to resolve it to some_module/contracts/AnotherContract.sol, ensuring
    // that when this path is evaluated this source is used again.
    resolveDependencyPath(importPath, dependencyPath) {
        if (!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))) {
            //if it's *not* a relative path, return it unchanged
            return dependencyPath;
        }
        var dirname = path_1.default.dirname(importPath);
        return path_1.default.join(dirname, dependencyPath);
    }
}
exports.NPM = NPM;
//# sourceMappingURL=npm.js.map

/***/ }),

/***/ 50794:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Deployed = void 0;
const web3Utils = __webpack_require__(118269);
const rangeUtils_1 = __importDefault(__webpack_require__(141016));
class Deployed {
    static makeSolidityDeployedAddressesLibrary(mapping, { solc: { version } }) {
        let source = "";
        source +=
            "//SPDX-License-Identifier: MIT\n" +
                "pragma solidity >= 0.4.15 < 0.9.0; \n\n library DeployedAddresses {" +
                "\n";
        for (let [name, address] of Object.entries(mapping)) {
            let body = "revert();";
            if (address) {
                address = Deployed.toChecksumAddress(address);
                body = "return payable(" + address + ");";
            }
            source +=
                "  function " +
                    name +
                    "() public pure returns (address payable) { " +
                    body +
                    " }";
            source += "\n";
        }
        source += "}";
        version = rangeUtils_1.default.resolveToRange(version);
        if (!rangeUtils_1.default.rangeContainsAtLeast(version, "0.5.0")) {
            //remove "payable"s in types if we're before 0.5.0
            source = source.replace(/address payable/g, "address");
        }
        if (!rangeUtils_1.default.rangeContainsAtLeast(version, "0.6.0")) {
            //remove "payable"s in conversions if we're before 0.6.0
            source = source.replace(/payable\((.*)\)/g, "$1");
        }
        return source;
    }
    // Pulled from ethereumjs-util, but I don't want all its dependencies at the moment.
    static toChecksumAddress(address) {
        address = address.toLowerCase().replace("0x", "");
        const hash = web3Utils.sha3(address).replace("0x", "");
        var ret = "0x";
        for (var i = 0; i < address.length; i++) {
            if (parseInt(hash[i], 16) >= 8) {
                ret += address[i].toUpperCase();
            }
            else {
                ret += address[i];
            }
        }
        return ret;
    }
}
exports.Deployed = Deployed;
//# sourceMappingURL=Deployed.js.map

/***/ }),

/***/ 203785:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Truffle = void 0;
const path_1 = __importDefault(__webpack_require__(385622));
const fs_extra_1 = __importDefault(__webpack_require__(655674));
const Deployed_1 = __webpack_require__(50794);
const contract_sources_1 = __importDefault(__webpack_require__(123542));
const contract = __webpack_require__(378883);
class Truffle {
    constructor(options) {
        this.options = options;
    }
    resolve(importPath) {
        return __awaiter(this, void 0, void 0, function* () {
            if (importPath === "truffle/DeployedAddresses.sol") {
                const sourceFiles = yield contract_sources_1.default(this.options.contracts_directory);
                const buildDirFiles = fs_extra_1.default.existsSync(this.options.contracts_build_directory)
                    ? fs_extra_1.default.readdirSync(this.options.contracts_build_directory)
                    : [];
                const abstractionFiles = buildDirFiles.filter(file => file.match(/^.*.json$/));
                const mapping = {};
                const blacklist = new Set(["Assert", "DeployedAddresses"]);
                // Ensure we have a mapping for source files and abstraction files
                // to prevent any compile errors in tests.
                sourceFiles.forEach((file) => {
                    // we need to account for .json and .abi.json files
                    const name = path_1.default.basename(path_1.default.basename(path_1.default.basename(file, ".sol"), ".json"), ".abi");
                    if (blacklist.has(name))
                        return;
                    mapping[name] = false;
                });
                abstractionFiles.forEach(file => {
                    const name = path_1.default.basename(file, ".json");
                    if (blacklist.has(name))
                        return;
                    mapping[name] = false;
                });
                const filesData = abstractionFiles.map(file => {
                    return fs_extra_1.default.readFileSync(path_1.default.join(this.options.contracts_build_directory, file), "utf8");
                });
                const addresses = filesData.map(data => {
                    const c = contract(JSON.parse(data));
                    c.setNetwork(this.options.network_id);
                    if (c.isDeployed())
                        return c.address;
                    return null;
                });
                addresses.forEach((address, i) => {
                    const name = path_1.default.basename(abstractionFiles[i], ".json");
                    if (blacklist.has(name))
                        return;
                    mapping[name] = address;
                });
                const addressSource = Deployed_1.Deployed.makeSolidityDeployedAddressesLibrary(mapping, this.options.compilers);
                return { body: addressSource, filePath: importPath };
            }
            const truffleLibraries = [
                "Assert",
                "AssertAddress",
                "AssertAddressArray",
                "AssertBalance",
                "AssertBool",
                "AssertBytes32",
                "AssertBytes32Array",
                "AssertGeneral",
                "AssertInt",
                "AssertIntArray",
                "AssertString",
                "AssertUint",
                "AssertUintArray",
                "SafeSend"
            ];
            for (const lib of truffleLibraries) {
                if (importPath === `truffle/${lib}.sol`) {
                    const actualImportPath = 
                    // @ts-ignore
                     true
                        ? path_1.default.resolve(path_1.default.join(__dirname, `${lib}.sol`))
                        : 0;
                    const body = fs_extra_1.default.readFileSync(actualImportPath, { encoding: "utf8" });
                    return { body, filePath: importPath };
                }
            }
            return { body: undefined, filePath: undefined };
        });
    }
    require() {
        // return null to let another source handle this behavior
        // (will be covered by FS source)
        return null;
    }
    resolveDependencyPath(_importPath, dependencyPath) {
        return dependencyPath;
    }
}
exports.Truffle = Truffle;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 404320:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.Vyper = void 0;
const debug_1 = __importDefault(__webpack_require__(227062));
const debug = debug_1.default("resolver:sources:vyper");
const path_1 = __importDefault(__webpack_require__(385622));
class Vyper {
    constructor(wrappedSources, contractsDirectory) {
        this.wrappedSources = wrappedSources;
        this.cache = {};
        this.contractsDirectory = contractsDirectory;
    }
    require() {
        //out of scope for this resolver source
        return null;
    }
    resolve(importModule, importedFrom) {
        return __awaiter(this, void 0, void 0, function* () {
            importedFrom = importedFrom || "";
            debug("importModule: %s", importModule);
            debug("importedFrom: %s", importedFrom);
            //attempt to just resolve as if it's a file path rather than Vyper module
            for (const source of this.wrappedSources) {
                const directlyResolvedSource = yield source.resolve(importModule, importedFrom);
                if (directlyResolvedSource.body !== undefined) {
                    debug("found directly");
                    return directlyResolvedSource;
                }
            }
            //otherwise, it's time for some Vyper module processing...
            //only attempt this if what we have looks like a Vyper module
            if (!importModule.match(/^[\w.]+$/)) {
                debug("clearly not a Vyper module");
                return { body: undefined, filePath: undefined };
            }
            const importPath = moduleToPath(importModule); //note: no file extension yet
            debug("importPath: %s", importPath);
            const explicitlyRelative = importModule[0] === "."; //note we check importModule,
            //not importPath, to make the check simpler (can just check if begins with "."
            //rather than "./" or "../")
            debug("explicitlyRelative: %o", explicitlyRelative);
            const possiblePathsMinusExtension = [];
            //first: check in local directory
            possiblePathsMinusExtension.push(path_1.default.join(path_1.default.dirname(importedFrom), importPath));
            if (!explicitlyRelative) {
                //next: check in contracts dir, if not explicitly relative
                possiblePathsMinusExtension.push(path_1.default.join(this.contractsDirectory, importPath));
                //finally: check wherever the resolver says to check
                possiblePathsMinusExtension.push(importPath);
            }
            const possibleExtensions = [".json", ".vy"]; //Vyper only expects these two
            //note: this puts all JSON before all Vyper, which is how we want it
            //(we do not want to try Vyper from any sources until JSON from all sources
            //has been checked)
            const possiblePaths = [].concat(...possibleExtensions.map(extension => possiblePathsMinusExtension.map(path => path + extension)));
            debug("possiblePaths: %O", possiblePaths);
            for (const possiblePath of possiblePaths) {
                debug("possiblePath: %s", possiblePath);
                let resolvedSource;
                if (possiblePath in this.cache) {
                    resolvedSource = this.cache[possiblePath];
                }
                else {
                    for (const source of this.wrappedSources) {
                        debug("source: %o", source);
                        resolvedSource = yield source.resolve(possiblePath, importedFrom);
                        if (resolvedSource.body !== undefined) {
                            debug("found via this source");
                            break;
                        }
                    }
                    this.cache[possiblePath] = resolvedSource; //yes, even failures are cached!
                }
                if (resolvedSource.body !== undefined) {
                    debug("found");
                    return resolvedSource;
                }
                debug("not found");
            }
            //if not found, return nothing
            return { body: undefined, filePath: undefined };
        });
    }
    resolveDependencyPath(importPath, dependencyPath) {
        return __awaiter(this, void 0, void 0, function* () {
            //unfortunately, for this sort of source to resolve a dependency path,
            //it's going to need to do a resolve :-/
            debug("importPath: %s", importPath);
            const resolved = yield this.resolve(dependencyPath, importPath);
            if (resolved) {
                return resolved.filePath;
            }
            else {
                return null;
            }
        });
    }
}
exports.Vyper = Vyper;
function moduleToPath(moduleName) {
    //first: get initial dot count by matching against regular expression for
    //initial dots, then taking captured group (note: regular expression
    //will always match so don't have to worry about null here) and taking
    //length
    const initialDotCount = moduleName.match(/^(\.*)/)[1].length;
    //then: change rest of dots to slashes
    const withoutInitialDots = moduleName.slice(initialDotCount);
    const pathWithoutDots = withoutInitialDots.replace(/\./g, path_1.default.sep);
    let initialDotPath;
    //then: interpret initial dots
    switch (initialDotCount) {
        case 0:
            initialDotPath = "";
            break;
        case 1:
            initialDotPath = "./";
            break;
        default:
            initialDotPath = "../".repeat(initialDotCount - 1);
            break;
    }
    //finally: combine
    return initialDotPath + pathWithoutDots;
}
//# sourceMappingURL=vyper.js.map

/***/ }),

/***/ 571103:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InvalidNetworkError = exports.removeLibraries = exports.makeTimer = exports.makeFilename = exports.networksById = void 0;
//these imports aren't actually necessary, but why not :)
const util_1 = __importDefault(__webpack_require__(431669));
const timers_1 = __webpack_require__(278213);
exports.networksById = {
    1: "mainnet",
    3: "ropsten",
    4: "rinkeby",
    5: "goerli",
    42: "kovan"
};
function makeFilename(name, extension = ".sol") {
    if (!name) {
        return "Contract" + extension;
    }
    if (name.endsWith(extension)) {
        return name;
    }
    else {
        return name + extension;
    }
}
exports.makeFilename = makeFilename;
exports.makeTimer = util_1.default.promisify(timers_1.setTimeout);
function removeLibraries(settings) {
    let copySettings = Object.assign({}, settings);
    delete copySettings.libraries;
    return copySettings;
}
exports.removeLibraries = removeLibraries;
class InvalidNetworkError extends Error {
    constructor(networkId, fetcherName) {
        super(`Invalid network ID ${networkId} for fetcher ${fetcherName}`);
        this.networkId = networkId;
        this.fetcherName = fetcherName;
        this.name = "InvalidNetworkError";
    }
}
exports.InvalidNetworkError = InvalidNetworkError;
//# sourceMappingURL=common.js.map

/***/ }),

/***/ 574578:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const debug_1 = __importDefault(__webpack_require__(48690));
const debug = debug_1.default("source-fetcher:etherscan");
// untyped import since no @types/web3-utils exists
const Web3Utils = __webpack_require__(118269);
const common_1 = __webpack_require__(571103);
const axios_1 = __importDefault(__webpack_require__(409669));
//this looks awkward but the TS docs actually suggest this :P
const EtherscanFetcher = class EtherscanFetcher {
    //then, afterwards, start a new timer.
    constructor(networkId, apiKey = "") {
        const networkName = common_1.networksById[networkId];
        const supportedNetworks = [
            "mainnet",
            "ropsten",
            "kovan",
            "rinkeby",
            "goerli"
        ];
        if (networkName === undefined || !supportedNetworks.includes(networkName)) {
            throw new common_1.InvalidNetworkError(networkId, "etherscan");
        }
        this.suffix = networkName === "mainnet" ? "" : `-${networkName}`;
        debug("apiKey: %s", apiKey);
        this.apiKey = apiKey;
        const baseDelay = this.apiKey ? 200 : 3000; //etherscan permits 5 requests/sec w/a key, 1/3sec w/o
        const safetyFactor = 1; //no safety factor atm
        this.delay = baseDelay * safetyFactor;
        this.ready = common_1.makeTimer(0); //at start, it's ready to go immediately
    }
    get fetcherName() {
        return "etherscan";
    }
    static get fetcherName() {
        return "etherscan";
    }
    static forNetworkId(id, options) {
        return __awaiter(this, void 0, void 0, function* () {
            debug("options: %O", options);
            return new EtherscanFetcher(id, options ? options.apiKey : "");
        });
    }
    fetchSourcesForAddress(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const response = yield this.getSuccessfulResponse(address);
            return EtherscanFetcher.processResult(response.result[0]);
        });
    }
    getSuccessfulResponse(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const allowedAttempts = 2; //for now, we'll just retry once if it fails
            let lastError;
            for (let attempt = 0; attempt < allowedAttempts; attempt++) {
                yield this.ready;
                const responsePromise = this.makeRequest(address);
                this.ready = common_1.makeTimer(this.delay);
                try {
                    return yield responsePromise;
                }
                catch (error) {
                    lastError = error;
                    //just go back to the top of the loop to retry
                }
            }
            //if we've made it this far with no successful response, just
            //throw the last error
            throw lastError;
        });
    }
    makeRequest(address) {
        return __awaiter(this, void 0, void 0, function* () {
            //not putting a try/catch around this; if it throws, we throw
            const response = yield axios_1.default.get(`https://api${this.suffix}.etherscan.io/api`, {
                params: {
                    module: "contract",
                    action: "getsourcecode",
                    address,
                    apikey: this.apiKey
                },
                responseType: "json"
            });
            if (response.data.status === "0") {
                throw new Error(response.data.result);
            }
            return response.data;
        });
    }
    static processResult(result) {
        //we have 5 cases here.
        //case 1: the address doesn't exist
        if (result.SourceCode === "" &&
            result.ABI === "Contract source code not verified") {
            return null;
        }
        //case 2: it's a Vyper contract
        if (result.CompilerVersion.startsWith("vyper:")) {
            return this.processVyperResult(result);
        }
        let multifileJson;
        try {
            //try to parse the source JSON.  if it succeeds,
            //we're in the multi-file case.
            multifileJson = JSON.parse(result.SourceCode);
        }
        catch (_) {
            //otherwise, we could be single-file or we could be full JSON.
            //for full JSON input, etherscan will stick an extra pair of braces around it
            if (result.SourceCode.startsWith("{") &&
                result.SourceCode.endsWith("}")) {
                const trimmedSource = result.SourceCode.slice(1).slice(0, -1); //remove braces
                let fullJson;
                try {
                    fullJson = JSON.parse(trimmedSource);
                }
                catch (_) {
                    //if it still doesn't parse, it's single-source I guess?
                    //(note: we shouldn't really end up here?)
                    debug("single-file input??");
                    return this.processSingleResult(result);
                }
                //case 5: full JSON input
                debug("json input");
                return this.processJsonResult(result, fullJson);
            }
            //case 3 (the way it should happen): single source
            debug("single-file input");
            return this.processSingleResult(result);
        }
        //case 4: multiple sources
        debug("multi-file input");
        return this.processMultiResult(result, multifileJson);
    }
    static processSingleResult(result) {
        const filename = common_1.makeFilename(result.ContractName);
        return {
            contractName: result.ContractName,
            sources: {
                [filename]: result.SourceCode
            },
            options: {
                language: "Solidity",
                version: result.CompilerVersion,
                settings: this.extractSettings(result),
                specializations: {
                    libraries: this.processLibraries(result.Library),
                    constructorArguments: result.ConstructorArguments
                }
            }
        };
    }
    static processMultiResult(result, sources) {
        return {
            contractName: result.ContractName,
            sources: this.processSources(sources),
            options: {
                language: "Solidity",
                version: result.CompilerVersion,
                settings: this.extractSettings(result),
                specializations: {
                    libraries: this.processLibraries(result.Library),
                    constructorArguments: result.ConstructorArguments
                }
            }
        };
    }
    static processJsonResult(result, jsonInput) {
        return {
            contractName: result.ContractName,
            sources: this.processSources(jsonInput.sources),
            options: {
                language: jsonInput.language,
                version: result.CompilerVersion,
                settings: common_1.removeLibraries(jsonInput.settings),
                specializations: {
                    libraries: jsonInput.settings.libraries,
                    constructorArguments: result.ConstructorArguments
                }
            }
        };
    }
    static processVyperResult(result) {
        const filename = common_1.makeFilename(result.ContractName, ".vy");
        //note: this means filename will always be Vyper_contract.vy
        return {
            sources: {
                [filename]: result.SourceCode
            },
            options: {
                language: "Vyper",
                version: result.CompilerVersion.replace(/^vyper:/, ""),
                settings: this.extractVyperSettings(result),
                specializations: {
                    constructorArguments: result.ConstructorArguments
                }
            }
        };
    }
    static processSources(sources) {
        return Object.assign({}, ...Object.entries(sources).map(([path, { content: source }]) => ({
            [common_1.makeFilename(path)]: source
        })));
    }
    static extractSettings(result) {
        const evmVersion = result.EVMVersion === "Default" ? undefined : result.EVMVersion;
        const optimizer = {
            enabled: result.OptimizationUsed === "1",
            runs: parseInt(result.Runs)
        };
        //old version got libraries here, but we don't actually want that!
        if (evmVersion !== undefined) {
            return {
                optimizer,
                evmVersion
            };
        }
        else {
            return {
                optimizer
            };
        }
    }
    static processLibraries(librariesString) {
        let libraries;
        if (librariesString === "") {
            libraries = {};
        }
        else {
            libraries = Object.assign({}, ...librariesString.split(";").map(pair => {
                const [name, address] = pair.split(":");
                return { [name]: Web3Utils.toChecksumAddress(address) };
            }));
        }
        return { "": libraries }; //empty string as key means it applies to all contracts
    }
    static extractVyperSettings(result) {
        const evmVersion = result.EVMVersion === "Default" ? undefined : result.EVMVersion;
        if (evmVersion !== undefined) {
            return { evmVersion };
        }
        else {
            return {};
        }
    }
};
exports.default = EtherscanFetcher;
//# sourceMappingURL=etherscan.js.map

/***/ }),

/***/ 887031:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.InvalidNetworkError = void 0;
const common_1 = __webpack_require__(571103);
Object.defineProperty(exports, "InvalidNetworkError", ({ enumerable: true, get: function () { return common_1.InvalidNetworkError; } }));
const etherscan_1 = __importDefault(__webpack_require__(574578));
const sourcify_1 = __importDefault(__webpack_require__(711284));
const Fetchers = [etherscan_1.default, sourcify_1.default];
exports.default = Fetchers;
//# sourceMappingURL=index.js.map

/***/ }),

/***/ 711284:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const debug_1 = __importDefault(__webpack_require__(48690));
const debug = debug_1.default("source-fetcher:sourcify");
const common_1 = __webpack_require__(571103);
const axios_1 = __importDefault(__webpack_require__(409669));
//this looks awkward but the TS docs actually suggest this :P
const SourcifyFetcher = class SourcifyFetcher {
    constructor(networkId) {
        //but may be in the future
        this.domain = "repo.sourcify.dev";
        this.networkId = networkId;
        this.networkName = common_1.networksById[networkId];
        const supportedNetworks = [
            "mainnet",
            "ropsten",
            "kovan",
            "rinkeby",
            "goerli"
        ];
        if (this.networkName === undefined ||
            !supportedNetworks.includes(this.networkName)) {
            throw new common_1.InvalidNetworkError(networkId, "sourcify");
        }
    }
    get fetcherName() {
        return "sourcify";
    }
    static get fetcherName() {
        return "sourcify";
    }
    static forNetworkId(id, _options) {
        return __awaiter(this, void 0, void 0, function* () {
            //in the future, we may add protocol and node options,
            //but these don't exist yet
            return new SourcifyFetcher(id);
        });
    }
    fetchSourcesForAddress(address) {
        return __awaiter(this, void 0, void 0, function* () {
            const metadata = yield this.getMetadata(address);
            debug("metadata: %O", metadata);
            if (!metadata) {
                debug("no metadata");
                return null;
            }
            let sources;
            if (metadata.language === "Solidity") {
                sources = Object.assign({}, ...(yield Promise.all(Object.entries(metadata.sources).map(([sourcePath, { content: source }]) => __awaiter(this, void 0, void 0, function* () {
                    return ({
                        [sourcePath]: source !== undefined
                            ? source //sourcify doesn't support this yet but they're planning it
                            : yield this.getSource(address, sourcePath)
                    });
                })))));
            }
            else {
                //don't bother attempting to fetch sources if it's Yul
                sources = {};
            }
            return {
                sources,
                options: {
                    language: metadata.language,
                    version: metadata.compiler.version,
                    settings: common_1.removeLibraries(metadata.settings),
                    specializations: {
                        libraries: metadata.settings.libraries
                    }
                }
            };
        });
    }
    getMetadata(address) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                return yield this.requestWithRetries({
                    url: `https://${this.domain}/contracts/full_match/${this.networkId}/${address}/metadata.json`,
                    method: "get",
                    responseType: "json"
                });
            }
            catch (error) {
                //is this a 404 error? if so just return null
                debug("error: %O", error);
                if (error.response.status === 404) {
                    return null;
                }
                //otherwise, we've got a problem; rethrow the error
                throw error;
            }
        });
    }
    getSource(address, sourcePath) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.requestWithRetries({
                url: `https://${this.domain}/contracts/full_match/${this.networkId}/${address}/sources/${sourcePath}`,
                responseType: "text",
                method: "get"
            });
        });
    }
    requestWithRetries(requestObject //sorry, trying to import the type properly ran into problems
    ) {
        return __awaiter(this, void 0, void 0, function* () {
            const allowedAttempts = 2; //for now, we'll just retry once if it fails
            let lastError;
            for (let attempt = 0; attempt < allowedAttempts; attempt++) {
                try {
                    const response = yield axios_1.default(requestObject);
                    return response.data;
                }
                catch (error) {
                    //check: is this a 404 error? if so give up
                    if (error.response.status === 404) {
                        throw error;
                    }
                    //otherwise, just go back to the top of the loop to retry
                    lastError = error;
                }
            }
            //if we've made it this far with no successful response, just
            //throw the last error
            throw lastError;
        });
    }
};
exports.default = SourcifyFetcher;
//# sourceMappingURL=sourcify.js.map

/***/ }),

/***/ 832731:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(656278)("source-map-utils");
const CodeUtils = __webpack_require__(908135);
const Codec = __webpack_require__(20102);
const Web3Utils = __webpack_require__(118269);
const jsonpointer = __webpack_require__(883573);
const IntervalTree = __webpack_require__(891501)/* .default */ .ZP;

var SourceMapUtils = {
  getCharacterOffsetToLineAndColumnMapping: function (source) {
    var mapping = [];

    source = source.split("");

    var line = 0;
    var column = 0;

    source.forEach(function (character) {
      if (character === "\n") {
        line += 1;
        column = -1;

        mapping.push({
          line: line,
          column: 0
        });
      } else {
        mapping.push({
          line: line,
          column: column
        });
      }

      column += 1;
    });

    return mapping;
  },

  getHumanReadableSourceMap: function (sourceMap) {
    const instructions = sourceMap.split(";");

    let processedInstruction = {
      start: 0,
      length: 0,
      file: 0
    }; //persists across instructions for when info doesn't change
    let processedSourceMap = [];

    //JS doesn't have scan, so we'll do this scan manually
    for (let instruction of instructions) {
      let splitInstruction = instruction.split(":");

      //note: if(splitInstruction[i]) checks both that there are
      //at least that many fields, and that that particular field
      //is nonempty

      if (splitInstruction[0]) {
        processedInstruction.start = parseInt(splitInstruction[0]);
      }

      if (splitInstruction[1]) {
        processedInstruction.length = parseInt(splitInstruction[1]);
      }

      if (splitInstruction[2]) {
        processedInstruction.file = parseInt(splitInstruction[2]);
      }

      if (splitInstruction[3]) {
        processedInstruction.jump = splitInstruction[3];
      }

      if (splitInstruction[4]) {
        processedInstruction.modifierDepth = parseInt(splitInstruction[4]);
      }

      //we need to clone before pushing so that the array won't contain a
      //bunch of copies of the same thing.  unfortunately, we don't have
      //babel here, so we need to clone a bit manually.
      let clonedProcessedInstruction = {
        start: processedInstruction.start,
        length: processedInstruction.length,
        file: processedInstruction.file,
        jump: processedInstruction.jump,
        modifierDepth: processedInstruction.modifierDepth
      };

      processedSourceMap.push(clonedProcessedInstruction);
    }

    return processedSourceMap;
  },

  //sources: array of text sources (must be in order!)
  //binary: raw binary to process.  should not have unresolved links.
  //sourceMap: a processed source map as output by getHumanReadableSourceMap above
  //we... attempt to muddle through.
  getProcessedInstructionsForBinary: function (sources, binary, sourceMap) {
    if (!sources || !binary) {
      return [];
    }
    debug("sourceMap: %O", sourceMap);

    let numInstructions;
    if (sourceMap) {
      numInstructions = sourceMap.length;
    }

    //because we might be dealing with a constructor with arguments, we do
    //*not* remove metadata manually
    let instructions = CodeUtils.parseCode(binary, numInstructions);

    if (!sourceMap) {
      // HACK
      // Let's create a source map to use since none exists. This source
      // map maps just as many ranges as there are instructions (or
      // possibly more), and marks them all as being Solidity-internal and
      // not jumps.
      sourceMap = new Array(instructions.length);
      sourceMap.fill({
        start: 0,
        length: 0,
        file: -1,
        jump: "-",
        modifierDepth: "0"
      });
    }

    const lineAndColumnMappings = sources.map(source =>
      SourceMapUtils.getCharacterOffsetToLineAndColumnMapping(source || "")
    );

    let primaryFile;
    if (sourceMap[0]) {
      primaryFile = sourceMap[0].file;
    }
    debug("primaryFile %o", primaryFile);

    return instructions
      .map((instruction, index) => {
        // lookup source map by index and add `index` property to
        // instruction
        //

        const instructionSourceMap = sourceMap[index] || {};

        instruction.index = index; //should be fine to modify this

        return {
          instruction,
          instructionSourceMap
        };
      })
      .map(({ instruction, instructionSourceMap }) => {
        // add source map information to instruction, or defaults

        //I think it is also OK to modify instruction here
        ({
          jump: instruction.jump,
          start: instruction.start = 0,
          length: instruction.length = 0,
          file: instruction.file = primaryFile,
          modifierDepth: instruction.modifierDepth = 0
        } = instructionSourceMap);
        if (instruction.start === -1 && instruction.length === -1) {
          instruction.start = 0;
          instruction.length = 0;
        }
        const lineAndColumnMapping =
          lineAndColumnMappings[instruction.file] || {};
        instruction.range = {
          start: lineAndColumnMapping[instruction.start] || {
            line: null,
            column: null
          },
          end: lineAndColumnMapping[instruction.start + instruction.length] || {
            line: null,
            column: null
          }
        };

        return instruction;
      });
  },

  //instructions: as output by the function above
  //asts: array of abstract syntax trees for the sources. must be in order!
  //overlapFunctions: an array of functions -- each one corresponding to the AST of the same index --
  //that, given a start index and a length, will search for all nodes in that AST overlapping the
  //given range, and will return an array of objects with fields node and pointer; node should
  //be the corresponding node, and pointer a jsonpointer to it (from the AST root)
  //compilationId: what it says.  the function will work fine without it.
  getFunctionsByProgramCounter: function (
    instructions,
    asts,
    overlapFunctions,
    compilationId
  ) {
    return Object.assign(
      {},
      ...instructions
        .filter(instruction => instruction.name === "JUMPDEST")
        .map(instruction => {
          debug("instruction %O", instruction);
          let sourceIndex = instruction.file;
          //first off, a special case: if the file is -1, check for designated
          //invalid and if it's not that give up
          //(designated invalid gets file -1 in some Solidity versions)
          if (sourceIndex === -1) {
            if (
              SourceMapUtils.isDesignatedInvalid(
                instructions.slice(instruction.index)
              )
            ) {
              //designated invalid, include it
              return {
                [instruction.pc]: {
                  isDesignatedInvalid: true
                }
              };
            } else {
              //not designated invalid, filter it out
              return {};
            }
          }
          //now we proceed with the normal case
          let findOverlappingRange = overlapFunctions[sourceIndex];
          let ast = asts[sourceIndex];
          if (!ast) {
            //if we can't get the ast... filter it out I guess
            return {};
          }
          let range = SourceMapUtils.getSourceRange(instruction);
          let { node, pointer } = SourceMapUtils.findRange(
            findOverlappingRange,
            range.start,
            range.length
          );
          if (!pointer) {
            node = ast;
          }
          if (!node || node.nodeType !== "FunctionDefinition") {
            //filter out JUMPDESTs that aren't function definitions...
            //except for the designated invalid function
            if (
              SourceMapUtils.isDesignatedInvalid(
                instructions.slice(instruction.index)
              )
            ) {
              //designated invalid, include it
              return {
                [instruction.pc]: {
                  isDesignatedInvalid: true
                }
              };
            } else {
              //not designated invalid, filter it out
              return {};
            }
          }
          //otherwise, we're good to go, so let's find the contract node and
          //put it all together
          //to get the contract node, we go up twice from the function node;
          //the path from one to the other should have a very specific form,
          //so this is easy
          let contractPointer = pointer.replace(/\/nodes\/\d+$/, "");
          let contractNode = jsonpointer.get(ast, contractPointer);
          if (contractNode.nodeType !== "ContractDefinition") {
            //if it's a free function, there is no contract pointer or contract node
            contractPointer = null;
            contractNode = null;
          }
          return {
            [instruction.pc]: {
              sourceIndex,
              compilationId,
              //note: we're assuming that functions in generated sources are never pointed to
              pointer,
              node,
              name: node.name,
              id: node.id,
              mutability: Codec.Ast.Utils.mutability(node),
              contractPointer,
              contractNode,
              contractName: contractNode ? contractNode.name : null,
              contractId: contractNode ? contractNode.id : null,
              contractKind: contractNode ? contractNode.contractKind : null,
              contractPayable: contractNode
                ? Codec.Ast.Utils.isContractPayable(contractNode)
                : null,
              isDesignatedInvalid: false
            }
          };
        })
    );
  },

  getSourceRange: function (instruction = {}) {
    return {
      start: instruction.start || 0,
      length: instruction.length || 0,
      lines: instruction.range || {
        start: {
          line: 0,
          column: 0
        },
        end: {
          line: 0,
          column: 0
        }
      }
    };
  },

  //findOverlappingRange should be as described above
  findRange: function (findOverlappingRange, sourceStart, sourceLength) {
    // find nodes that fully contain requested range,
    // return one with longest pointer
    // (note: returns { range, node, pointer }
    let sourceEnd = sourceStart + sourceLength;
    let pointerLength = pointer => (pointer.match(/\//g) || []).length; //counts number of slashes in ptr
    return findOverlappingRange(sourceStart, sourceLength)
      .filter(({ range }) => sourceStart >= range[0] && sourceEnd <= range[1])
      .reduce(
        (acc, cur) =>
          pointerLength(cur.pointer) >= pointerLength(acc.pointer) ? cur : acc,
        { pointer: "" }
      );
    //note we make sure to bias towards cur (the new value being compared) rather than acc (the old value)
    //so that we don't actually get {pointer: ""} as our result
  },

  //makes the overlap function for an AST
  makeOverlapFunction: function (ast) {
    let tree = new IntervalTree();
    let ranges = SourceMapUtils.rangeNodes(ast);
    for (let { range, node, pointer } of ranges) {
      let [start, end] = range;
      tree.insert(start, end, { range, node, pointer });
    }
    return (sourceStart, sourceLength) =>
      tree.search(sourceStart, sourceStart + sourceLength);
  },

  //for use by makeOverlapFunction
  rangeNodes: function (node, pointer = "") {
    if (node instanceof Array) {
      return [].concat(
        ...node.map((sub, i) =>
          SourceMapUtils.rangeNodes(sub, `${pointer}/${i}`)
        )
      );
    } else if (node instanceof Object) {
      let results = [];

      if (node.src !== undefined && node.nodeType !== undefined) {
        //don't add "pseudo-nodes" (i.e.: outside variable references
        //in assembly) with no nodeType
        results.push({ pointer, node, range: SourceMapUtils.getRange(node) });
      }

      return results.concat(
        ...Object.keys(node).map(key =>
          SourceMapUtils.rangeNodes(node[key], `${pointer}/${key}`)
        )
      );
    } else {
      return [];
    }
  },

  getRange: function (node) {
    // src: "<start>:<length>:<_>"
    // returns [start, end]
    let [start, length] = node.src
      .split(":")
      .slice(0, 2)
      .map(i => parseInt(i));

    return [start, start + length];
  },

  //takes an array of instructions (as returned by parseCode)
  //and asks: is the start of this instruction array the
  //start of a Solidity designated invalid function?
  //i.e. what an uninitialized internal function pointer jumps to?
  isDesignatedInvalid: function (instructions) {
    const oldSequence = [{ name: "JUMPDEST" }, { name: "INVALID" }];
    const panicSelector = Web3Utils.soliditySha3({
      type: "string",
      value: "Panic(uint256)"
    }).slice(0, 2 + 2 * Codec.Evm.Utils.SELECTOR_SIZE);
    const paddedSelector = panicSelector.padEnd(
      2 + 2 * Codec.Evm.Utils.WORD_SIZE,
      "00"
    );
    //we double and add 2 because we're using hex strings...
    const newSequence = [
      { name: "JUMPDEST" },
      { name: "PUSH32", pushData: paddedSelector },
      { name: "PUSH1", pushData: "0x00" },
      { name: "MSTORE" },
      { name: "PUSH1", pushData: "0x51" },
      { name: "PUSH1", pushData: "0x04" },
      { name: "MSTORE" },
      { name: "PUSH1", pushData: "0x24" },
      { name: "PUSH1", pushData: "0x00" },
      { name: "REVERT" }
    ];

    const checkAgainstTemplate = (instructions, template) => {
      for (let index = 0; index < template.length; index++) {
        const instruction = instructions[index];
        const comparison = template[index];
        if (!instruction || instruction.name !== comparison.name) {
          return false;
        }
        if (
          comparison.pushData &&
          instruction.pushData !== comparison.pushData
        ) {
          return false;
        }
      }
      return true;
    };

    return (
      checkAgainstTemplate(instructions, oldSequence) ||
      checkAgainstTemplate(instructions, newSequence)
    );
  }
};

module.exports = SourceMapUtils;


/***/ }),

/***/ 577135:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const debug = __webpack_require__(685373)("workflow-compile");
const fse = __webpack_require__(655674);
const { prepareConfig } = __webpack_require__(991671);
const { Shims } = __webpack_require__(529833);

const SUPPORTED_COMPILERS = {
  solc: __webpack_require__(611105).Compile,
  vyper: __webpack_require__(874269).Compile,
  external: __webpack_require__(296412).Compile
};

let Db;
try {
  Db = __webpack_require__(168060);
} catch {}

async function compile(config) {
  // determine compiler(s) to use
  //
  const compilers = config.compiler
    ? config.compiler === "none"
      ? []
      : [config.compiler]
    : Object.keys(config.compilers);

  // invoke compilers
  //
  const rawCompilations = await Promise.all(
    compilers.map(async name => {
      const Compile = SUPPORTED_COMPILERS[name];
      if (!Compile) throw new Error("Unsupported compiler: " + name);

      const compileMethod =
        config.all === true || config.compileAll === true
          ? Compile.all
          : Compile.necessary;

      return await compileMethod(config);
    })
  );

  // collect results - rawCompilations is CompilerResult[]
  // flatten the array and remove compilations without results
  const compilations = rawCompilations.reduce((a, compilerResult) => {
    compilerResult.compilations.forEach(compilation => {
      if (compilation.contracts.length > 0) {
        a = a.concat(compilation);
      }
    });
    return a;
  }, []);

  const contracts = compilations.reduce((a, compilation) => {
    return a.concat(compilation.contracts);
  }, []);

  const sources = compilations.reduce((a, compilation) => {
    return a.concat(compilation.sources);
  }, []);

  // return WorkflowCompileResult
  return { contracts, sources, compilations };
}

const WorkflowCompile = {
  async compile(options) {
    const config = prepareConfig(options);

    if (config.events) config.events.emit("compile:start");

    const { contracts, sources, compilations } = await compile(config);

    const compilers = compilations
      .reduce((a, compilation) => {
        return a.concat(compilation.compiler);
      }, [])
      .filter(compiler => compiler);

    if (contracts.length === 0 && config.events) {
      config.events.emit("compile:nothingToCompile");
    }

    if (config.events) {
      config.events.emit("compile:succeed", {
        contractsBuildDirectory: config.contracts_build_directory,
        compilers
      });
    }

    return {
      contracts,
      sources,
      compilations
    };
  },

  async compileAndSave(options) {
    const { contracts, sources, compilations } = await this.compile(options);

    return await this.save(options, { contracts, sources, compilations });
  },

  async save(options, { contracts, sources, compilations }) {
    const config = prepareConfig(options);

    await fse.ensureDir(config.contracts_build_directory);

    if (
      Db &&
      options.db &&
      options.db.enabled === true &&
      contracts.length > 0
    ) {
      debug("saving to @truffle/db");
      const db = Db.connect(config.db);
      const project = await Db.Project.initialize({
        db,
        project: {
          directory: config.working_directory
        }
      });
      ({ contracts, compilations } = await project.loadCompile({
        result: { contracts, sources, compilations }
      }));
    }

    const artifacts = contracts.map(Shims.NewToLegacy.forContract);
    await config.artifactor.saveAll(artifacts);

    return { contracts, sources, compilations };
  },

  async assignNames(options, { contracts }) {
    const config = prepareConfig(options);

    if (!Db || !config.db || !config.db.enabled || contracts.length === 0) {
      return;
    }

    const db = Db.connect(config.db);
    const project = await Db.Project.initialize({
      db,
      project: {
        directory: config.working_directory
      }
    });

    await project.assignNames({
      assignments: {
        contracts: contracts.map(({ db: { contract } }) => contract)
      }
    });
  }
};

module.exports = WorkflowCompile;


/***/ }),

/***/ 991671:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

const Config = __webpack_require__(120553);
const expect = __webpack_require__(139883);
const Resolver = __webpack_require__(648511);
const Artifactor = __webpack_require__(529463);

function prepareConfig(options) {
  expect.options(options, ["contracts_build_directory"]);

  expect.one(options, ["contracts_directory", "files"]);

  // Use a config object to ensure we get the default sources.
  const config = Config.default().merge(options);

  config.compilersInfo = {};

  if (!config.resolver) config.resolver = new Resolver(config);

  if (!config.artifactor) {
    config.artifactor = new Artifactor(config.contracts_build_directory);
  }

  return config;
}

function multiPromisify(func) {
  return (...args) =>
    new Promise((accept, reject) => {
      const callback = (err, ...results) => {
        if (err) reject(err);

        accept(results);
      };

      func(...args, callback);
    });
}

module.exports = {
  prepareConfig,
  multiPromisify,
};


/***/ })

};
;
//# sourceMappingURL=459.bundled.js.map