@polkadot/api/types#UnsubscribePromise TypeScript Examples

The following examples show how to use @polkadot/api/types#UnsubscribePromise. 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: Events.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
subscribeToLogEvents(callback: IEventCallback<LogEvent>): UnsubscribePromise {
    return this.api.query.system.events((events) => {
      events
        .filter(({ event }) => this.api.events.gear.Log.is(event))
        .forEach(({ event }) => {
          setTimeout(() => {
            callback(new LogEvent(event));
          }, 100);
        });
    });
  }
Example #2
Source File: Events.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
subscribeToProgramEvents(callback: IEventCallback<ProgramEvent>): UnsubscribePromise {
    return this.api.query.system.events((events) => {
      events
        .filter(({ event }) => this.api.events.gear.InitSuccess.is(event) || this.api.events.gear.InitFailure.is(event))
        .forEach(({ event }) => {
          setTimeout(() => {
            callback(new ProgramEvent(event));
          }, 100);
        });
    });
  }
Example #3
Source File: Events.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
subscribeToTransferEvents(callback: IEventCallback<TransferEvent>): UnsubscribePromise {
    return this.api.query.system.events((events) => {
      events
        .filter(({ event }) => this.api.events.balances.Transfer.is(event))
        .forEach(({ event }) => {
          callback(new TransferEvent(event));
        });
    });
  }
Example #4
Source File: Events.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
async subscribeToBalanceChange(accountAddress: string, callback: IBalanceCallback): UnsubscribePromise {
    let {
      data: { free: previousFree },
    } = (await this.api.query.system.account(accountAddress)) as ISystemAccountInfo;

    return this.api.query.system.account(accountAddress, ({ data: { free: currentFree } }) => {
      if (!currentFree.sub(previousFree).isZero()) {
        callback(this.api.createType('Balance', currentFree));
        previousFree = currentFree;
      }
    });
  }
