How to use js-sha3 - 10 common examples

To help you get started, we’ve selected a few js-sha3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github DivanteLtd / vue-storefront / core / modules / order / store / actions.ts View on Github external
async placeOrder ({ commit, getters, dispatch }, order:Order) {
  
    // Check if order is already processed/processing
    const currentOrderHash = sha3_224(JSON.stringify(order))
    const isAlreadyProcessed = getters.getSessionOrderHashes.includes(currentOrderHash)
    if (isAlreadyProcessed) return
    commit(types.ORDER_ADD_SESSION_ORDER_HASH, currentOrderHash)

    const storeView = currentStoreView()
    if (storeView.storeCode) {
      order.store_code = storeView.storeCode
    }

    Vue.prototype.$bus.$emit('order-before-placed', { order: order })
    if (!config.orders.directBackendSync || !isOnline()) {
      commit(types.ORDER_PLACE_ORDER, order)
      Vue.prototype.$bus.$emit('order-after-placed', { order: order })
      return {
        resultCode: 200
      }
github DivanteLtd / vue-storefront / core / modules / order / store / actions.ts View on Github external
async placeOrder ({ commit, getters, dispatch }, order: Order) {
    if (config.entities.optimize && config.entities.optimizeShoppingCart) {
      order.products = order.products.map(product => omit(product, ['configurable_options', 'configurable_children'])) as Order['products']
    }
    // Check if order is already processed/processing
    const currentOrderHash = sha3_224(JSON.stringify(order))
    const isAlreadyProcessed = getters.getSessionOrderHashes.includes(currentOrderHash)
    if (isAlreadyProcessed) return
    commit(types.ORDER_ADD_SESSION_ORDER_HASH, currentOrderHash)

    const storeView = currentStoreView()
    if (storeView.storeCode) {
      order.store_code = storeView.storeCode
    }

    EventBus.$emit('order-before-placed', { order: order })
    order = orderHooksExecutors.beforePlaceOrder(order)
    if (!config.orders.directBackendSync || !isOnline()) {
      commit(types.ORDER_PLACE_ORDER, order)
      EventBus.$emit('order-after-placed', { order: order })
      orderHooksExecutors.beforePlaceOrder({ order, task: { resultCode: 200 } })
      return {
github blockchainbox / blockchainbox-core / routes / account.js View on Github external
account.create(accountEntity).then(function(accountId){
    	// generate passphrase
    	// generate token
    	var passphrase = sha3_224(account + ':passphrase:' + Math.random());
    	var token = sha3_224(account + ':token:' + Math.random());

      var ethAddress = web3.personal.newAccount(passphrase);
      // TODO save address & passphrase
      var addressEntity = {
      	'accountId': accountId,
        'address': ethAddress,
        'passphrase': passphrase,    // hash
        'token': token
      }

      address.create(addressEntity).then(function(addressResult){
				var fileDir = process.env.KEYSTORE_PATH;
				fs.readdir(fileDir, 'utf8', function(err, files) {
					if (err) console.log(err);
				  files.forEach(function(file) {
github fairDataSociety / fds.js / migrations / 1563788331_ens.js View on Github external
await deployer.deploy(ENS);

            const ens = await ENS.deployed();

            await deployer.deploy(TestRegistrar, ens.address, namehash.hash('eth'));
            await deployer.deploy(PublicResolver, ens.address);

            await ens.setSubnodeOwner('0x0', '0x' + sha3('eth'), accounts[0]);
            await ens.setSubnodeOwner(namehash.hash('eth'), '0x' + sha3('datafund'), accounts[0]);

            const resolver = await PublicResolver.deployed();
            await ens.setResolver(namehash.hash('datafund.eth'), resolver.address);

            const dhr = await TestRegistrar.deployed();
            await ens.setSubnodeOwner('0x0', '0x' + sha3('eth'), accounts[0]);

            await deployer.deploy(SubdomainRegistrar, ens.address, namehash.hash('datafund.eth'));

            const registrar = await SubdomainRegistrar.deployed();
            await ens.setSubnodeOwner(namehash.hash('eth'), '0x' + sha3('datafund'), registrar.address);
            
        } else {
            // const ens = ENS.deployed();
            // await deployer.deploy(SubdomainRegistrar, ens.address);
        }
    });
};
github paritytech / js-libs / packages / abi / src / util / signature.ts View on Github external
export const eventSignature = (
  eventName: string | undefined,
  params: ParamType[] = []
) => {
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  const { strName, name } = parseName(eventName);
  const types = (params || []).map(fromParamType).join(',');
  const id = `${strName}(${types})`;
  const signature = strName ? keccak_256(id) : '';

  return { id, name, signature };
};
github paritytech / js-libs / packages / api / src / transport / ws / ws.js View on Github external
this._ws.onerror = null;
      this._ws.onopen = null;
      this._ws.onclose = null;
      this._ws.onmessage = null;
      this._ws.close();
      this._ws = null;
      this._sessionHash = null;
    }
    this._connecting = true;
    this._connected = false;
    this._lastError = null;

    // rpc secure API
    if (this._token) {
      const time = parseInt(new Date().getTime() / 1000, 10);
      const sha3 = keccak_256(`${this._token}:${time}`);
      const hash = `${sha3}_${time}`;

      this._sessionHash = sha3;
      this._ws = new WebSocket(this._url, hash);
    // non-secure API
    } else {
      this._ws = new WebSocket(this._url);
    }

    this._ws.onerror = this._onError;
    this._ws.onopen = this._onOpen;
    this._ws.onclose = this._onClose;
    this._ws.onmessage = this._onMessage;

    // Get counts in dev mode only
    if (process.env.NODE_ENV === 'development') {
github pubkey / broadcast-channel / dist / es / methods / node.js View on Github external
function getPaths(channelName) {
  if (!getPathsCache.has(channelName)) {
    var channelHash = sha3_224(channelName); // use hash incase of strange characters

    /**
     * because the lenght of socket-paths is limited, we use only the first 20 chars
     * and also start with A to ensure we do not start with a number
     * @link https://serverfault.com/questions/641347/check-if-a-path-exceeds-maximum-for-unix-domain-socket
     */

    var channelFolder = 'A' + channelHash.substring(0, 20);
    var channelPathBase = path.join(TMP_FOLDER_BASE, channelFolder);
    var folderPathReaders = path.join(channelPathBase, 'rdrs');
    var folderPathMessages = path.join(channelPathBase, 'messages');
    var ret = {
      channelBase: channelPathBase,
      readers: folderPathReaders,
      messages: folderPathMessages
    };
github DivanteLtd / storefront-api / src / modules / default-catalog / api / catalog.js View on Github external
}

  delete requestBody.groupToken
  delete requestBody.groupId

  let auth = null;

  // Only pass auth if configured
  if (config.elasticsearch.user || config.elasticsearch.password) {
    auth = {
      user: config.elasticsearch.user,
      pass: config.elasticsearch.password
    };
  }
  const s = Date.now()
  const reqHash = sha3_224(`${JSON.stringify(requestBody)}${req.url}`)
  const dynamicRequestHandler = () => {
    request({ // do the elasticsearch request
      uri: elasticBackendUrl,
      method: req.method,
      body: requestBody,
      json: true,
      auth: auth
    }, (_err, _res, _resBody) => { // TODO: add caching layer to speed up SSR? How to invalidate products (checksum on the response BEFORE processing it)
      if (_resBody && _resBody.hits && _resBody.hits.hits) { // we're signing up all objects returned to the client to be able to validate them when (for example order)
        const factory = new ProcessorFactory(config)
        const tagsArray = []
        if (config.server.useOutputCache && cache) {
          const tagPrefix = entityType[0].toUpperCase() // first letter of entity name: P, T, A ...
          tagsArray.push(entityType)
          _resBody.hits.hits.map(item => {
            if (item._source.id) { // has common identifier
github pubkey / broadcast-channel / src / methods / node.js View on Github external
function getPaths(channelName) {
    if (!getPathsCache.has(channelName)) {
        const channelHash = sha3_224(channelName); // use hash incase of strange characters
        /**
         * because the lenght of socket-paths is limited, we use only the first 20 chars
         * and also start with A to ensure we do not start with a number
         * @link https://serverfault.com/questions/641347/check-if-a-path-exceeds-maximum-for-unix-domain-socket
         */
        const channelFolder = 'A' + channelHash.substring(0, 20);

        const channelPathBase = path.join(
            TMP_FOLDER_BASE,
            channelFolder
        );
        const folderPathReaders = path.join(
            channelPathBase,
            'rdrs'
        );
        const folderPathMessages = path.join(
github DivanteLtd / vue-storefront / core / modules / cart / store / actions.ts View on Github external
serverPull (context, { forceClientState = false, dryRun = false }) { // pull current cart FROM the server
    const isUserInCheckout = context.rootGetters['checkout/isUserInCheckout']
    if (isUserInCheckout) forceClientState = true // never surprise the user in checkout - #
    if (config.cart.synchronize && !isServer && onlineHelper.isOnline && context.state.cartServerToken) {
      const newItemsHash = sha3_224(JSON.stringify({ items: context.state.cartItems, token: context.state.cartServerToken }))
      if ((Date.now() - context.state.cartServerPullAt) >= CART_PULL_INTERVAL_MS || (newItemsHash !== context.state.cartItemsHash)) {
        context.state.cartServerPullAt = Date.now()
        context.state.cartItemsHash = newItemsHash
        return TaskQueue.execute({ url: config.cart.pull_endpoint, // sync the cart
          payload: {
            method: 'GET',
            headers: { 'Content-Type': 'application/json' },
            mode: 'cors'
          },
          silent: true,
          force_client_state: forceClientState,
          dry_run: dryRun,
          callback_event: 'store:cart/servercartAfterPulled'
        }).then(task => {
          const storeView = currentStoreView()
          if ((Date.now() - context.state.cartServerMethodsRefreshAt) >= CART_METHODS_INTERVAL_MS) {