Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add the new toggle functionality #1152

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/core/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
export const PACKAGE_NAME = "near-wallet-selector";
export const RECENTLY_SIGNED_IN_WALLETS = "recentlySignedInWallets";
export const REMEMBER_RECENT_WALLETS = "rememberRecentWallets";
export const REMEMBER_RECENT_WALLETS_STATE = {
ENABLED: "enabled",
DISABLED: "disabled",
};

export const CONTRACT = "contract";
export const PENDING_CONTRACT = "contract:pending";
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "استخدم محفظة لتأمين وإدارة أصول نير الخاصة بك، وادخل لأي تطبيق يستخدم نير دون الحاجة إلى اسم المستخدم وكلمةالمرور",
"connectionFailed": "اتصال فاشل",
"connectionSuccessful": "اتصال ناجح",
"rememberWallet": "تذكر المحافظ",
"connected": "متصل",
"connectingTo": "جاري الاتصال ب",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/bg.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Използвайте портфейла, за да защитите и управлявате активите си на NEAR както и да използвате всяко приложение на NEAR без нужда от потребителски имена и пароли.",
"connectionFailed": "Свързването неуспешно",
"connectionSuccessful": "Свързването успешно",
"rememberWallet": "Запази портфейлите",
"connected": "Свързан",
"connectingTo": "Свързване към",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Use a wallet to secure and manage your NEAR assets, and to log in to any NEAR app without the need for usernames and passwords.",
"connectionFailed": "Connection Failed",
"connectionSuccessful": "Connection Successful",
"rememberWallet": "Remember wallets",
"connected": "Connected",
"connectingTo": "Connecting to",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Usa tu Billetera para resguardar y administrar tus activos en NEAR, e Iniciar sesión en cualquier aplicacion NEAR sin la necesidad de nombres de usuarios y contraseñas",
"connectionFailed": "Conexión Fallida",
"connectionSuccessful": "Conexión Existosa",
"rememberWallet": "Recordar las carteras",
"connected": "Conectado",
"connectingTo": "Conectando a ",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "अपनी NEAR संपत्तियों को सुरक्षित और प्रबंधित करने के लिए वॉलेट का उपयोग करें और किसी भी NEAR ऐप (app) में लॉग इन करें, किसी उपयोगकर्ता (user) नाम और पासवर्ड की आवश्यकता नहीं है।",
"connectionFailed": "कनेक्शन विफल|",
"connectionSuccessful": "कनेक्शन सफल|",
"rememberWallet": "वॉलेटों को याद रखें",
"connected": "वॉलेट जुड़ गया|",
"connectingTo": "वॉलेट जुड़ रहा हे|",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/hr.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Koristite crypto novčanik da biste osigurali i upravljali svojom NEAR imovinom, te se prijavite u bilo koju NEAR aplikaciju bez korisničkog imena i lozinke.",
"connectionFailed": "Neuspješno povezivanje.",
"connectionSuccessful": "Uspješno povezivanje.",
"rememberWallet": "Zapamti novčanike",
"connected": "Povezano.",
"connectingTo": "Povezivanje u tijeku",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "지갑을 사용하여 NEAR 자산을 보호·관리하고, 아이디와 비밀번호 없이 NEAR 앱에 로그인할 수 있습니다.",
"connectionFailed": "연결 실패",
"connectionSuccessful": "연결 성공",
"rememberWallet": "지갑들 기억하기",
"connected": "Connected",
"connectingTo": "연결 중: ",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/mk.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Користете паричник за да ги заштитите и управувате вашите NEAR средства и да се најавите на која било NEAR апликација без потреба од кориснички имиња и лозинки.",
"connectionFailed": "Поврзувањето не беше успешно.",
"connectionSuccessful": "Успешно поврзување.",
"rememberWallet": "Запомни паричници",
"connected": "Поврзано.",
"connectingTo": "Поврзување со",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/sl.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Uporabite denarnico, da bi zavarovali in upravljali s svoja NEAR digitalna sredstva, in se prijavite v katero koli aplikacijo ekosistema NEAR",
"connectionFailed": "Povezava ni bila uspešna.",
"connectionSuccessful": "Povezava je bila uspešna.",
"rememberWallet": "Zapomni si denarnice",
"connected": "Vaša denarnica je povezana.",
"connectingTo": "Povezovanje z",
"connectingMessage": {
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/lib/locale/sr.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Користите новчаник да обезбедите и управљате својим NEAR средствима и да се пријавите у било коју апликацију NEAR без потребе за корисничким именима и лозинкама.",
"connectionFailed": "Веза није успостављена.",
"connectionSuccessful": "Веза је успела.",
"rememberWallet": "Запамти новчанике",
"connected": "Повезан.",
"connectingTo": "Повезивање на",
"connectingMessage": {
Expand Down Expand Up @@ -103,4 +104,4 @@
}
}
}
}
}
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/vi.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "Sử dụng ví để bảo mật và quản lý tài sản trên NEAR của bạn và đăng nhập vào bất kỳ ứng dụng NEAR nào, không cần tên người dùng và mật khẩu.",
"connectionFailed": "Kết nối thất bại",
"connectionSuccessful": "Kết nối thành công",
"rememberWallet": "Ghi nhớ lựa chọn ví",
"connected": "Đã kết nối",
"connectingTo": "Đang kết nối tới",
"connectingMessage": {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/lib/locale/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"useAWallet": "使用钱包来保护和管理你的 NEAR 资产,无需用户名和密码即可登录任何 NEAR 应用",
"connectionFailed": "连接失败",
"connectionSuccessful": "连接成功",
"rememberWallet": "记住钱包选择",
"connected": "已连接",
"connectingTo": "正在连接"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import {
PACKAGE_NAME,
PENDING_CONTRACT,
PENDING_SELECTED_WALLET_ID,
REMEMBER_RECENT_WALLETS,
REMEMBER_RECENT_WALLETS_STATE,
} from "../../constants";
import { JsonStorage } from "../storage/json-storage.service";
import type { ProviderService } from "../provider/provider.service.types";
Expand Down Expand Up @@ -81,6 +83,9 @@ export class WalletModules {
const pendingContract = await jsonStorage.getItem<ContractState>(
PENDING_CONTRACT
);
const rememberRecentWallets = await jsonStorage.getItem<string>(
REMEMBER_RECENT_WALLETS
);

if (pendingSelectedWalletId && pendingContract) {
const accounts = await this.validateWallet(pendingSelectedWalletId);
Expand All @@ -99,14 +104,18 @@ export class WalletModules {
});
}

const recentlySignedInWalletsFromPending =
await this.setWalletAsRecentlySignedIn(pendingSelectedWalletId);

let recentlySignedInWalletsFromPending: Array<string> = [];
if (rememberRecentWallets === REMEMBER_RECENT_WALLETS_STATE.ENABLED) {
recentlySignedInWalletsFromPending =
await this.setWalletAsRecentlySignedIn(pendingSelectedWalletId);
}
return {
accounts,
contract: pendingContract,
selectedWalletId: pendingSelectedWalletId,
recentlySignedInWallets: recentlySignedInWalletsFromPending,
rememberRecentWallets:
rememberRecentWallets || REMEMBER_RECENT_WALLETS_STATE.ENABLED,
};
}
}
Expand All @@ -124,6 +133,8 @@ export class WalletModules {
contract: null,
selectedWalletId: null,
recentlySignedInWallets: recentlySignedInWallets || [],
rememberRecentWallets:
rememberRecentWallets || REMEMBER_RECENT_WALLETS_STATE.ENABLED,
};
}

