OpenST Utility Contract constructor

@constructor
@augments OwnedKlass

@param {string} contractAddress - address on Utility Chain where Contract has been deployed
329985
function (contractAddress) {
  // Helpful while deployement, since ENV variables are not set at that time
  contractAddress = contractAddress || openSTUtilityContractAddr;

  const oThis = this;

  oThis.contractAddress = contractAddress;

  openSTUtilityContractObj.options.address = contractAddress;
  //openSTUtilityContractObj.setProvider(web3Provider.currentProvider);

  OwnedKlass.call(oThis, contractAddress, web3Provider, openSTUtilityContractObj, UC_GAS_PRICE)

}
802838
function buildPrivateElementsChain(conn, unit, message_index, output_index, payload, handlePrivateElements){
	var asset = payload.asset;
	var denomination = payload.denomination;
	var output = payload.outputs[output_index];
	var hidden_payload = _.cloneDeep(payload);
	hidden_payload.outputs.forEach(function(o){
		delete o.address;
		delete o.blinding;
		// output_hash was already added
	});
	var arrPrivateElements = [{
		unit: unit,
		message_index: message_index,
		payload: hidden_payload,
		output_index: output_index,
		output: {
			address: output.address,
			blinding: output.blinding
		}
	}];
	
	function readPayloadAndGoUp(_unit, _message_index, _output_index){
		conn.query(
			"SELECT src_unit, src_message_index, src_output_index, serial_number, denomination, amount, address, asset, \n\
				(SELECT COUNT(*) FROM unit_authors WHERE unit=?) AS count_authors \n\
			FROM inputs WHERE unit=? AND message_index=?", 
			[_unit, _unit, _message_index],
			function(in_rows){
				if (in_rows.length === 0)
					throw Error("building chain: blackbyte input not found");
				if (in_rows.length > 1)
					throw Error("building chain: more than 1 input found");
				var in_row = in_rows[0];
				if (!in_row.address)
					throw Error("readPayloadAndGoUp: input address is NULL");
				if (in_row.asset !== asset)
					throw Error("building chain: asset mismatch");
				if (in_row.denomination !== denomination)
					throw Error("building chain: denomination mismatch");
				var input = {};
				if (in_row.src_unit){ // transfer
					input.unit = in_row.src_unit;
					input.message_index = in_row.src_message_index;
					input.output_index = in_row.src_output_index;
				}
				else{
					input.type = 'issue';
					input.serial_number = in_row.serial_number;
					input.amount = in_row.amount;
					if (in_row.count_authors > 1)
						input.address = in_row.address;
				}
				conn.query(
					"SELECT address, blinding, output_hash, amount, output_index, asset, denomination FROM outputs \n\
					WHERE unit=? AND message_index=? ORDER BY output_index", 
					[_unit, _message_index], 
					function(out_rows){
						if (out_rows.length === 0)
							throw Error("blackbyte output not found");
						var output = {};
						var outputs = out_rows.map(function(o){
							if (o.asset !== asset)
								throw Error("outputs asset mismatch");
							if (o.denomination !== denomination)
								throw Error("outputs denomination mismatch");
							if (o.output_index === _output_index){
								output.address = o.address;
								output.blinding = o.blinding;
							}
							return {
								amount: o.amount,
								output_hash: o.output_hash
							};
						});
						if (!output.address)
							throw Error("output not filled");
						var objPrivateElement = {
							unit: _unit,
							message_index: _message_index,
							payload: {
								asset: asset,
								denomination: denomination,
								inputs: [input],
								outputs: outputs
							},
							output_index: _output_index,
							output: output
						};
						arrPrivateElements.push(objPrivateElement);
						(input.type === 'issue') 
							? handlePrivateElements(arrPrivateElements)
							: readPayloadAndGoUp(input.unit, input.message_index, input.output_index);
					}
				);
			}
		);
	}
	
	var input = payload.inputs[0];
	(input.type === 'issue') 
		? handlePrivateElements(arrPrivateElements)
		: readPayloadAndGoUp(input.unit, input.message_index, input.output_index);
}
523106
function getContractAddress(transaction) {
    if (!transaction.from) {
        throw new Error('missing from address');
    }
    var nonce = transaction.nonce;
    return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([
        getAddress(transaction.from),
        bytes_1.stripZeros(bytes_1.hexlify(nonce))
    ])).substring(26));
}
215147
function chaiSupportChainPromise(chai, utils){
    function copyChainPromise(promise, assertion){
        let protoPromise = Object.getPrototypeOf(promise);
        let protoNames = Object.getOwnPropertyNames(protoPromise);
        let protoAssertion = Object.getPrototypeOf(assertion);
        protoNames.forEach(function(protoName){
            if(protoName !== 'constructor' && !protoAssertion[protoName]){
                assertion[protoName] = promise[protoName].bind(promise);
            }
        });
    }
    function doAsserterAsync(asserter, assertion, args){
        let self = utils.flag(assertion, "object");
        if(self && self.then && typeof self.then === "function"){
            let promise = self.then(function(value){
                assertion._obj = value;
                asserter.apply(assertion, args);
                return value;
            }, function(error){
                assertion._obj = new Error(error);
                asserter.apply(assertion, args);
            });
            copyChainPromise(promise, assertion);
        }
        else{
            return asserter.apply(assertion, args);
        }
    }
    let Assertion = chai.Assertion;
    let propertyNames = Object.getOwnPropertyNames(Assertion.prototype);

    let propertyDescs = {};
    propertyNames.forEach(function (name) {
        propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name);
    });

    let methodNames = propertyNames.filter(function (name) {
        return name !== "assert" && typeof propertyDescs[name].value === "function";
    });

    methodNames.forEach(function (methodName) {
        Assertion.overwriteMethod(methodName, function (originalMethod) {
            return function () {
                doAsserterAsync(originalMethod, this, arguments);
            };
        });
    });

    let getterNames = propertyNames.filter(function (name) {
        return name !== "_obj" && typeof propertyDescs[name].get === "function";
    });

    getterNames.forEach(function (getterName) {
        let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName);
        if (isChainableMethod) {
            Assertion.overwriteChainableMethod(
                getterName,
                function (originalMethod) {
                    return function() {
                        doAsserterAsync(originalMethod, this, arguments);
                    };
                },
                function (originalGetter) {
                    return function() {
                        doAsserterAsync(originalGetter, this);
                    };
                }
            );
        } else {
            Assertion.overwriteProperty(getterName, function (originalGetter) {
                return function () {
                    doAsserterAsync(originalGetter, this);
                };
            });
        }
    });
}
686651
async function (showPrompts) {
    logger.step('** Deploying valueCore Contract');
    if (showPrompts) {
      // confirming the important addresses
      logger.info("Deployer Address: " + valueDeployerAddress);
      logger.info("Value Ops Address: " + valueOpsAddress);
      logger.info("Value Registrar Contract: " + valueRegistrarContractAddress);
      logger.info("OpenST Utility Contract: " + openSTUtilityContractAddress);
      logger.info("OpenST Value Contract: " + openSTValueContractAddress);

      await new Promise(
        function (onResolve, onReject) {
          prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
            if ((intent === 'Y') || (intent === 'y')) {
              logger.info('Great! Proceeding deployment.');
              prompts.close();
              onResolve();
            } else {
              logger.error('Exiting deployment scripts. Change the env vars and re-run.');
              process.exit(1);
            }
          });
        }
      );
    } else {
      prompts.close();
    }

    const valueCoreContractDeployResponse = await deployHelper.perform(valueCoreContractName, web3Provider,
      valueCoreContractAbi, valueCoreContractBin, valueDeployerName, {gasPrice: VALUE_GAS_PRICE, gas: VALUE_GAS_LIMIT},
      [valueRegistrarContractAddress, VALUE_CHAIN_ID, UTILITY_CHAIN_ID, openSTUtilityContractAddress]);

    const valueCoreContractAddress = valueCoreContractDeployResponse.contractAddress;

    logger.step('** Calling addCore of Value Registrar Contract');
    await valueRegistrar.addCore(valueOpsName, openSTValueContractAddress, valueCoreContractAddress);

    return Promise.resolve(responseHelper.successWithData(
      {contract: 'valueCore', address: valueCoreContractAddress}));
  }
