• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Mintbase / mintbase-js / 8233788221

11 Mar 2024 01:38PM UTC coverage: 76.955%. First build
8233788221

Pull #486

github

sainthiago
add condition
Pull Request #486: Add allKeys param to mintbase-wallet

860 of 1307 branches covered (65.8%)

Branch coverage included in aggregate %.

1177 of 1340 relevant lines covered (87.84%)

13.24 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

24.53
/packages/react/src/wallet/wallet.ts
1
import {
3✔
2
  setupWalletSelector,
3
  VerifiedOwner,
4
  VerifyOwnerParams,
5
  Wallet,
6
} from '@near-wallet-selector/core';
7
import { setupModal } from '@near-wallet-selector/modal-ui';
3✔
8
import { map, distinctUntilChanged, Subscription } from 'rxjs';
3✔
9

10
import {
3✔
11
  WALLET_CONNECTION_POLL_INTERVAL,
12
  WALLET_CONNECTION_TIMEOUT,
13
} from './constants';
14

15
import { setupMeteorWallet } from '@near-wallet-selector/meteor-wallet';
3✔
16
import { setupHereWallet } from '@near-wallet-selector/here-wallet';
3✔
17
import { setupMyNearWallet } from '@near-wallet-selector/my-near-wallet';
3✔
18

19
import type {
20
  WalletSelector,
21
  AccountState,
22
  WalletModuleFactory,
23
} from '@near-wallet-selector/core';
24
import type { WalletSelectorModal } from '@near-wallet-selector/modal-ui';
25
import { setupMintbaseWallet } from '@mintbase-js/wallet';
3✔
26

27
// error messages
28
const SUPPORT = '- further help available on our telegram channel: https://t.me/mintdev';
3✔
29

30
export const ERROR_MESSAGES =  {
3✔
31
  WALLET_SETUP_NOT_CALLED_ERROR : `Call and await setupWalletSelectorComponents() before registering a subscriber - ${SUPPORT}`,
32
  WALLET_CONNECTION_NOT_FOUND:  `Wallet connection not received after ${WALLET_CONNECTION_TIMEOUT}ms - ${SUPPORT}`,
33
};
34

35
export const SUPPORTED_NEAR_WALLETS: Array<WalletModuleFactory> =[
3✔
36
  setupMeteorWallet(),
37
  setupMyNearWallet(),
38
  setupHereWallet(),
39
];
40

41
// mintbase SDK wallet functionality wraps
42
// Near Wallet Selector lib, provided by NEAR Protocol
43
// https://github.com/near/wallet-selector/
44

45
export type WalletSelectorComponents = {
46
  selector: WalletSelector;
47
  modal: WalletSelectorModal;
48
}
49

50
// wallet components are held and exposed as a singleton reference
51
// this way they can be more easily passed to other components vs composing calls.
52
export let walletSelectorComponents: WalletSelectorComponents = {
3✔
53
  selector: null,
54
  modal: null,
55
};
56

57
/**
58
 * Set up wallet selector components. Returns the modal
59
 * See also docs on {@link https://github.com/near/wallet-selector/ | near wallet selector}
60
 */
61

62
const walletUrls = {
3✔
63
  testnet: 'https://testnet.wallet.mintbase.xyz/',
64
  mainnet: 'https://wallet.mintbase.xyz',
65
};
66

67
// eslint-disable-next-line max-len
68
export const setupMintbaseWalletSelector = async (
3✔
69
  callbackUrl,
70
  onlyMbWallet = false,
×
71
  network?,
72
  contractAddress?,
73
  options?: { additionalWallets?: Array<WalletModuleFactory> },
74
  successUrl?: string,
75
  failureUrl?: string,
76
): Promise<WalletSelectorComponents> => {
×
77

78

79
  if (onlyMbWallet === false) {
×
80
    walletSelectorComponents.selector = await setupWalletSelector({
×
81
      network: network,
82
      modules: [
83
        setupMintbaseWallet({
84
          walletUrl: walletUrls[network],
85
          callbackUrl: callbackUrl,
86
          successUrl: successUrl || window.location.href,
×
87
          failureUrl: successUrl || window.location.href,
×
88
          contractId: contractAddress,
89
        }),
90
        ...(options?.additionalWallets || []),
×
91
        ...SUPPORTED_NEAR_WALLETS,
92
      ],
93
    });
94
  } else {
95
    walletSelectorComponents.selector = await setupWalletSelector({
×
96
      network: network,
97
      modules: [
98
        setupMintbaseWallet({
99
          walletUrl: walletUrls[network],
100
          callbackUrl: callbackUrl,
101
          contractId: contractAddress,
102
        }),
103
        ...(options?.additionalWallets || []),
×
104
      ],
105
    });
106
  }
107

108
  walletSelectorComponents.modal = setupModal(walletSelectorComponents.selector, {
×
109
    contractId: contractAddress,
110
  });
111

112
  return walletSelectorComponents;
×
113
};
114

