svelte/store#derived JavaScript Examples

The following examples show how to use svelte/store#derived. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dungeon.js    From ethernal with MIT License 6 votes vote down vote up
dungeon = derived([wallet, preDungeonCheck], async ([$wallet, $preDungeonCheck], set) => {
  if (
    $wallet.status === 'Ready' &&
    $preDungeonCheck.status === 'Done' &&
    $preDungeonCheck.isCharacterInDungeon &&
    $preDungeonCheck.isDelegateReady
  ) {
    if (lastWalletAddress !== $wallet.address) {
      lastWalletAddress = $wallet.address;
      set('loading');
      d = await loadDungeon($wallet);
      set(d);
    }
  } else {
    lastWalletAddress = null;
    if (d) {
      d = null;
    }
    set(null);
  }

  // @TODO: remove debug
  window.dungeon = d;
})
Example #2
Source File: Data.js    From svelte-simple-datatables with MIT License 6 votes vote down vote up
createRows(filtered, options, pageNumber)
    {
        return derived(
            [filtered, options, pageNumber],
            ([$filtered, $options, $pageNumber]) => {
                if (!$options.pagination) {
                    return $filtered
                }
                return $filtered.slice( ($pageNumber - 1) * $options.rowsPerPage, $pageNumber * $options.rowsPerPage) 
            }
        ) 
    }
Example #3
Source File: Data.js    From svelte-simple-datatables with MIT License 6 votes vote down vote up
createFiltered(data, rowsCount, globalFilter, localFilters) 
    {
        return derived(
            [data, globalFilter, localFilters],
            ([$data, $globalFilter, $localFilters]) => {
                if ($globalFilter) {
                    $data = $data.filter( item => {
                        return Object.keys(item).some( k => {
                            return item[k].toString().toLowerCase().indexOf($globalFilter.toString().toLowerCase()) > -1
                        })
                    })
                }
                if ($localFilters.length > 0) {
                    $localFilters.forEach(filter => {
                        return $data = $data.filter( item => filter.key(item).toString().toLowerCase().indexOf(filter.value.toString().toLowerCase()) > -1)
                    })
                }
                rowsCount.set($data.length)
                return $data
            } 	
        )
    }