1065640
def ContainsAddressStr(self, address):
        
        for key, contract in self._contracts.items():
            if contract.Address == address:
                return True
        return False
1307991
@Programmatic
    public CommunicationChannelOwnerLink createLink(
            final CommunicationChannel communicationChannel,
            final Object owner) {

        final CommunicationChannelType type = communicationChannel.getType();
        final Class<? extends CommunicationChannelOwnerLink> subtype = subtypeClassFor(owner, type);

        final CommunicationChannelOwnerLink link = repositoryService.instantiate(subtype);

        link.setCommunicationChannel(communicationChannel);
        // copy over the type, to support subsequent querying.
        link.setCommunicationChannelType(type);

        final Bookmark bookmark = bookmarkService.bookmarkFor(owner);
        link.setOwner(owner);
        link.setOwnerStr(bookmark.toString());

        repositoryService.persist(link);

        return link;
    }
550256
async function () {
    logger.step("** Setting Admin Address of Simple Token Contract to value Registrar");

    await SimpleToken.setAdminAddress('foundation', valueRegistrarAddr, {});
    const simpleTokenAdminAddressResponse = await SimpleToken.getAdminAddress()
      , simpleTokenAdminAddress = simpleTokenAdminAddressResponse.data.address;

    // check if the admin address is correctly set.
    if(!simpleTokenAdminAddress || !simpleTokenAdminAddress.equalsIgnoreCase(valueRegistrarAddr)){
      return Promise.reject('Admin Address not correctly set');
    }

    logger.step("** Finalize Simple Token Contract");
    // finalize the simple token contract
    await SimpleToken.finalize(valueRegistrarAddr, valueRegistrarPassphrase);

    return Promise.resolve();
  }