115
export const setupWalletSelectorComponents = async (
3✔
116
  network?,
117
  contractAddress?,
118
  options?: { additionalWallets?: Array<WalletModuleFactory> },
119
): Promise<WalletSelectorComponents> => {
×
120
  const selector = await setupWalletSelector({
×
121
    network: network,
122
    modules: [
123
      ...SUPPORTED_NEAR_WALLETS,
124
      ...(options?.additionalWallets || []),
×
125
    ],
126
  });
127

128
  const modal = setupModal(selector, {
×
129
    contractId: contractAddress,
130
  });
131

132
  walletSelectorComponents = {
×
133
    selector,
134
    modal,
135
  };
136
  return walletSelectorComponents;
×
137
};
138

139
export class SetupNotCalledError extends Error {
3✔
140
  message: string
141
}
142

143
export class ConnectionTimeoutError extends Error {
3✔
144
  message: string
145
}
146

147
const validateWalletComponentsAreSetup = (): void => {
3✔
148
  if (!walletSelectorComponents.selector) {
×
149
    throw new SetupNotCalledError(ERROR_MESSAGES.WALLET_SETUP_NOT_CALLED_ERROR);
×
150
  }
151
};
152

153
export const registerWalletAccountsSubscriber = (
3✔
154
  callback: (accounts: AccountState[]) => void,
155
): Subscription => {
156
  validateWalletComponentsAreSetup();
×
157

158
  return walletSelectorComponents.selector.store.observable
×
159
    .pipe(
160
      map((state) => state.accounts),
×
161
      distinctUntilChanged(),
162
    )
163
    .subscribe(callback);
164
};
165

166
// scoped to module and cleared since pollForWalletConnection might
167
// get called repeatedly in react enviroments
168
let timerReference = null;
3✔
169

170
export const pollForWalletConnection = async (): Promise<AccountState[]> => {
3✔
171
  validateWalletComponentsAreSetup();
×
172
  // clear any existing timer
173
  clearTimeout(timerReference);
×
174

175
  const tryToResolveAccountsFromState = (
×
176
    resolve: (value: AccountState[]) => void,
177
    reject: (err: ConnectionTimeoutError) => void,
178
    elapsed = 0,
×
179
  ): void => {
180
    const { accounts } =
181
      walletSelectorComponents.selector.store.getState() || {};
×
182

183
    // accounts present in state
184
    if (accounts) {
×
185
      resolve(accounts);
×
186
    }
187

188
    // timed out
189
    if (elapsed > WALLET_CONNECTION_TIMEOUT) {
×
190
      reject(
×
191
        new ConnectionTimeoutError(ERROR_MESSAGES.WALLET_CONNECTION_NOT_FOUND),
192
      );
193
    }
194

195
    // try again
196
    clearTimeout(timerReference);
×
197
    timerReference = setTimeout(
×
198
      () =>
199
        tryToResolveAccountsFromState(
×
200
          resolve,
201
          reject,
202
          elapsed + WALLET_CONNECTION_POLL_INTERVAL,
203
        ),
204
      WALLET_CONNECTION_POLL_INTERVAL,
205
    );
206
  };
207

208
  return new Promise((resolve, reject) =>
×
209
    tryToResolveAccountsFromState(resolve, reject),
×
210
  );
211
};
212

213
export const getWallet = async (): Promise<Wallet> => {
3✔
214
  validateWalletComponentsAreSetup();
×
215

216
  return await walletSelectorComponents.selector.wallet();
×
217
};
218

219
export const connectWalletSelector = (): void => {
3✔
220
  validateWalletComponentsAreSetup();
×
221

222
  walletSelectorComponents.modal.show();
×
223
};
224

225
export const disconnectFromWalletSelector = async (): Promise<void> => {
3✔
226
  validateWalletComponentsAreSetup();
×
227

228
  const wallet = await walletSelectorComponents.selector.wallet();
×
229
  wallet.signOut();
×
230
};
231

232
export const getVerifiedOwner = async (
3✔
233
  params: VerifyOwnerParams,
234
): Promise<VerifiedOwner | undefined> => {
×
235
  validateWalletComponentsAreSetup();
×
236

237
  const { message, callbackUrl, meta } = params;
×
238

239
  const wallet = await walletSelectorComponents.selector.wallet();
×
240

241
  const owner = (await wallet.verifyOwner({
×
242
    message: message,
243
    callbackUrl: callbackUrl,
244
    meta: meta,
245
  })) as VerifiedOwner;
246

247
  return owner;
×
248
};
249

250
// returns a signature of message
251
export const signMessage = async (
3✔
252
  params: VerifyOwnerParams,
253
): Promise<VerifiedOwner> => {
×
254
  const owner = await getVerifiedOwner(params);
×
255

256
  return owner;
×
257
};
258

259

260
//  https://www.npmjs.com/package/bs58
261
// https://github.com/feross/buffer
262
// https://github.com/near/wallet-selector/issues/434
263
// export const verifyMessage = async (signature: string): Promise<boolean> => {
264

265
//   // const owner = await getVerifiedOwner(signature);
266

267
//   // const publicKeyString = `ed25519:${BinaryToBase58(Buffer.from(owner.publicKey, 'base64'))}`;
268

269
//   // const createdPublicKey = utils.PublicKey.from(publicKeyString);
270

271
//   // const stringified = JSON.stringify(owner);
272

273
//   // const verified = createdPublicKey.verify(new Uint8Array(sha256.array(stringified)), Buffer.from(signature, 'base64'));
274

275
//   return false;
276
// };
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc