types#WalletId TypeScript Examples

The following examples show how to use types#WalletId. 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: login.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
export async function createUserWithAddress(
  address: string,
  walletId: WalletId,
  keytype?: string,
  community?: string
): Promise<Account<any>> {
  const account = app.chain.accounts.get(address, keytype);
  const response = await createAccount(account, walletId, community);
  const token = response.result.verification_token;
  const newAccount = app.chain.accounts.get(response.result.address, keytype);
  newAccount.setValidationToken(token);
  newAccount.setAddressId(response.result.id);
  newAccount.setWalletId(walletId);
  return newAccount;
}
Example #2
Source File: login.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
function createAccount(
  account: Account<any>,
  walletId: WalletId,
  community?: string
) {
  return $.post(`${app.serverUrl()}/createAddress`, {
    address: account.address,
    keytype:
      account.chainBase === ChainBase.Substrate && (account as any).isEd25519
        ? 'ed25519'
        : undefined,
    chain: account.chain.id,
    community,
    jwt: app.user.jwt,
    wallet_id: walletId,
  });
}
Example #3
Source File: chain.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
public async sendTx(account: CosmosAccount, tx: EncodeObject): Promise<readonly Event[]> {
    // TODO: error handling
    // TODO: support multiple wallets
    if (this._app.chain.network === ChainNetwork.Terra) {
      throw new Error('Tx not yet supported on Terra');
    }
    const wallet = this.app.wallets.getByName(WalletId.Keplr) as KeplrWebWalletController;
    if (!wallet) throw new Error('Keplr wallet not found');
    if (!wallet.enabled) {
      await wallet.enable();
    }
    const client = await SigningStargateClient.connectWithSigner(this._app.chain.meta.node.url, wallet.offlineSigner);

    // these parameters will be overridden by the wallet
    // TODO: can it be simulated?
    const DEFAULT_FEE: StdFee = {
      gas: '180000',
      amount: [{ amount: (2.5e-8).toFixed(9), denom: this.denom }]
    };
    const DEFAULT_MEMO = '';

    // send the transaction using keplr-supported signing client
    try {
      const result = await client.signAndBroadcast(account.address, [ tx ], DEFAULT_FEE, DEFAULT_MEMO);
      console.log(result);
      if (isBroadcastTxFailure(result)) {
        throw new Error('TX execution failed.');
      } else if (isBroadcastTxSuccess(result)) {
        const txHash = result.transactionHash;
        const txResult = await this._tmClient.tx({ hash: Buffer.from(txHash, 'hex') });
        return txResult.result.events;
      } else {
        throw new Error('Unknown broadcast result');
      }
    } catch (err) {
      console.log(err.message);
      throw err;
    }
  }
Example #4
Source File: web_wallets.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
// sets a WalletId on the backend for an account whose walletId has not already been set
  private async _setWalletId(account: Account<any>, wallet: WalletId): Promise<void> {
    if (app.user.activeAccount.address !== account.address) {
      console.error('account must be active to set wallet id');
      return;
    }

    // do nothing on failure
    try {
      await $.post(`${app.serverUrl()}/setAddressWallet`, {
        address: account.address,
        author_chain: account.chain.id,
        wallet_id: wallet,
        jwt: app.user.jwt
      });
    } catch (e) {
      console.error(`Failed to set wallet for address: ${e.message}`);
    }
  }