Example #4
Source File: notification-store.js    From rally-core-addon with Mozilla Public License 2.0 6 votes vote down vote up
export function createNotificationStore() {
  const _notification = writable({ id: undefined});
  let timeout;

  function send({ message, type = "default", code }) {
		_notification.set({ id: id(), type, message, code });
  }

  function clear() {
    _notification.set({ id: undefined });
  }

  const notifications = derived(_notification, ($notification, set) => {
    // if there already was a notification, let's clear the timer
    // and reset it here.
    clearTimeout(timeout);
    set($notification);
		// if this is not the reset message, set the timer.
    if ($notification.id) {
      timeout = setTimeout(clear, NOTIFICATION_TIMEOUT);
    }
  })
  const { subscribe } = notifications;

  return {
    timeoutID: timeout,
    subscribe,
    send,
    clear: () => {
      clearTimeout(timeout);
      clear();
    },
  }
}
Example #5
Source File: index.js    From packager with Apache License 2.0 6 votes vote down vote up
translate = derived(locale, (locale) => {
  const localMessages = allMessages[locale]();
  /**
   * @param {string} id Message ID
   * @returns {string} Translated message
   */
  const translateMessage = (id) => {
    return getProperty(localMessages, id) || getProperty(englishMessages, id) || id;
  };
  translate.translate = translateMessage;
  return translateMessage;
})
Example #6
Source File: cache.js    From ethernal with MIT License 6 votes vote down vote up
scavengeLoot = derived([currentRoom], ([$currentRoom], set) => {
  const { scavenge } = $currentRoom;
  set(
    scavenge &&
      (scavenge.gear.length ||
        scavenge.corpses.length ||
        Object.values(scavenge.balance || {})
          .flat()
          .filter(Boolean).length)
      ? scavenge
      : null,
  );
})
Example #7
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
currentFloor = derived([currentRoom], ([$currentRoom], set) => {
  const { z } = parseCoordinates($currentRoom.coordinates);
  set(z);
})
Example #8
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
characterCoordinates = derived([currentRoom], ([$currentRoom], set) => {
  set($currentRoom.coordinates);
})
Example #9
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
taxDueDate = derived([characterInfo], ([$characterInfo], set) => {
  set($characterInfo.taxDueDate);
})
Example #10
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
currentQuest = derived([currentRoom, characterQuests], ([$currentRoom, $characterQuests], set) => {
  // Is NPC and can claim?
  const findQuest = () => {
    const charQuests = Object.entries($characterQuests).filter(([, q]) => q);
    const validStatus = ['discovered', 'accepted', 'claiming'];
    let result = charQuests.find(
      ([, q]) => q && q.coordinates === $currentRoom.coordinates && validStatus.includes(q.status),
    );
    if (!result) {
      const [, , floor] = $currentRoom.formattedCoordinates.split(',').map(Number);
      result = charQuests.find(
        ([, q]) =>
          q &&
          $currentRoom.npc &&
          q.rules.npc &&
          q.npc === $currentRoom.npc.type &&
          validStatus.includes(q.status) &&
          (q.floor == null || q.floor === floor),
      );
    }
    if (result) {
      const [id, quest] = result;
      let { status } = quest;
      if (status === 'accepted') {
        status = 'incomplete';
      }
      if (quests[id].states[status]) {
        return { id, ...quest, label: quests[id].buttons.npc };
      }
    }

    // Is permitted room and can advance?
    result = charQuests.find(
      ([, q]) =>
        q &&
        q.rules &&
        q.status === 'accepted' &&
        q.rules.roomTypes &&
        q.rules.roomTypes.includes($currentRoom.kind) &&
        q.data &&
        Array.isArray(q.data) &&
        !q.data.includes($currentRoom.coordinates),
    );
    if (result) {
      const [id, quest] = result;
      return { id, ...quest, label: quests[id].buttons.action };
    }
    return false;
  };
  const newQuest = findQuest();
  // None of the above
  if (!equal(newQuest, get(currentQuest))) {
    set(newQuest);
  }
})
Example #11
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
currentDuel = derived([currentCombat, characterId], async ([$currentCombat, $characterId], set) => {
  set($currentCombat && $currentCombat.duels[$characterId]);
})
Example #12
Source File: contract-stores.js    From svelte-web3 with MIT License 5 votes vote down vote up
myContractStore = derived([web3, chainId], ([$web3, $chainId]) => {
  if ($chainId && $web3.eth) {
    // DO whaever nececessay to get address from chainId
    console.log('chainId is', $chainId)
    return new $web3.eth.Contract(ERC20.abi, DAI, {})
  }
  return null
})
Example #13
Source File: stores.js    From svelte-web3 with MIT License 5 votes vote down vote up
makeEvmStores = name => {
  const evmStore = (allStores[name] = createStore())

  allStores[name].web3 = derived(evmStore, $evmStore => {
    if (!$evmStore.web3) return { utils: Web3.utils, version: Web3.version }
    return $evmStore.web3
  })

  allStores[name].selectedAccount = derived(
    evmStore,
    $evmStore => $evmStore.selectedAccount
  )

  allStores[name].connected = derived(
    evmStore,
    $evmStore => $evmStore.connected
  )
  allStores[name].chainId = derived(evmStore, $evmStore => $evmStore.chainId)
  allStores[name].chainData = derived(evmStore, $evmStore =>
    $evmStore.chainId ? getData($evmStore.chainId) : {}
  )

  allStores[name].evmProviderType = derived(
    evmStore,
    $evmStore => $evmStore.evmProviderType
  )
  allStores[name].walletType = derived(evmStore, $evmStore => {
    if (!$evmStore.eipProvider) return null
    if (typeof $evmStore.eipProvider === 'string') return $evmStore.eipProvider
    if ($evmStore.eipProvider.isNiftyWallet) return 'Nifty'
    if ($evmStore.eipProvider.isTrust) return 'Trust'
    if ($evmStore.eipProvider.isMetaMask) return 'MetaMask (or compatible)'
    if (
      $evmStore.eipProvider.bridge &&
      /walletconnect/.test($evmStore.eipProvider.bridge)
    )
      return 'WalletConnect'
    return 'Unknown'
  })

  return new Proxy(allStores[name], {
    get: function (internal, property) {
      if (/^\$/.test(property)) {
        // TODO forbid deconstruction !
        property = property.slice(1)
        if (subStoreNames.includes(property))
          return allStores[name].get(property)
        throw new Error(`[svelte-web3] no value for store named ${property}`)
      }
      if (
        [
          'subscribe',
          'get',
          'setBrowserProvider',
          'setProvider',
          'evmProviderType',
          'chainData',
          'walletType',
          'close',
          'disconnect',
          ...subStoreNames
        ].includes(property)
      )
        return Reflect.get(internal, property)
      throw new Error(`[svelte-web3] no store named ${property}`)
    }
  })
}
Example #14
Source File: stores.js    From svelte-web3 with MIT License 5 votes vote down vote up
makeContractStore = (abi, address, defaults = {}) =>
  derived([web3, connected], ([$web3, $connected]) => {
    if ($connected && $web3.eth) {
      return new $web3.eth.Contract(abi, address, defaults)
    }
    return null
  })