Example #5
Source File: api.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
function useBalanceSubscription() {
  const { api } = useApi();
  const { account, updateBalance } = useAccount();

  useEffect(() => {
    let unsub: UnsubscribePromise | undefined;

    if (account) {
      unsub = api?.gearEvents.subscribeToBalanceChange(account.address, updateBalance);
    }

    return () => {
      if (unsub) unsub.then((callback) => callback());
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api, account]);
}
Example #6
Source File: useBalanceSubscription.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
function useBalanceSubscription() {
  const { api } = useApi();
  const { account, updateBalance } = useAccount();

  const { address } = account || {};

  useEffect(() => {
    let unsub: UnsubscribePromise | undefined;

    if (address) {
      unsub = api?.gearEvents.subscribeToBalanceChange(address, updateBalance);
    }

    return () => {
      if (unsub) unsub.then((callback) => callback());
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api, address]);
}
Example #7
Source File: useSubscription.tsx    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
export function useSubscription(callback: () => UnsubscribePromise) {
  const { api } = useApi();

  useEffect(() => {
    let unsub: UnsubscribePromise | undefined;

    if (api) {
      unsub = callback();
    }

    return () => {
      if (unsub) {
        (async () => {
          (await unsub)();
        })();
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api]);
}
Example #8
Source File: useApiSubscription.ts    From parity-bridges-ui with GNU General Public License v3.0 6 votes vote down vote up
export function useApiSubscription(fn: () => Promise<unknown>, isReady: boolean): void {
  useEffect(() => {
    if (!isReady) {
      return;
    }

    try {
      const unsub = fn() as UnsubscribePromise;
      return () => {
        isReady &&
          unsub &&
          unsub
            .then((u) => u())
            .catch((e) => {
              logger.error('error unsubscribing', e);
            });
      };
    } catch (e) {
      logger.error('error executing subscription', e);
    }
  }, [fn, isReady]);
}
Example #9
Source File: DebugMode.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
snapshots(callback: (event: DebugDataSnapshotEvent) => void | Promise<void>): UnsubscribePromise {
    return this.api.query.system.events((events) => {
      events
        .filter(({ event }) => this.api.events.gearDebug.DebugDataSnapshot.is(event))
        .forEach(({ event }) => callback(new DebugDataSnapshotEvent(event)));
    });
  }
Example #10
Source File: Events.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
subscribeToNewBlocks(callback: IBlocksCallback): UnsubscribePromise {
    return this.api.rpc.chain.subscribeNewHeads((header) => {
      callback(header);
    });
  }
Example #11
Source File: Mailbox.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
subscription: UnsubscribePromise;
Example #12
Source File: Account.tsx    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
function AccountProvider({ children }: Props) {
  const { api } = useApi();

  const [accounts, setAccounts] = useState<InjectedAccountWithMeta[]>();
  const [account, setAccount] = useState<Account>();

  const getAccounts = (extensions: InjectedExtension[]) => (extensions.length > 0 ? web3Accounts() : undefined);

  useEffect(() => {
    setTimeout(() => {
      web3Enable('Gear App').then(getAccounts).then(setAccounts);
    }, 300);
  }, []);

  const getBalance = (balance: Balance) => {
    const [value, unit] = balance.toHuman().split(' ');
    return { value, unit };
  };

  const getAccount = (_account: InjectedAccountWithMeta, balance: Balance) => ({
    ..._account,
    balance: getBalance(balance),
    decodedAddress: GearKeyring.decodeAddress(_account.address),
  });

  const switchAccount = (_account: InjectedAccountWithMeta) => {
    api?.balance
      .findOut(_account.address)
      .then((balance) => getAccount(_account, balance))
      .then(setAccount);
  };

  const logout = () => {
    setAccount(undefined);
  };

  useEffect(() => {
    const loggedInAccount = accounts?.find(isLoggedIn);
    if (loggedInAccount) switchAccount(loggedInAccount);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api, accounts]);

  const updateBalance = (balance: Balance) => {
    setAccount((prevAccount) => ({ ...prevAccount!, balance: getBalance(balance) }));
  };

  useEffect(() => {
    let unsub: UnsubscribePromise | undefined;

    if (account) {
      unsub = api?.gearEvents.subscribeToBalanceChange(account.address, updateBalance);
    }

    return () => {
      if (unsub) unsub.then((callback) => callback());
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [api, account]);

  const { Provider } = AccountContext;
  const value = { accounts, account, switchAccount, logout };

  return <Provider value={value}>{children}</Provider>;
}
Example #13
Source File: initApi.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
readonly subscriptions: Record<string, UnsubscribePromise> = {};
Example #14
Source File: Wallet.tsx    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
Wallet = () => {
  const { api } = useApi();
  const accounts = useAccounts();
  const { account } = useAccount();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [accountBalance, setAccountBalance] = useState('');

  useEffect(() => {
    if (account && api) {
      api.balance.findOut(account.address).then((result) => setAccountBalance(result.toHuman()));
    }
  }, [account, api]);

  useEffect(() => {
    // TODO: think how to wrap it hook
    let unsub: UnsubscribePromise | undefined;

    if (account && api) {
      unsub = api.gearEvents.subscribeToBalanceChange(account.address, (balance) => {
        setAccountBalance(balance.toHuman());
      });
    }

    return () => {
      if (unsub) {
        unsub.then((callback) => callback());
      }
    };
  }, [api, account]);

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  const balanceSectionClassName = clsx(styles.section, styles.balance);
  const accButtonClassName = clsx(
    buttonStyles.button,
    buttonStyles.normal,
    buttonStyles.secondary,
    styles.accountButton
  );

  return (
    <>
      <div className={styles.wallet}>
        {account ? (
          <>
            <div className={balanceSectionClassName}>
              <p>
                Balance: <span className={styles.balanceAmount}>{accountBalance}</span>
              </p>
            </div>
            <div className={styles.section}>
              <button type="button" className={accButtonClassName} onClick={openModal}>
                <Identicon value={account.address} size={28} theme="polkadot" className={styles.avatar} />
                {account.meta.name}
              </button>
            </div>
          </>
        ) : (
          <div>
            <Button text="Connect" color="secondary" className={styles.accountButton} onClick={openModal} />
          </div>
        )}
      </div>
      <SelectAccountModal isOpen={isModalOpen} accounts={accounts} onClose={closeModal} />
    </>
  );
}
Example #15
Source File: subscriptions.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
export async function listenLog(api: GearApi, callback: (logData: LogData) => void): UnsubscribePromise {
  return await api.gearEvents.subscribeToLogEvents((event) => {
    callback(event.data);
  });
}
Example #16
Source File: subscriptions.ts    From gear-js with GNU General Public License v3.0 5 votes vote down vote up
export async function listenInit(
  api: GearApi,
  callback: (info: MessageInfo, reason?: Reason) => void,
): UnsubscribePromise {
  return api.gearEvents.subscribeToProgramEvents((event) => {
    callback(event.data.info, event.data.reason);
  });
}