192700
function Contract(addressOrName, contractInterface, signerOrProvider) {
        var _this = this;
        errors.checkNew(this, Contract);
        // @TODO: Maybe still check the addressOrName looks like a valid address or name?
        //address = getAddress(address);
        if (interface_1.Interface.isInterface(contractInterface)) {
            properties_1.defineReadOnly(this, 'interface', contractInterface);
        }
        else {
            properties_1.defineReadOnly(this, 'interface', new interface_1.Interface(contractInterface));
        }
        if (abstract_signer_1.Signer.isSigner(signerOrProvider)) {
            properties_1.defineReadOnly(this, 'provider', signerOrProvider.provider);
            properties_1.defineReadOnly(this, 'signer', signerOrProvider);
        }
        else if (abstract_provider_1.Provider.isProvider(signerOrProvider)) {
            properties_1.defineReadOnly(this, 'provider', signerOrProvider);
            properties_1.defineReadOnly(this, 'signer', null);
        }
        else {
            errors.throwError('invalid signer or provider', errors.INVALID_ARGUMENT, { arg: 'signerOrProvider', value: signerOrProvider });
        }
        properties_1.defineReadOnly(this, 'estimate', {});
        properties_1.defineReadOnly(this, 'functions', {});
        properties_1.defineReadOnly(this, 'filters', {});
        Object.keys(this.interface.events).forEach(function (eventName) {
            var event = _this.interface.events[eventName];
            properties_1.defineReadOnly(_this.filters, eventName, function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return {
                    address: _this.address,
                    topics: event.encodeTopics(args)
                };
            });
        });
        this._events = [];
        properties_1.defineReadOnly(this, 'address', addressOrName);
        if (this.provider) {
            properties_1.defineReadOnly(this, 'addressPromise', this.provider.resolveName(addressOrName).then(function (address) {
                if (address == null) {
                    throw new Error('name not found');
                }
                return address;
            }).catch(function (error) {
                throw error;
            }));
        }
        else {
            try {
                properties_1.defineReadOnly(this, 'addressPromise', Promise.resolve(address_1.getAddress(addressOrName)));
            }
            catch (error) {
                // Without a provider, we cannot use ENS names
                errors.throwError('provider is required to use non-address contract address', errors.INVALID_ARGUMENT, { argument: 'addressOrName', value: addressOrName });
            }
        }
        Object.keys(this.interface.functions).forEach(function (name) {
            var run = runMethod(_this, name, false);
            if (_this[name] == null) {
                properties_1.defineReadOnly(_this, name, run);
            }
            else {
                errors.warn('WARNING: Multiple definitions for ' + name);
            }
            if (_this.functions[name] == null) {
                properties_1.defineReadOnly(_this.functions, name, run);
                properties_1.defineReadOnly(_this.estimate, name, runMethod(_this, name, true));
            }
        });
    }