Example #5
Source File: linked_addresses_well.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
AccountRow: m.Component<{ account: AddressInfo, onclick?: (e: Event) => any }, { removing }> = {
  view: (vnode): m.Vnode => {
    const { account } = vnode.attrs;
    const isActiveAccount = app.user.activeAccount
      && app.user.activeAccount.chain.id === account.chain
      && app.user.activeAccount.address === account.address;

    return m('.AccountRow', {
      key: `${account.chain}#${account.address}`,
      onclick: vnode.attrs.onclick,
      class: isActiveAccount ? 'selected' : '',
    }, [
      m('.avatar-col', [
        m(User, {
          user: account,
          avatarOnly: true,
          avatarSize: 32,
          linkify: true,
          popover: true
        }),
      ]),
      m('.info-col', [
        m('.username', [
          m(User, {
            user: account,
            hideAvatar: true,
            linkify: true,
            popover: true,
          }),
        ]),
        // checking for balance to guarantee that delegate key has loaded
        m('.address', [
          `${account.address} - ${app.config.chains.getById(account.chain)?.name}`,
          account.walletId === WalletId.Magic && [
            m('br'),
            `Magically linked to ${app.user.email}`,
          ]
        ]),
        (account instanceof MolochMember && account.isMember && account.delegateKey) ? m('.moloch-delegatekey', [
          'Delegate: ',
          account.isMember
            ? link('a', `/${account.chain.id}/account/${account.delegateKey}`, account.delegateKey)
            : 'N/A',
        ]) : [],
      ]),
      m('.action-col', [
        m(Button, {
          intent: 'negative',
          onclick: async () => {
            const confirmed = await confirmationModalWithText('Are you sure you want to remove this account?')();
            if (confirmed) {
              vnode.state.removing = true;
              if (app.user.activeAccount?.address === account.address
                  && app.user.activeAccount?.chain.id === account.chain) {
                app.user.ephemerallySetActiveAccount(null);
              }
              unlinkLogin(account).then(() => {
                vnode.state.removing = false;
                m.redraw();
              });
            }
          },
          rounded: true,
          disabled: vnode.state.removing || app.user.addresses.some((a) => a.walletId === WalletId.Magic),
          loading: vnode.state.removing,
          label: 'Remove',
        }),
      ]),
    ]);
  },
}
Example #6
Source File: AddressInfo.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly walletId: WalletId;
Example #7
Source File: Account.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
private _walletId?: WalletId;
Example #8
Source File: Account.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public setWalletId(walletId: WalletId) {
    this._walletId = walletId;
  }
Example #9
Source File: walletconnect_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.WalletConnect;
Example #10
Source File: terra_station_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.TerraStation;
Example #11
Source File: ronin_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.Ronin;
Example #12
Source File: polkadot_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.Polkadot;
Example #13
Source File: phantom_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.Phantom;
Example #14
Source File: near_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.NearWallet;
Example #15
Source File: metamask_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.Metamask;
Example #16
Source File: keplr_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.Keplr;
Example #17
Source File: cosmos_evm_metamask_web_wallet.ts    From commonwealth with GNU General Public License v3.0 5 votes vote down vote up
public readonly name = WalletId.CosmosEvmMetamask;
Example #18
Source File: select_address_modal.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
SelectAddressModal: m.Component<
  {},
  { selectedIndex: number; loading: boolean }
