Skip to content

Commit

Permalink
Add isPeraDiscoverBrowser property
Browse files Browse the repository at this point in the history
  • Loading branch information
yasincaliskan committed Aug 29, 2024
1 parent 0f8e55b commit c34ebd4
Show file tree
Hide file tree
Showing 7 changed files with 35 additions and 129 deletions.
37 changes: 4 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,39 +86,13 @@ try {
}
```
You can also use the `autoConnect` function to connect to the mobile wallet without any UI. This function is specifically designed for mobile browsers.
```jsx
// Auto Connect
peraWallet.autoConnect()
.then((accounts) => {
// Setup the disconnect event listener
peraWallet.connector?.on("disconnect", handleDisconnectWalletClick);

if (accounts.length) {
setAccountAddress(accounts[0]);
}
})
.catch((error) => {
// You MUST handle the rejection when running outside of a mobile browser,
// as the peraWallet.autoConnect() promise will be rejected.
// For the async/await syntax you MUST use try/catch
if (error?.data?.type !== "CONNECT_CANCELLED") {
// log the necessary errors
}
});

```
## Options
| option | default | value | |
| ------------------------ | ------- | ------------------------------------- | -------- |
| `chainId` | `4160` | `416001`, `416002`, `416003` , `4160` | optional |
| `shouldShowSignTxnToast` | `true` | `boolean` | optional |
| `compactMode` | `false` | `boolean` | optional |
| `singleAccount` | `false` | `boolean` | optional |
#### **`chainId`**
Expand All @@ -142,10 +116,6 @@ It's enabled by default but in some cases, you may not need the toast message (e
It offers a compact UI optimized for smaller screens, with a minimum resolution of 400x400 pixels.
#### **`singleAccount`**
It allows you to select only one account.
## Methods
#### `PeraWalletConnect.connect(): Promise<string[]>`
Expand All @@ -160,9 +130,6 @@ Reconnects to the wallet if there is any active connection and returns the array
Disconnects from the wallet and resets the related storage items.
#### `PeraWalletConnect.autoConnect(): Promise<string[]>`
#### `PeraWalletConnect.platform: PeraWalletPlatformType`
Expand All @@ -172,6 +139,10 @@ Returns the platform of the active session. Possible responses: _`mobile | web |
Checks if there's any active session regardless of platform. Possible responses: _`true | false`_
#### `PeraWalletConnect.isPeraDiscoverBrowser: boolean`
Checks if it is on Pera Discover Browser. Possible responses: _`true | false`_
#### `PeraWalletConnect.signTransaction(txGroups: SignerTransaction[][], signerAddress?: string): Promise<Uint8Array[]>`
Starts the sign process and returns the signed transaction in `Uint8Array`
Expand Down
102 changes: 19 additions & 83 deletions src/PeraWalletConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ import {
formatJsonRpcRequest
} from "./util/transaction/transactionUtils";
import {isMobile} from "./util/device/deviceUtils";
import {AlgorandChainIDs, PeraWalletAutoConnectOptions} from "./util/peraWalletTypes";
import {AlgorandChainIDs} from "./util/peraWalletTypes";
import {runWebSignTransactionFlow} from "./util/sign/signTransactionFlow";
import {runWebConnectFlow} from "./util/connect/connectFlow";
import {generatePeraWalletConnectDeepLink} from "./util/peraWalletUtils";

