truffle
Version:
Truffle - Simple development framework for Ethereum
1,703 lines (1,501 loc) • 199 kB
JavaScript
#!/usr/bin/env node
exports.id = 3077;
exports.ids = [3077];
exports.modules = {
/***/ 26291:
/***/ ((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 = 26291;
module.exports = webpackEmptyContext;
/***/ }),
/***/ 29463:
/***/ (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__(67078));
const fs_extra_1 = __importDefault(__webpack_require__(55674));
const path_1 = __importDefault(__webpack_require__(71017));
const os_1 = __importDefault(__webpack_require__(22037));
const utils_1 = __webpack_require__(42061);
const debug = __webpack_require__(15158)("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 = (0, utils_1.finalizeArtifact)(normalizedExistingArtifact, normalizedNewArtifact);
(0, utils_1.writeArtifact)(completeArtifact, outputPath);
}
catch (e) {
// if artifact doesn't already exist, write new file
if (e.code === "ENOENT")
return (0, 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 => {
const contractName = artifactObj.contract_name || artifactObj.contractName;
if (newArtifactObjects[contractName]) {
console.warn(`${os_1.default.EOL}> Duplicate contract names found for ${contractName}.${os_1.default.EOL}` +
`> This can cause errors and unknown behavior. Please rename one of your contracts.`);
}
newArtifactObjects[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
/***/ }),
/***/ 42061:
/***/ (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__(55674));
const merge_1 = __importDefault(__webpack_require__(82492));
const assign_1 = __importDefault(__webpack_require__(28583));
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 = (0, merge_1.default)({}, normalizedExistingArtifact.networks, normalizedNewArtifact.networks);
const completeArtifact = (0, assign_1.default)({}, normalizedExistingArtifact, normalizedNewArtifact, { networks: knownNetworks });
return completeArtifact;
}
exports.finalizeArtifact = finalizeArtifact;
//# sourceMappingURL=utils.js.map
/***/ }),
/***/ 86317:
/***/ ((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
/***/ }),
/***/ 67078:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
var pkgVersion = (__webpack_require__(23373)/* .version */ .i8);
var Ajv = __webpack_require__(65096);
var util = __webpack_require__(73837);
var contractObjectSchema = __webpack_require__(85351);
var networkObjectSchema = __webpack_require__(53245);
var abiSchema = __webpack_require__(900);
/**
* 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: {},
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;
/***/ }),
/***/ 78883:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const Schema = __webpack_require__(67078);
const Contract = __webpack_require__(7974);
const truffleContractVersion = (__webpack_require__(54720)/* .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;
/***/ }),
/***/ 85210:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const execute = __webpack_require__(41441);
const debug = __webpack_require__(15158)("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}))
)
}))
);
}
/***/ }),
/***/ 2629:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const {
Web3Shim,
createInterfaceAdapter
} = __webpack_require__(36339);
const utils = __webpack_require__(13735);
const execute = __webpack_require__(41441);
const bootstrap = __webpack_require__(85210);
const debug = __webpack_require__(15158)("contract:contract:constructorMethods");
const OS = __webpack_require__(22037);
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() {
// guard interfaceAdapter!
if (this.interfaceAdapter == null) {
throw new Error("Provider not set or invalid");
}
// 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
});
/***/ }),
/***/ 7974:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/* module decorator */ module = __webpack_require__.nmd(module);
const debug = __webpack_require__(15158)("contract:contract");
let Web3 = __webpack_require__(3283);
const webUtils = __webpack_require__(18269);
const execute = __webpack_require__(41441);
const bootstrap = __webpack_require__(85210);
const constructorMethods = __webpack_require__(2629);
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;
}
});
// instance.{sendTransaction, estimateGas, call, send}
instance.sendTransaction = execute.send.call(
constructor,
null,
null,
instance.address
);
instance.estimateGas = execute.estimate.call(
constructor,
null,
null,
instance.address
);
// Prefer user defined `call`
if (!instance.call) {
instance.call = execute.call.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__(13735);
const web3Utils = __webpack_require__(18269);
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", "BigInt"];
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;
}
}
};
/***/ }),
/***/ 41441:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
const debug = __webpack_require__(15158)("contract:execute");
const PromiEvent = __webpack_require__(20302);
const EventEmitter = __webpack_require__(82361);
const utils = __webpack_require__(13735);
const StatusError = __webpack_require__(60550);
const Reason = __webpack_require__(12630);
const handlers = __webpack_require__(99198);
const override = __webpack_require__(47009);
const reformat = __webpack_require__(90908);
const { sendTransactionManual } = __webpack_require__(95945);
const execute = {
// ----------------------------------- Helpers --------------------------------------------------
/**
* Retrieves gas estimate multiplied by the set gas multiplier for a `sendTransaction` call.
* Lacking an estimate, sets gas to have of latest blockLimit
* @param {Object} params `sendTransaction` parameters
* @param {Number} blockLimit most recent network block.blockLimit
* @return {Number} gas estimate
*/
getGasEstimate: function (params, blockLimit, stacktrace = false) {
const constructor = this;
const interfaceAdapter = constructor.interfaceAdapter;
const web3 = constructor.web3;
return new Promise(function (accept, reject) {
// Always prefer gas specified by user (if a user sets gas to 0, that is treated
// as undefined here and we do proceed to do gas estimation)
if (params.gas) return accept(params.gas);
if (!constructor.autoGas) return accept();
interfaceAdapter
.estimateGas(params, stacktrace)
.then(gas => {
// there are situations where the web3 gas estimation function in interfaceAdapter
// fails, specifically when a transaction will revert; we still want to continue
// the user flow for debugging purposes if the user has enabled stacktraces; so we provide a
// default gas for that situation, equal to half of the blockLimit for the latest block
//
// note: this means if a transaction will revert but the user does not have stacktracing enabled,
// they will get an error from the gas estimation and be unable to proceed; we may need to revisit this
if (gas === null) {
const defaultGas = utils.bigNumberify(Math.floor(blockLimit / 2));
accept(defaultGas.toHexString());
} else {
const limit = utils.bigNumberify(blockLimit);
// if we did get a numerical gas estimate from interfaceAdapter, we
// multiply that estimate by the gasMultiplier to help ensure we
// have enough gas for the transaction
const bestEstimate = utils.multiplyBigNumberByDecimal(
utils.bigNumberify(gas),
constructor.gasMultiplier
);
// Check that we don't go over blockLimit
bestEstimate.gte(limit)
? accept(limit.sub(1).toHexString())
: accept(bestEstimate.toHexString());
}
})
.catch(error => {
//HACK: Frankenstein together an error in a destructive fashion!!
debug("error: %O", error);
const reason = Reason._extract({ error }, web3);
error.reason = reason;
if (reason) {
error.message += ` -- Reason given: ${reason}.`;
}
reject(error);
});
});
},
/**
* 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
* @param {Boolean} isCall Used when preparing a call as opposed to a tx;
* skips network checks and ignores default gas prices
* @return {Promise} Resolves object w/ tx params disambiguated from arguments
*/
prepareCall: async function (constructor, methodABI, _arguments, isCall) {
let args = Array.prototype.slice.call(_arguments);
let params = utils.getTxParams.call(constructor, methodABI, args, isCall);
args = utils.convertToEthersBN(args);
if (constructor.ens && constructor.ens.enabled) {
const { web3 } = constructor;
const processedValues = await utils.ens.convertENSNames({
networkId: constructor.network_id,
ens: constructor.ens,
inputArgs: args,
inputParams: params,
methodABI,
web3
});
args = processedValues.args;
params = processedValues.params;
}
//isCall flag used to skip network call for read data (calls type) methods invocation
if (isCall) {
return { args, 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} methodABI ABI for the method;