> = {
  view: (vnode) => {
    const activeAccountsByRole: Array<[Account<any>, RoleInfo]> =
      app.user.getActiveAccountsByRole();
    const activeEntityInfo = app.chain?.meta;
    const createRole = (e) => {
      vnode.state.loading = true;

      const [account, role] = activeAccountsByRole[vnode.state.selectedIndex];
      const addressInfo = app.user.addresses.find(
        (a) => a.address === account.address && a.chain === account.chain.id
      );
      app.user
        .createRole({
          address: addressInfo,
          chain: app.activeChainId(),
        })
        .then(() => {
          vnode.state.loading = false;
          m.redraw();
          vnode.state.selectedIndex = null;
          // select the address, and close the form
          notifySuccess(
            `Joined with ${formatAddressShort(
              addressInfo.address,
              addressInfo.chain,
              true
            )}`
          );
          setActiveAccount(account).then(() => {
            m.redraw();
            $(e.target).trigger('modalexit');
          });
        })
        .catch((err: any) => {
          vnode.state.loading = false;
          m.redraw();
          notifyError(err.responseJSON.error);
        });
    };

    const deleteRole = async (index, e) => {
      vnode.state.loading = true;
      const [account, role] = activeAccountsByRole[index];
      const addressInfo = app.user.addresses.find(
        (a) => a.address === account.address && a.chain === account.chain.id
      );

      // confirm
      const confirmed = await confirmationModalWithText(
        'Remove this address from the community?'
      )();
      if (!confirmed) {
        vnode.state.loading = false;
        m.redraw();
        return;
      }

      app.user
        .deleteRole({
          address: addressInfo,
          chain: app.activeChainId(),
        })
        .then(() => {
          vnode.state.loading = false;
          m.redraw();
          vnode.state.selectedIndex = null;
          // unset activeAccount, or set it to the next activeAccount
          if (isSameAccount(app.user.activeAccount, account)) {
            app.user.ephemerallySetActiveAccount(null);
          }
        })
        .catch((err: any) => {
          vnode.state.loading = false;
          m.redraw();
          notifyError(err.responseJSON.error);
        });
    };

    const chainbase = app.chain
      ? app.chain?.meta?.base
      : ChainBase.Ethereum;

    const activeCommunityMeta = app.chain.meta;
    const hasTermsOfService = !!activeCommunityMeta?.terms;

    return m('.SelectAddressModal', [
      m('.compact-modal-title', [m('h3', 'Manage addresses')]),
      m('.compact-modal-body', [
        activeAccountsByRole.length === 0
          ? m('.select-address-placeholder', [
              m('p', [
                `Connect ${
                  (chainbase && app.chain.network === ChainNetwork.Terra) ? 'Terra' :
                    (chainbase) ? chainbase[0].toUpperCase() + chainbase.slice(1) : 'Web3'
                } address to join this community: `,
              ]),
            ])
          : m('.select-address-options', [
              activeAccountsByRole.map(
                ([account, role], index) =>
                  role &&
                  m('.select-address-option.existing', [
                    m('.select-address-option-left', [
                      m(UserBlock, { user: account }),
                      app.user.addresses.find(
                        (a) =>
                          a.address === account.address &&
                          a.chain === account.chain.id
                      )?.walletId === WalletId.Magic &&
                        m(
                          '.magic-label',
                          `Magically linked to ${app.user.email}`
                        ),
                    ]),
                    m('.role-remove', [
                      m(
                        'span.already-connected',
                        `${formatAsTitleCase(role.permission)} of '${
                          activeEntityInfo?.name
                        }'`
                      ),
                      m(CWIcon, {
                        iconName: 'close',
                        iconSize: 'small',
                        onclick: deleteRole.bind(this, index),
                      }),
                    ]),
                  ])
              ),
              activeAccountsByRole.map(
                ([account, role], index) =>
                  !role &&
                  m(
                    '.select-address-option',
                    {
                      class:
                        vnode.state.selectedIndex === index ? 'selected' : '',
                      onclick: async (e) => {
                        e.preventDefault();
                        vnode.state.selectedIndex = index;
                      },
                    },
                    [
                      m('.select-address-option-left', [
                        m(UserBlock, {
                          user: account,
                          showRole: true,
                          selected: vnode.state.selectedIndex === index,
                        }),
                        app.user.addresses.find(
                          (a) =>
                            a.address === account.address &&
                            a.chain === account.chain.id
                        )?.walletId === WalletId.Magic &&
                          m(
                            '.magic-label',
                            `Magically linked to ${app.user.email}`
                          ),
                      ]),
                      role &&
                        m('.role-permission', [
                          m(Tag, {
                            label: formatAsTitleCase(role.permission),
                            rounded: true,
                            size: 'sm',
                          }),
                          role.is_user_default &&
                            m(Tag, {
                              label: 'Last used',
                              rounded: true,
                              size: 'sm',
                            }),
                        ]),
                    ]
                  )
              ),
            ]),
        hasTermsOfService &&
          m('p.terms-of-service', [
            `By linking an address, you agree to ${activeCommunityMeta.name}'s `,
            m(
              'a',
              { href: activeCommunityMeta.terms, target: '_blank' },
              'terms of service'
            ),
            '.',
          ]),
        activeAccountsByRole.length !== 0 &&
          m(Button, {
            label: 'Join community with address',
            intent: 'primary',
            compact: true,
            fluid: true,
            rounded: true,
            disabled:
              vnode.state.selectedIndex === undefined || vnode.state.loading,
            onclick: createRole.bind(this),
          }),
        m(LoginWithWalletDropdown, {
          loggingInWithAddress: false,
          joiningChain: app.activeChainId(),
          label:
            activeAccountsByRole.length !== 0
              ? 'Connect a new address'
              : 'Connect address',
          onSuccess: () => {
            $('.SelectAddressModal').trigger('modalexit');
            notifySuccess('New address connected!');
          },
        }),
      ]),
    ]);
  },
}
Example #19
Source File: finish_near_login.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
validate = async (
  vnode: m.Vnode<Record<string, never>, IState>,
  wallet: WalletConnection
) => {
  try {
    // TODO: do we need to do this every time, or only on first connect?
    const acct: NearAccount = app.chain.accounts.get(wallet.getAccountId());
    await createUserWithAddress(acct.address, WalletId.NearWallet);
    const signature = await acct.signMessage(`${acct.validationToken}\n`);
    await acct.validate(signature);
    if (!app.isLoggedIn()) {
      await initAppState();
      const chain = app.user.selectedChain || app.config.chains.getById(app.activeChainId());
      await updateActiveAddresses(chain);
    }
    await setActiveAccount(acct);
    vnode.state.validatedAccount = acct;
  } catch (err) {
    vnode.state.validationError = err.responseJSON
      ? err.responseJSON.error
      : err.message;
    return;
  }

  // tx error handling
  const failedTx = m.route.param('tx_failure');
  if (failedTx) {
    console.log(`Login failed: deleting storage key ${failedTx}`);
    if (localStorage[failedTx]) {
      delete localStorage[failedTx];
    }
    vnode.state.validationError = 'Login failed.';
    return;
  }

  // tx success handling
  // TODO: ensure that create() calls redirect correctly
  const savedTx = m.route.param('saved_tx');
  if (savedTx && localStorage[savedTx]) {
    try {
      // fetch tx localstorage hash and execute
      const txString = localStorage[savedTx];
      delete localStorage[savedTx];

      // tx object
      const tx = JSON.parse(txString);
      // rehydrate BN
      if (tx.attachedDeposit) {
        tx.attachedDeposit = new BN(tx.attachedDeposit);
      }
      if (tx.gas) {
        tx.gas = new BN(tx.gas);
      }
      await wallet.account().functionCall(tx as FunctionCallOptions);
    } catch (err) {
      vnode.state.validationError = err.message;
    }
  }

  // create new chain handling
  // TODO: we need to figure out how to clean this localStorage entry up
  //   in the case of transaction failure!!
  const chainName = m.route.param('chain_name');
  if (chainName && localStorage[chainName]) {
    try {
      const chainCreateArgString = localStorage[chainName];
      delete localStorage[chainName];

      // POST object
      const chainCreateArgs = JSON.parse(chainCreateArgString);
      const res = await $.post(
        `${app.serverUrl()}/createChain`,
        chainCreateArgs
      );
      await initAppState(false);
      m.route.set(`${window.location.origin}/${res.result.chain.id}`);
    } catch (err) {
      vnode.state.validationError = `Failed to initialize chain node: ${err.message}`;
    }
  }
}
Example #20
Source File: email_well.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
EmailWell: m.Component<IAttrs, IState> = {
  oninit: (vnode) => {
    vnode.state.email = app.user.email;
    vnode.state.emailInputUpdated = false;
    vnode.state.verificationSent = false;
    vnode.state.emailVerified = app.user.emailVerified;
    vnode.state.githubAccount = app.user.socialAccounts.find(
      (sa) => sa.provider === 'github'
    );
    vnode.state.discordAccount = app.user.socialAccounts.find(
      (sa) => sa.provider === 'discord'
    );
    vnode.state.errorMessage = null;
  },
  view: (vnode) => {
    const {
      email,
      githubAccount,
      discordAccount,
      emailInputUpdated,
      emailVerified,
      verificationSent,
      errorMessage,
    } = vnode.state;
    return [
      m('.EmailWell', [
        m('h4', 'Login'),
        m(Input, {
          placeholder: '[email protected]',
          contentLeft: m(Icon, { name: Icons.MAIL }),
          defaultValue: app.user.email || null,
          oninput: (e) => {
            vnode.state.emailInputUpdated = true;
            vnode.state.verificationSent = false;
            vnode.state.email = (e.target as any).value;
          },
        }),
        (!app.user.email || emailInputUpdated || !emailVerified) &&
          m(Button, {
            intent: 'primary',
            label:
              app.user.email && !emailInputUpdated && !emailVerified
                ? 'Retry verification'
                : 'Update email',
            class: 'update-email-button',
            disabled:
              (!emailInputUpdated && emailVerified) ||
              verificationSent ||
              app.user.addresses.some((a) => a.walletId === WalletId.Magic),
            rounded: true,
            onclick: async () => {
              vnode.state.errorMessage = null;
              const confirmed = await confirmationModalWithText(
                'You will be required to confirm your new email address. Continue?'
              )();
              if (!confirmed) return;
              try {
                const response = await $.post(
                  `${app.serverUrl()}/updateEmail`,
                  {
                    email: vnode.state.email,
                    jwt: app.user.jwt,
                  }
                );
                vnode.state.emailVerified = false;
                vnode.state.verificationSent = true;
                vnode.state.errorMessage = null;
                m.redraw();
              } catch (err) {
                vnode.state.errorMessage = err.responseJSON.error;
                m.redraw();
                console.log('Failed to update email');
                throw new Error(
                  err.responseJSON && err.responseJSON.error
                    ? err.responseJSON.error
                    : 'Failed to update email'
                );
              }
            },
          }),
        verificationSent
          ? m(
              'label',
              {
                style: {
                  color: Colors.GREEN500,
                  position: 'relative',
                  top: '2px',
                },
              },
              'Check your email for a confirmation link'
            )
          : [
              m(Icon, {
                size: 'lg',
                intent: emailVerified ? 'positive' : 'warning',
                name: emailVerified ? Icons.CHECK_CIRCLE : Icons.ALERT_CIRCLE,
              }),
              m(
                'label',
                {
                  style: {
                    color: emailVerified ? Colors.GREEN500 : '#f57c01',
                    position: 'relative',
                    top: '2px',
                  },
                },
                emailVerified
                  ? 'Verified'
                  : app.user.email
                  ? 'Not verified'
                  : 'No email'
              ),
            ],
        errorMessage && m('p.error', errorMessage),
      ]),
      m('.LinkButtonWrapper', [
        vnode.attrs.github &&
          m('.GithubWell', [
            m('form', [
              githubAccount &&
                m(Input, {
                  value: `github.com/${githubAccount.username || ''}`,
                  contentLeft: m(Icon, { name: Icons.GITHUB }),
                  disabled: true,
                }),
              m(Button, {
                label: githubAccount ? 'Unlink Github' : 'Link Github',
                intent: githubAccount ? 'negative' : 'primary',
                rounded: true,
                onclick: () => {
                  if (githubAccount) {
                    $.ajax({
                      url: `${app.serverUrl()}/githubAccount`,
                      data: { jwt: app.user.jwt },
                      type: 'DELETE',
                      success: (result) => {
                        vnode.state.githubAccount = null;
                        m.redraw();
                      },
                      error: (err) => {
                        console.dir(err);
                        m.redraw();
                      },
                    });
                  } else {
                    localStorage.setItem(
                      'githubPostAuthRedirect',
                      JSON.stringify({
                        timestamp: (+new Date()).toString(),
                        path: m.route.get(),
                      })
                    );
                    document.location = `${app.serverUrl()}/auth/github` as any;
                    m.redraw();
                  }
                },
              }),
            ]),
          ]),
        m('.DiscordWell', [
          m('form', [
            discordAccount &&
              m(Input, {
                value: `${discordAccount.username || ''}`,
                contentLeft: m(Icon, { name: Icons.DISC }), // TODO: add a discord icon
                disabled: true,
              }),
            m(Button, {
              label: discordAccount ? 'Unlink Discord' : 'Link Discord',
              intent: discordAccount ? 'negative' : 'primary',
              rounded: true,
              onclick: () => {
                if (discordAccount) {
                  $.ajax({
                    url: `${app.serverUrl()}/discordAccount`,
                    data: { jwt: app.user.jwt },
                    type: 'DELETE',
                    success: (result) => {
                      vnode.state.discordAccount = null;
                      m.redraw();
                    },
                    error: (err) => {
                      console.dir(err);
                      m.redraw();
                    },
                  });
                } else {
                  localStorage.setItem(
                    'discordPostAuthRedirect',
                    JSON.stringify({
                      timestamp: (+new Date()).toString(),
                      path: m.route.get(),
                    })
                  );
                  document.location = `${app.serverUrl()}/auth/discord` as any;
                  m.redraw();
                }
              },
            }),
          ]),
        ]),
      ]),
    ];
  },
}