UNPKG

@decent-bet/solido

Version:

Code first contract entity mapper for Solidity based blockchains like Ethereum, Vechain, Tron

113 lines (112 loc) 3.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const types_1 = require("../types"); const __1 = require(".."); function applyMixins(derivedCtor, baseCtors) { baseCtors.forEach(baseCtor => { Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => { derivedCtor.prototype[name] = baseCtor.prototype[name]; }); }); } class ContractCollection { constructor() { this.coll = {}; } add(key, c) { this.coll[key] = c; } getContract(key) { return this.coll[key]; } getDynamicContract(key) { return this.coll[key]; } connect() { const contracts = {}; Object.keys(this.coll).forEach(i => { const c = this.coll[i]; c.connect(); contracts[i] = c; }); return contracts; } } exports.ContractCollection = ContractCollection; class Empty { } class SolidoModule { constructor(contractMappings, ...providers) { this.contractMappings = contractMappings; this.providers = providers; } addContractMapping(contractProviderMapping) { this.contractMappings.push(contractProviderMapping); } rebind() { if (this.bindSetupOptions) { this.bindContracts(this.bindSetupOptions); } else { throw new Error('bindContracts must have been called previously'); } } bindContracts(setupOptions) { const coll = new ContractCollection(); if (this.contractMappings.length === 1 && this.providers.length > 0) { const c = this.contractMappings[0]; this.providers.forEach((provider) => { const name = c.name; if (!name) { throw new Error('Must have a name for short module syntax'); } this.bindContract(provider, c, coll, true, setupOptions); }); } else { this.contractMappings.map((c) => { let provider = c.provider; this.bindContract(provider, c, coll, false, setupOptions); }); } this.bindSetupOptions = setupOptions; return coll; } bindContract(provider, c, collection, generateName, setupOptions) { if (!provider) { throw new Error(`Missing provider for ${c.name}`); } if (!c && c.import) { throw new Error(`Missing import for ${c.name}`); } if (!c.entity && c.enableDynamicStubs) { c.entity = Empty; } if (!c.entity && !c.enableDynamicStubs) { throw new Error('Must provide an entity class'); } const init = function fn() { }; init.prototype = Object.create(c.entity.prototype); applyMixins(init, [provider, __1.SolidoProvider]); const instance = new init(); instance.setContractImport(c.import); if (c.enableDynamicStubs) { instance.buildDynamicStubs(); } let name = c.name; const providerKeyName = instance.getProviderType(); const providerName = types_1.SolidoProviderType[providerKeyName]; if (generateName) { name = `${providerName}${c.name}`; } const contract = instance; collection.add(name, contract); if (setupOptions) { const instanceOptions = setupOptions[providerKeyName]; if (instanceOptions) { contract.setInstanceOptions(instanceOptions); } } } } exports.SolidoModule = SolidoModule;