351171
private void assignAddress(String addressString) throws ChannelFrameworkException, UnknownHostException {
        if (addressString == null) {
            // No address found in properties. No CFEndPoint can be created.
            throw new ChannelFrameworkException("No address available in properties.");
        }
        if ("*".equals(addressString)) {
            // TODO WAS used the node name
            this.address = InetAddress.getLocalHost();
        } else {
            this.address = InetAddress.getByName(addressString);
        }
    }
315968
private static void assignKeyFromAddressNode(ModelNode payload, ModelNode address) {
        List<Property> props = address.asPropertyList();
        Property lastToken = props.get(props.size()-1);
        payload.get("entity.key").set(lastToken.getValue().asString());
    }
1191692
function deploy(contract, callback, contractMap) {
  // Reuse existing contract address
  if (config.deployedContracts.hasOwnProperty(contract.name)) {
    contract.address = config.deployedContracts[contract.name];
    return callback(null, contract);
  }

  linkBytecode(contract, contractMap);

  // Deploy a new one
  var params = resolveConstructorParams(contract, contractMap);
  logDebug('Constructor params ' + contract.name + ':', params);
  if(contract.bytecode && !contract.bytecode.startsWith('0x')) {
    contract.bytecode = '0x' + contract.bytecode;
  }
  params.push({
    from: config.from,
    data: contract.bytecode,
    gas: config.gasLimit,
  });
  params.push(function (err, deployed) {
    if (err) {
      return callback(err);
    }
    if (typeof deployed.address !== 'undefined') {
      contract.address = deployed.address;
      return callback(null, contract);
    }
  });

  var web3Contract = web3.eth.contract(contract.abi);
  web3Contract.new.apply(web3Contract, params);
}
635057
function(priv, network, _expectedAddress) {
    // Errors
    if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
    if (!Helpers.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
    //Processing
    let expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
    let kp = KeyPair.create(priv);
    let address = Address.toAddress(kp.publicKey.toString(), network);
    // Result
    return address === expectedAddress;
}
784606
function createAdditionalMessages(conn, last_ball_mci, bMultiAuthored, arrPayingAddresses, onDone){
			var arrAssetPayingAddresses = _.intersection(arrPayingAddresses, params.paying_addresses);
			storage.loadAssetWithListOfAttestedAuthors(conn, params.asset, last_ball_mci, arrAssetPayingAddresses, function(err, objAsset){
				if (err)
					return onDone(err);
				if (!objAsset.fixed_denominations)
					return onDone("divisible asset type");
				if (!objAsset.is_transferrable && params.to_address !== objAsset.definer_address && arrAssetPayingAddresses.indexOf(objAsset.definer_address) === -1)
					return onDone("the asset is not transferrable and definer not found on either side of the deal");
				if (objAsset.cosigned_by_definer && arrPayingAddresses.concat(params.signing_addresses || []).indexOf(objAsset.definer_address) === -1)
					return onDone("the asset must be cosigned by definer");
				if (objAsset.spender_attested && objAsset.arrAttestedAddresses.length === 0)
					return onDone("none of the authors is attested");

				var target_amount = params.to_address ? params.amount : params.asset_outputs[0].amount;
				var to_address = params.to_address ? params.to_address : params.asset_outputs[0].address;
				pickIndivisibleCoinsForAmount(
					conn, objAsset, arrAssetPayingAddresses, last_ball_mci, 
					to_address, params.change_address,
					target_amount, params.tolerance_plus || 0, params.tolerance_minus || 0, 
					bMultiAuthored, params.spend_unconfirmed || 'own',
					function(err, arrPayloadsWithProofs){
						if (!arrPayloadsWithProofs)
							return onDone({
								error_code: "NOT_ENOUGH_FUNDS", 
								error: err
							});
						var arrMessages = [];
						var assocPrivatePayloads = {};
						for (var i=0; i<arrPayloadsWithProofs.length; i++){
							var payload = arrPayloadsWithProofs[i].payload;
							var payload_hash;// = objectHash.getBase64Hash(payload);
							var bJsonBased = (last_ball_mci >= constants.timestampUpgradeMci);
							if (objAsset.is_private){
								payload.outputs.forEach(function(o){
									o.output_hash = objectHash.getBase64Hash({address: o.address, blinding: o.blinding});
								});
								var hidden_payload = _.cloneDeep(payload);
								hidden_payload.outputs.forEach(function(o){
									delete o.address;
									delete o.blinding;
								});
								payload_hash = objectHash.getBase64Hash(hidden_payload, bJsonBased);
							}
							else
								payload_hash = objectHash.getBase64Hash(payload, bJsonBased);
							var objMessage = {
								app: "payment",
								payload_location: objAsset.is_private ? "none" : "inline",
								payload_hash: payload_hash
							};
							if (objAsset.is_private){
								assocPrivatePayloads[payload_hash] = payload;
								objMessage.spend_proofs = [arrPayloadsWithProofs[i].spend_proof];
							}
							else
								objMessage.payload = payload;
							arrMessages.push(objMessage);
						}
						// messages are sorted in descending order by denomination of the coin, so shuffle them to avoid giving any clues
						shuffleArray(arrMessages);
						console.log("composed messages "+JSON.stringify(arrMessages));
						onDone(null, arrMessages, assocPrivatePayloads);
					}
				);
			});
		}
166728
@MemberOrder(name = "CommunicationChannels", sequence = "2")
    @Action(semantics = SemanticsOf.NON_IDEMPOTENT)
    @ActionLayout(contributed = Contributed.AS_ACTION)
    public CommunicationChannelOwner newEmail(
            final CommunicationChannelOwner owner,
            @ParameterLayout(named = "Type")
            final CommunicationChannelType type,
            @ParameterLayout(named = "Address")
            final String address) {
        communicationChannelRepository.newEmail(owner, type, address);
        return owner;
    }
259751
function(args, connectionInfo) {
  // args.consignmentIdToProductIdMap.value MUST already be set by the caller
  // args.consignmentProductId.value MUST be set for the very first call
  args.arrayIndex = {value: 0};
  args.consignmentProductId = {value: args.consignmentIdToProductIdMap.value[args.arrayIndex.value].productId};
  args.getArray = function(){
    return this.consignmentIdToProductIdMap.value;
  };
  args.getArrayIndex = function(){
    return this.arrayIndex.value;
  };

  // iterate serially through a promise chain for all args.consignmentIds.value
  return utils.processPromisesSerially(
    args.getArray(),
    args.getArrayIndex(),
    args,
    function mergeStrategy(newData, previousData, args){
      log.debug('resolveMissingSuppliers - inside mergeStrategy()');
      var product = newData.products[0];
      //log.silly('newData: ', newData);
      //log.silly('product: ', product);
      var updateMe = args.getArray()[args.getArrayIndex()];
      updateMe.supplier = product.supplier_name || product.supplier_code;
      log.debug('updated consignmentIdToProductIdMap: ', args.getArray()[args.getArrayIndex()]);

      previousData = args.getArray();
      return Promise.resolve(previousData); // why do we need a promise?
    },
    function setupNext(updateArgs){
      log.debug('resolveMissingSuppliers - inside setupNext()');
      updateArgs.arrayIndex.value = updateArgs.getArrayIndex() + 1;
      if (updateArgs.getArrayIndex() < updateArgs.getArray().length) {
        updateArgs.consignmentProductId.value = updateArgs.getArray()[updateArgs.getArrayIndex()].productId;
        log.debug('resolveMissingSuppliers - next is consignmentId: ' + updateArgs.consignmentProductId.value);
      }
      else {
        updateArgs.consignmentProductId.value = null;
        log.debug('resolveMissingSuppliers - finished iterating through all the consignmentIds');
      }
      return updateArgs;
    },
    function executeNext(updatedArgs){
      log.debug('resolveMissingSuppliers - inside executeNext()');
      log.debug('resolveMissingSuppliers - executing for consignmentProductId: ' + updatedArgs.consignmentProductId.value);
      //log.silly('updatedArgs: ', updatedArgs);
      var args = argsForInput.products.fetchById();
      args.apiId.value = updatedArgs.consignmentProductId.value;
      return product.endpoints.fetchProduct(args, connectionInfo);
    }
  );
}
975600
async function (showPrompts) {

    logger.step('** Deploying OpenST Utility Contract');
    if (showPrompts) {
      logger.info('Utility Chain Deployer Address: ' + utilityDeployerAddress);
      logger.info('Value Chain ID: ' + VALUE_CHAIN_ID);
      logger.info('Utility Chain ID: ' + UTILITY_CHAIN_ID);
      logger.info('Foundation Address: ' + foundationAddress);

      await new Promise(
        function (onResolve, onReject) {
          prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
            if ((intent === 'Y') || (intent === 'y')) {
              logger.info('Great! Proceeding deployment.');
              prompts.close();
              onResolve();
            } else {
              logger.error('Exiting deployment scripts. Change the env vars and re-run.');
              process.exit(1);
            }
          });
        }
      );
    } else {
      prompts.close();
    }

    const openSTUtiltiyContractDeployResponse = await deployHelper.perform(openSTUtilityContractName,
      web3Provider, openSTUtilityContractAbi, openSTUtilityContractBin, utilityDeployerName,
      {gasPrice: UC_GAS_PRICE, gas: UC_GAS_LIMIT}, [VALUE_CHAIN_ID, UTILITY_CHAIN_ID, utilityRegistrarContractAddress]
    );

    const openSTUtilityContractAddress = openSTUtiltiyContractDeployResponse.contractAddress
      , openStUtility = new OpenStUtilityKlass(openSTUtilityContractAddress);

    logger.step('** Initiating OwnerShipTransfer of openSTUtility Contract to foundation');

    await openStUtility.initiateOwnerShipTransfer(utilityDeployerName,
      foundationAddress, {gasPrice: UC_GAS_PRICE, gas: UC_GAS_LIMIT});

    const getOwnerResponse = await openStUtility.getOwner();

    if (!foundationAddress.equalsIgnoreCase(getOwnerResponse.data.address)) {
      logger.error('Exiting the deployment as owner of openSTUtility Contract does not match');
      process.exit(1);
    }

    return Promise.resolve(responseHelper.successWithData(
      {contract: 'openSTUtility', address: openSTUtilityContractAddress}));
  }