Example #15
Source File: location.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
routeHasChanged = derived(location, ($l) => {
  if (!$l.previous || !$l.current) return true;

  if ($l.previous.pathname !== $l.current.pathname) return true;

  return false;
})
Example #16
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
needFood = derived([playerEnergy, wallet], ([$playerEnergy, $wallet], set) => {
  if ($playerEnergy) {
    set(BigNumber.from($playerEnergy).lt(BigNumber.from(config($wallet.chainId).minBalance).mul(5)));
    // set(true);
  }
})
Example #17
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
combatLog = derived([currentDuel], async ([$currentDuel], set) => {
  const introduction = combatText.start;
  if ($currentDuel) {
    set([introduction, ...$currentDuel.log.map(logToText)]);
  } else {
    set([introduction]);
  }
})
Example #18
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
characterPortrait = derived([characterClass], ([$characterClass], set) => {
  set(classPortrait($characterClass));
})
Example #19
Source File: claim.js    From ethernal with MIT License 4 votes vote down vote up
store = derived(
  wallet,
  async ($wallet, set) => {
    const _set = obj => {
      $claim = { ...$claim, ...obj };
      log.info('CLAIM', JSON.stringify($claim, null, '  '));
      set($claim);
    };

    const gasPrice = BigNumber.from('1000000000'); // await provider.getGasPrice();
    const gasLimit = BigNumber.from(21000);
    const gasFee = gasLimit.mul(gasPrice);
    const extraValue = BigNumber.from('100000000000000');
    const minimum = gasFee.add(extraValue);
    const maximum = BigNumber.from('4000000000000000000'); // @TODO: config)

    if (claimKey && typeof $claim.rawBalance === 'undefined') {
      try {
        claimWallet = new Wallet(claimKey);
        const provider = wallet.getFallbackProvider();
        if (provider) {
          (async () => {
            let claimBalance = await wallet.getFallbackProvider().getBalance(claimWallet.address);
            if (claimBalance.lt(minimum)) {
              claimBalance = BigNumber.from(0);
            }
            if (claimBalance.gt(maximum)) {
              claimBalance = maximum;
            }
            // eslint-disable-next-line no-console
            console.log({
              address: claimWallet.address,
              status: 'WaitingWallet',
              rawBalance: claimBalance,
              balance: utils.formatUnits(claimBalance, 18),
            });
            _set({
              status: 'WaitingWallet',
              rawBalance: claimBalance,
              balance: utils.formatUnits(claimBalance, 18),
            });
          })();
        }
      } catch (e) {
        const claimBalance = BigNumber.from(0);
        _set({
          status: 'WaitingWallet',
          rawBalance: claimBalance,
          balance: utils.formatUnits(claimBalance, 18),
        });
      }
    }

    async function claim() {
      _set({ status: 'Loading' });
      const provider = wallet.getProvider();

      let claimingTxHash;
      const localStorageKeyForClaimTxHash = `${$wallet.address}_${$wallet.chainId}_claimTxHash`;
      try {
        claimingTxHash = localStorage.getItem(localStorageKeyForClaimTxHash);
      } catch (err) {
        //
      }

      if (claimingTxHash && claimingTxHash !== '') {
        _set({ status: 'WaitingOldTx' });

        const tx = await provider.getTransaction(claimingTxHash);
        if (tx) {
          const receipt = await tx.wait();
          if (tx.blockNumber) {
            if (receipt.status === 1) {
              _set({ status: 'Claimed' });
              clearClaimKey();
              return;
            }
            _set({ status: 'Failed' });
          } else {
            const txReceipt = await tx.wait();
            if (txReceipt.status === 1) {
              _set({ status: 'Claimed' });
              clearClaimKey();
              return;
            }
            _set({ status: 'Failed' });
          }
        } else {
          log.trace(`cannot find tx ${claimingTxHash}`);
        }
      }

      const claimBalance = await provider.getBalance(claimWallet.address);
      log.trace({ claimBalance });

      const claimValue = BigNumber.from('5000000000000000000'); // @TODO: from Config 5 DAI
      if (claimBalance.gte(minimum)) {
        const signer = claimWallet.connect(provider);
        let value = claimBalance.sub(gasFee);
        const maxValue = BigNumber.from(claimValue);
        if (value.gt(maxValue)) {
          value = maxValue;
        }
        _set({ status: 'Claiming' });

        const tx = await signer.sendTransaction({
          to: $wallet.address,
          value,
          gasLimit,
          gasPrice,
        });
        localStorage.setItem(localStorageKeyForClaimTxHash, tx.hash);
        _set({ status: 'WaitingTx' });

        const receipt = await tx.wait();
        if (receipt.status === 1) {
          _set({ status: 'Claimed' });
          clearClaimKey();
          return;
        }
        _set({ status: 'Failed' });
      } else {
        _set({ status: 'Gone' });
      }
      clearClaimKey();
    }

    store.claim = claim;
    store.acknowledge = () => {
      _set({ status: 'None' });
    };
  },
  $claim,
)
Example #20
Source File: preDungeonCheck.js    From ethernal with MIT License 4 votes vote down vote up
store = derived(
  wallet,
  async ($wallet, set) => {
    const _set = obj => {
      $data = { ...$data, ...obj };
      console.log('pre dungeon check', $data);
      set($data);
    };

    if ($wallet.status === 'Ready') {
      if (lastWalletAddress !== $wallet.address) {
        lastWalletAddress = $wallet.address;
        _set({ status: 'Loading' });
        const delegateAccount = getDelegateKey($wallet.address);

        const checkCharacter = async () => {
          const characterId = await wallet.call('Player', 'getLastCharacterId', $wallet.address);
          const isDelegateReady = await wallet.call(
            'Player',
            'isDelegateFor',
            delegateAccount.address,
            $wallet.address,
          );
          const result = await wallet.call('Characters', 'fullOwnerOf', characterId);
          const isCharacterInDungeon =
            result.owner === wallet.getContract('Dungeon').address &&
            result.subOwner.eq(BigNumber.from($wallet.address));
          const balance = await wallet.getProvider().getBalance($wallet.address);
          // TODO should be free
          const insufficientBalance = balance.lt('1100000000000000000');
          return { characterId, isDelegateReady, isCharacterInDungeon, insufficientBalance };
        };

        const { characterId, isDelegateReady, isCharacterInDungeon, insufficientBalance } = await checkCharacter();

        let characterInfo;
        const { minBalance } = config($wallet.chainId);
        let refill = minBalance;
        try {
          characterInfo = await fetchCache(`characters/${characterId}`);
        } catch (e) {
          console.log('failed to fetch character info from cache');
        }

        let ressurectedId;
        if (characterInfo && !isCharacterInDungeon && characterInfo.status.status === 'dead') {
          const { Dungeon } = window.contracts; // TODO get contract elsewhere
          const topic = Dungeon.interface.getEventTopic(Dungeon.interface.events['Resurrect(uint256,uint256)']);
          const [ressurect] = await Dungeon.queryFilter({
            address: Dungeon.address,
            topics: [topic, uint256(characterId)],
          });
          if (ressurect) {
            ressurectedId = ressurect.args.newCharacterId;
          }
        }

        _set({
          status: 'Done',
          isDelegateReady,
          isCharacterInDungeon,
          characterId,
          characterInfo,
          ressurectedId,
          refill,
          insufficientBalance,
        });

        if (isCharacterInDungeon) {
          preDungeon.clear();
          characterChoice.clear();
        }

        store.checkBackIn = async value => {
          const gasEstimate = 4000000; // @TODO: proper estimation
          _set({ status: 'SigningBackIn', delegateAccount });
          let tx;
          try {
            tx = await wallet.tx(
              { gas: gasEstimate + 15000, gasPrice, value },
              'Player',
              'addDelegate',
              delegateAccount.address,
            );
            await tx.wait();
          } catch (e) {
            _set({ status: 'Error', error: { code: 'addDelegate', message: e.toString(), e, wallet } }); // TODO
          }
          const { isDelegateReady, isCharacterInDungeon, insufficientBalance } = await checkCharacter();
          _set({
            status: 'Done',
            isDelegateReady,
            isCharacterInDungeon,
            insufficientBalance,
          });
        };

        store.enter = async ({ ressurectedId, characterInfo }) => {
          const { location } = await fetchCache('entry');
          await wallet
            .tx(
              { gas: BigNumber.from(2000000).toHexString(), gasPrice },
              'Player',
              'enter',
              '0x0000000000000000000000000000000000000000',
              ressurectedId,
              '0',
              characterInfo.characterName,
              '0',
              location || coordinatesToLocation('0,0'),
            )
            .then(tx => tx.wait());
          const { isDelegateReady, isCharacterInDungeon, insufficientBalance } = await checkCharacter();
          _set({
            status: 'Done',
            isDelegateReady,
            isCharacterInDungeon,
            insufficientBalance,
          });
        };

        store.join = async ({ name, characterClass }) => {
          _set({ status: 'Joining' });
          const gasEstimate = BigNumber.from(2000000).toHexString();
          const { price } = config($wallet.chainId);
          const value = BigNumber.from(price).toHexString();

          const { location } = await fetchCache('entry');

          const tx = await wallet.tx(
            { gas: gasEstimate, gasPrice, value },
            'Player',
            'createAndEnter',
            delegateAccount.address,
            0,
            name,
            characterClass,
            location || coordinatesToLocation('0,0'),
          );
          const receipt = await tx.wait();
          console.log({ receipt });
          console.log('gas used for join', BigNumber.from(receipt.gasUsed).toString());

          const { isCharacterInDungeon, isDelegateReady } = await checkCharacter();

          if (isCharacterInDungeon) {
            preDungeon.clear();
            characterChoice.clear();
          }
          _set({
            firstTime: true,
            status: 'Done',
            isDelegateReady,
            isCharacterInDungeon,
          });
        };
      }
    } else {
      lastWalletAddress = null;
      _set({ status: 'None' });
    }
  },
  $data,
)