interface PeraWalletConnectOptions {
bridge?: string;
Expand All @@ -51,7 +50,8 @@ function generatePeraWalletConnectModalActions({
shouldUseSound,
compactMode,
promoteMobile,
singleAccount
singleAccount,
selectedAccount
}: PeraWalletModalConfig) {
return {
open: openPeraWalletConnectModal({
Expand All @@ -60,7 +60,8 @@ function generatePeraWalletConnectModalActions({
shouldUseSound,
compactMode,
promoteMobile,
singleAccount
singleAccount,
selectedAccount
}),
close: () => removeModalWrapperFromDOM(PERA_WALLET_CONNECT_MODAL_ID)
};
Expand Down Expand Up @@ -102,7 +103,12 @@ class PeraWalletConnect {
return false;
}

connect() {
get isPeraDiscoverBrowser() {
return this.checkIsPeraDiscoverBrowser();
}

// `selectedAccount` option is only applicable for Pera Wallet products
connect(options?: {selectedAccount?: string}) {
return new Promise<string[]>(async (resolve, reject) => {
try {
// check if already connected and kill session first before creating a new one.
Expand Down Expand Up @@ -146,7 +152,8 @@ class PeraWalletConnect {
shouldUseSound,
compactMode: this.compactMode,
promoteMobile,
singleAccount: this.singleAccount
singleAccount: this.singleAccount,
selectedAccount: options?.selectedAccount
})
});

Expand Down Expand Up @@ -191,83 +198,6 @@ class PeraWalletConnect {
});
}

autoConnect(options?: PeraWalletAutoConnectOptions) {
return new Promise<string[]>(async (resolve, reject) => {
try {
if (!isMobile()) {
reject(
new PeraWalletConnectError(
{
type: "CONNECT_CANCELLED",
},
"autoConnect() method is only available on mobile browsers"
)
)
}
// check if already connected and kill session first before creating a new one.
// This is to kill the last session and make sure user start from scratch whenever `.connect()` method is called.
if (this.connector?.connected) {
try {
await this.connector.killSession();
} catch (_error) {
// No need to handle
}
}

const {bridgeURL} = await getPeraConnectConfig();

// Create Connector instance
this.connector = new WalletConnect({
bridge: this.bridge || bridgeURL || "https://bridge.walletconnect.org",
qrcodeModal: {
open: (uri: string) => {
window.open(`${generatePeraWalletConnectDeepLink(uri, options)}`, "_self");
},
close: () => removeModalWrapperFromDOM(PERA_WALLET_CONNECT_MODAL_ID)
}
});

await this.connector.createSession({
// eslint-disable-next-line no-magic-numbers
chainId: this.chainId || 4160
});

setupPeraWalletConnectModalCloseListener(PERA_WALLET_CONNECT_MODAL_ID, () =>
reject(
new PeraWalletConnectError(
{
type: "CONNECT_MODAL_CLOSED"
},
"Connect modal is closed by user"
)
)
);

this.connector.on("connect", (error, _payload) => {
if (error) {
reject(error);
}

resolve(this.connector?.accounts || []);

saveWalletDetailsToStorage(this.connector?.accounts || []);
});
} catch (error: any) {
console.log(error);

reject(
new PeraWalletConnectError(
{
type: "SESSION_CONNECT",
detail: error
},
error.message || `There was an error while connecting to Pera Wallet`
)
);
}
});
}

reconnectSession() {
return new Promise<string[]>(async (resolve, reject) => {
try {
Expand Down Expand Up @@ -487,6 +417,12 @@ class PeraWalletConnect {
);
}

private checkIsPeraDiscoverBrowser() {
const userAget = window.navigator.userAgent;

return userAget.includes("pera");
}

async signTransaction(
txGroups: SignerTransaction[][],
signerAddress?: string
Expand Down
3 changes: 2 additions & 1 deletion src/modal/PeraWalletConnectModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export class PeraWalletConnectModal extends HTMLElement {
}

const singleAccount = this.getAttribute("single-account") === "true";
const selectedAccount = this.getAttribute("selected-account");

if (isMobile()) {
peraWalletConnectModal.innerHTML = `
Expand All @@ -38,7 +39,7 @@ export class PeraWalletConnectModal extends HTMLElement {
"uri"
)}" should-use-sound="${this.getAttribute(
"should-use-sound"
)}"></pera-wallet-modal-touch-screen-mode>
)}" single-account="${singleAccount}" selected-account="${selectedAccount}"></pera-wallet-modal-touch-screen-mode>
</div>
</div>
`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,11 @@ export class PeraWalletModalTouchScreenMode extends HTMLElement {
"pera-wallet-connect-modal-touch-screen-mode-launch-pera-wallet-button"
);
const URI = this.getAttribute("uri");
const singleAccount = this.getAttribute("single-account") === "true";
const selectedAccount = this.getAttribute("selected-account") || undefined;

if (launchPeraLink && URI) {
launchPeraLink.setAttribute("href", generatePeraWalletConnectDeepLink(URI));
launchPeraLink.setAttribute("href", generatePeraWalletConnectDeepLink(URI, {singleAccount, selectedAccount}));
launchPeraLink.addEventListener("click", () => {
this.onClickLaunch();
});
Expand Down
6 changes: 4 additions & 2 deletions src/modal/peraWalletConnectModalUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface PeraWalletModalConfig {
promoteMobile?: boolean;
compactMode?: boolean;
singleAccount?: boolean;
selectedAccount?: string;
}

// The ID of the wrapper element for PeraWalletConnectModal
Expand Down Expand Up @@ -67,10 +68,11 @@ function openPeraWalletConnectModal(modalConfig: PeraWalletModalConfig) {
shouldUseSound,
compactMode,
promoteMobile,
singleAccount
singleAccount,
selectedAccount
} = modalConfig;

root.innerHTML = `<pera-wallet-connect-modal uri="${newURI}" is-web-wallet-avaliable="${isWebWalletAvailable}" should-display-new-badge="${shouldDisplayNewBadge}" should-use-sound="${shouldUseSound}" compact-mode="${compactMode}" promote-mobile="${promoteMobile}" single-account="${singleAccount}"></pera-wallet-connect-modal>`;
root.innerHTML = `<pera-wallet-connect-modal uri="${newURI}" is-web-wallet-avaliable="${isWebWalletAvailable}" should-display-new-badge="${shouldDisplayNewBadge}" should-use-sound="${shouldUseSound}" compact-mode="${compactMode}" promote-mobile="${promoteMobile}" single-account="${singleAccount}" selected-account="${selectedAccount || ''}"></pera-wallet-connect-modal>`;
}
};
}
Expand Down
8 changes: 1 addition & 7 deletions src/util/peraWalletTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,10 @@ interface PeraWalletDetails {
selectedAccount: string;
}

interface PeraWalletAutoConnectOptions {
// `selectedAccount` option is only applicable for Pera Wallet products
selectedAccount?: string;
}

export type {
PeraWalletType,
PeraWalletPlatformType,
PeraWalletDetails,
AlgorandChainIDs,
PeraWalletFlowType,
PeraWalletAutoConnectOptions
PeraWalletFlowType
};
4 changes: 2 additions & 2 deletions src/util/peraWalletUtils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {detectBrowser, isAndroid, isIOS} from "./device/deviceUtils";
import {PERA_WALLET_APP_DEEP_LINK} from "./peraWalletConstants";
import {PeraWalletAutoConnectOptions} from "./peraWalletTypes";

function generatePeraWalletAppDeepLink(shouldAddBrowserName = true): string {
let appDeepLink = PERA_WALLET_APP_DEEP_LINK;
Expand Down Expand Up @@ -32,7 +31,8 @@ function generatePeraWalletConnectDeepLink(
uri: string,
params?: {
singleAccount?: boolean;
} & PeraWalletAutoConnectOptions
selectedAccount?: string;
}
): string {
let appDeepLink = generatePeraWalletAppDeepLink(false);

Expand Down

0 comments on commit c34ebd4

Please sign in to comment.