Expand All @@ -132,6 +143,8 @@ export class WalletModules {
contract,
selectedWalletId,
recentlySignedInWallets: recentlySignedInWallets || [],
rememberRecentWallets:
rememberRecentWallets || REMEMBER_RECENT_WALLETS_STATE.ENABLED,
};
}

Expand Down Expand Up @@ -174,7 +187,7 @@ export class WalletModules {
walletId: string,
{ accounts, contractId, methodNames }: WalletEvents["signedIn"]
) {
const { selectedWalletId } = this.store.getState();
const { selectedWalletId, rememberRecentWallets } = this.store.getState();
const jsonStorage = new JsonStorage(this.storage, PACKAGE_NAME);
const contract = { contractId, methodNames };

Expand All @@ -194,13 +207,22 @@ export class WalletModules {
await this.signOutWallet(selectedWalletId);
}

const recentlySignedInWallets = await this.setWalletAsRecentlySignedIn(
walletId
);
let recentlySignedInWallets: Array<string> = [];
if (rememberRecentWallets === REMEMBER_RECENT_WALLETS_STATE.ENABLED) {
recentlySignedInWallets = await this.setWalletAsRecentlySignedIn(
walletId
);
}

this.store.dispatch({
type: "WALLET_CONNECTED",
payload: { walletId, contract, accounts, recentlySignedInWallets },
payload: {
walletId,
contract,
accounts,
recentlySignedInWallets,
rememberRecentWallets,
},
});

this.emitter.emit("signedIn", {
Expand Down Expand Up @@ -411,8 +433,13 @@ export class WalletModules {

this.modules = modules;

const { accounts, contract, selectedWalletId, recentlySignedInWallets } =
await this.resolveStorageState();
const {
accounts,
contract,
selectedWalletId,
recentlySignedInWallets,
rememberRecentWallets,
} = await this.resolveStorageState();

this.store.dispatch({
type: "SETUP_WALLET_MODULES",
Expand All @@ -422,6 +449,7 @@ export class WalletModules {
contract,
selectedWalletId,
recentlySignedInWallets,
rememberRecentWallets,
},
});

Expand Down
39 changes: 39 additions & 0 deletions packages/core/src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
CONTRACT,
SELECTED_WALLET_ID,
RECENTLY_SIGNED_IN_WALLETS,
REMEMBER_RECENT_WALLETS,
REMEMBER_RECENT_WALLETS_STATE,
} from "./constants";

const reducer = (
Expand All @@ -28,6 +30,7 @@ const reducer = (
contract,
selectedWalletId,
recentlySignedInWallets,
rememberRecentWallets,
} = action.payload;

const accountStates = accounts.map((account, i) => {
Expand All @@ -44,6 +47,7 @@ const reducer = (
contract,
selectedWalletId,
recentlySignedInWallets,
rememberRecentWallets,
};
}
case "WALLET_CONNECTED": {
Expand Down Expand Up @@ -129,6 +133,33 @@ const reducer = (
accounts: accountStates,
};
}
case "SET_REMEMBER_RECENT_WALLETS": {
const { selectedWalletId, recentlySignedInWallets } = state;
const { rememberRecentWallets } = action.payload;
const newRecentWallets =
rememberRecentWallets === REMEMBER_RECENT_WALLETS_STATE.ENABLED
? REMEMBER_RECENT_WALLETS_STATE.DISABLED
: REMEMBER_RECENT_WALLETS_STATE.ENABLED;

const newWalletsVal = [...recentlySignedInWallets];
if (
selectedWalletId &&
!recentlySignedInWallets.includes(selectedWalletId)
) {
newWalletsVal.push(selectedWalletId);
}

const newRecentlySignedInWallets =
newRecentWallets === REMEMBER_RECENT_WALLETS_STATE.ENABLED
? newWalletsVal
: [];

return {
...state,
rememberRecentWallets: newRecentWallets,
recentlySignedInWallets: newRecentlySignedInWallets,
};
}
default:
return state;
}
Expand All @@ -143,6 +174,8 @@ export const createStore = async (storage: StorageService): Promise<Store> => {
selectedWalletId: await jsonStorage.getItem(SELECTED_WALLET_ID),
recentlySignedInWallets:
(await jsonStorage.getItem(RECENTLY_SIGNED_IN_WALLETS)) || [],
rememberRecentWallets:
(await jsonStorage.getItem(REMEMBER_RECENT_WALLETS)) || "",
};

const state$ = new BehaviorSubject(initialState);
Expand Down Expand Up @@ -178,6 +211,12 @@ export const createStore = async (storage: StorageService): Promise<Store> => {
RECENTLY_SIGNED_IN_WALLETS,
"recentlySignedInWallets"
);
syncStorage(
prevState,
state,
REMEMBER_RECENT_WALLETS,
"rememberRecentWallets"
);
prevState = state;
});

Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/lib/store.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ export interface WalletSelectorState {
* Returns ID-s of 5 recently signed in wallets.
*/
recentlySignedInWallets: Array<string>;
/**
* Returns a string, which indicates if the functionality about recentlySignedInWallets is active.
*/
rememberRecentWallets: string;
}

export type WalletSelectorAction =
Expand All @@ -72,6 +76,7 @@ export type WalletSelectorAction =
contract: ContractState | null;
selectedWalletId: string | null;
recentlySignedInWallets: Array<string>;
rememberRecentWallets: string;
};
}
| {
Expand All @@ -81,6 +86,7 @@ export type WalletSelectorAction =
contract: ContractState;
accounts: Array<Account>;
recentlySignedInWallets: Array<string>;
rememberRecentWallets: string;
};
}
| {
Expand All @@ -101,6 +107,12 @@ export type WalletSelectorAction =
payload: {
accountId: string;
};
}
| {
type: "SET_REMEMBER_RECENT_WALLETS";
payload: {
rememberRecentWallets: string;
};
};

export interface ReadOnlyStore {
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/lib/wallet-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ const createSelector = (
payload: { accountId },
});
},
setRememberRecentWallets: () => {
const { rememberRecentWallets } = store.getState();

store.dispatch({
type: "SET_REMEMBER_RECENT_WALLETS",
payload: { rememberRecentWallets },
});
},
isSignedIn() {
const { accounts } = store.getState();

Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/lib/wallet-selector.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@ export interface WalletSelector {
*/
setActiveAccount(accountId: string): void;

/**
* Programmatically changes the rememberRecentWallets behavior, it can deactivate and activate rememberRecentWallets.
*/
setRememberRecentWallets(): void;

/**
* Attach an event handler to important events.
*/
Expand Down
Loading
Loading