Skip to content

Commit

Permalink
Merge pull request #166 from perawallet/auto-connection
Browse files Browse the repository at this point in the history
V1 - Add `isPeraDiscoverBrowser`
  • Loading branch information
yigitguler authored Oct 7, 2024
2 parents 0b02f7c + c34ebd4 commit 92659d7
Show file tree
Hide file tree
Showing 16 changed files with 2,511 additions and 7,965 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ peraWallet

setAccountAddress(newAccounts[0]);
})
.reject((error) => {
.catch((error) => {
// You MUST handle the reject because once the user closes the modal, peraWallet.connect() promise will be rejected.
// For the async/await syntax you MUST use try/catch
if (error?.data?.type !== "CONNECT_MODAL_CLOSED") {
Expand Down Expand Up @@ -130,6 +130,7 @@ 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.platform: PeraWalletPlatformType`
Returns the platform of the active session. Possible responses: _`mobile | web | null`_
Expand All @@ -138,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
9,886 changes: 2,432 additions & 7,454 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "1.3.4",
"version": "1.3.5",
"name": "@perawallet/connect",
"description": "JavaScript SDK for integrating Pera Wallet to web applications.",
"main": "dist/index.js",
Expand Down
32 changes: 26 additions & 6 deletions src/PeraWalletConnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,27 @@ interface PeraWalletConnectOptions {
shouldShowSignTxnToast?: boolean;
chainId?: AlgorandChainIDs;
compactMode?: boolean;
singleAccount?: boolean;
}

function generatePeraWalletConnectModalActions({
isWebWalletAvailable,
shouldDisplayNewBadge,
shouldUseSound,
compactMode,
promoteMobile
promoteMobile,
singleAccount,
selectedAccount
}: PeraWalletModalConfig) {
return {
open: openPeraWalletConnectModal({
isWebWalletAvailable,
shouldDisplayNewBadge,
shouldUseSound,
compactMode,
promoteMobile
promoteMobile,
singleAccount,
selectedAccount
}),
close: () => removeModalWrapperFromDOM(PERA_WALLET_CONNECT_MODAL_ID)
};
Expand All @@ -68,6 +73,7 @@ class PeraWalletConnect {
shouldShowSignTxnToast: boolean;
chainId?: AlgorandChainIDs;
compactMode?: boolean;
singleAccount?: boolean;

constructor(options?: PeraWalletConnectOptions) {
this.bridge = options?.bridge || "";
Expand All @@ -80,6 +86,7 @@ class PeraWalletConnect {

this.chainId = options?.chainId;
this.compactMode = options?.compactMode || false;
this.singleAccount = options?.singleAccount || false;
}

get platform() {
Expand All @@ -96,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 @@ -139,7 +151,9 @@ class PeraWalletConnect {
shouldDisplayNewBadge,
shouldUseSound,
compactMode: this.compactMode,
promoteMobile
promoteMobile,
singleAccount: this.singleAccount,
selectedAccount: options?.selectedAccount
})
});

Expand Down Expand Up @@ -328,7 +342,7 @@ class PeraWalletConnect {
chainId
}: {
// Converted Uin8Array data to base64
data: {data: string; message: string;}[];
data: {data: string; message: string}[];
signer: string;
chainId: AlgorandChainIDs;
}) {
Expand Down Expand Up @@ -403,6 +417,12 @@ class PeraWalletConnect {
);
}

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

return userAget.includes("pera");
}

async signTransaction(
txGroups: SignerTransaction[][],
signerAddress?: string
Expand Down Expand Up @@ -472,7 +492,7 @@ class PeraWalletConnect {

const b64encodedData = data.map((item) => ({
...item,
data: Buffer.from(item.data).toString('base64')
data: Buffer.from(item.data).toString("base64")
}));

// Pera Mobile Wallet flow
Expand Down
8 changes: 6 additions & 2 deletions src/modal/PeraWalletConnectModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export class PeraWalletConnectModal extends HTMLElement {
peraWalletConnectModalClassNames = `${peraWalletConnectModalClassNames} ${PERA_WALLET_MODAL_CLASSNAME}--compact`;
}

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

if (isMobile()) {
peraWalletConnectModal.innerHTML = `
<div class="${peraWalletConnectModalClassNames}">
Expand All @@ -36,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 All @@ -61,7 +64,8 @@ export class PeraWalletConnectModal extends HTMLElement {
"compact-mode"
)}" promote-mobile="${this.getAttribute(
"promote-mobile"
)}"></pera-wallet-modal-desktop-mode>
)}" single-account="${singleAccount}"
></pera-wallet-modal-desktop-mode>
</div>
</div>
`;
Expand Down
18 changes: 6 additions & 12 deletions src/modal/mode/desktop/PeraWalletConnectModalDesktopMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,17 +227,6 @@ export class PeraWalletModalDesktopMode extends HTMLElement {
}

this.handleChangeView();

// if (peraWalletFlowType() === "EMBEDDED" && this.shadowRoot) {
// const iframeWrapper = this.shadowRoot.querySelector(
// ".pera-wallet-connect-modal-desktop-mode__web-wallet-iframe"
// );

// if (iframeWrapper && this.getAttribute("is-web-wallet-avaliable") === "true") {
// // @ts-ignore ts-2339
// window.onWebWalletConnect(iframeWrapper);
// }
// }
}

handleChangeView() {
Expand Down Expand Up @@ -308,9 +297,14 @@ export class PeraWalletModalDesktopMode extends HTMLElement {
}

renderQRCode() {
const URI = this.getAttribute("uri");
const isWebWalletAvailable = this.getAttribute("is-web-wallet-avaliable");
const isCompactMode = this.getAttribute("compact-mode") === "true";
const singleAccount = this.getAttribute("single-account") === "true";
let URI = this.getAttribute("uri");

if (singleAccount) {
URI = `${URI}&singleAccount=true`;
}

/* eslint-disable no-magic-numbers */
let size = isWebWalletAvailable === "false" ? 250 : 205;
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
8 changes: 6 additions & 2 deletions src/modal/peraWalletConnectModalUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export interface PeraWalletModalConfig {
shouldUseSound: boolean;
promoteMobile?: boolean;
compactMode?: boolean;
singleAccount?: boolean;
selectedAccount?: string;
}

// The ID of the wrapper element for PeraWalletConnectModal
Expand Down Expand Up @@ -65,10 +67,12 @@ function openPeraWalletConnectModal(modalConfig: PeraWalletModalConfig) {
shouldDisplayNewBadge,
shouldUseSound,
compactMode,
promoteMobile
promoteMobile,
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}"></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
65 changes: 2 additions & 63 deletions src/util/connect/connectFlow.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
// PERA_WALLET_IFRAME_ID,
PERA_WALLET_CONNECT_MODAL_ID,
removeModalWrapperFromDOM,
removeModalWrapperFromDOM
// getHeaderCloseButton
} from "../../modal/peraWalletConnectModalUtils";
import PeraWalletConnectError from "../PeraWalletConnectError";
Expand All @@ -14,12 +14,8 @@ import {
} from "../dom/domUtils";
import appTellerManager, {PeraTeller} from "../network/teller/appTellerManager";
import {getPeraWebWalletURL} from "../peraWalletConstants";
// import {generateEmbeddedWalletURL} from "../peraWalletUtils";
import {RunWebConnectFlowTypes} from "./connectFlowModels";
import {
// embeddedConnectFlowTellerReducer,
newTabConnectFlowTellerReducer
} from "./connectFlowReducers";
import {newTabConnectFlowTellerReducer} from "./connectFlowReducers";

function runWebConnectFlow({
webWalletURL,
Expand All @@ -30,65 +26,8 @@ function runWebConnectFlow({
}: RunWebConnectFlowTypes) {
const webWalletURLs = getPeraWebWalletURL(webWalletURL);

// if (peraWalletFlowType() === "EMBEDDED") {
// return runEmbeddedWebConnectFlow;
// }

return runNewTabWebConnectFlow;

// =========== Embedded Connect Flow ===========
// function runEmbeddedWebConnectFlow(peraWalletIframeWrapper: Element) {
// const peraWalletIframe = document.createElement("iframe");

// peraWalletIframe.setAttribute("id", PERA_WALLET_IFRAME_ID);
// peraWalletIframe.setAttribute(
// "src",
// generateEmbeddedWalletURL(webWalletURLs.CONNECT, isCompactMode)
// );

// peraWalletIframeWrapper.appendChild(peraWalletIframe);

// if (peraWalletIframe.contentWindow) {
// let count = 0;

// const isIframeInitializedChecker = setInterval(() => {
// count += 1;

// if (count === WAIT_FOR_TAB_MAX_TRY_COUNT) {
// clearInterval(isIframeInitializedChecker);

// return;
// }

// appTellerManager.sendMessage({
// message: {
// type: "IFRAME_INITIALIZED"
// },

// origin: webWalletURLs.CONNECT,
// targetWindow: peraWalletIframe.contentWindow!
// });

// getHeaderCloseButton("connect")?.addEventListener("click", () => {
// clearInterval(isIframeInitializedChecker);
// });
// }, WAIT_FOR_TAB_TRY_INTERVAL);

// appTellerManager.setupListener({
// onReceiveMessage: (event: MessageEvent<TellerMessage<PeraTeller>>) =>
// embeddedConnectFlowTellerReducer({
// event,
// peraWalletIframe,
// chainId,
// isIframeInitializedChecker,
// webWalletURLs,
// resolve,
// reject
// })
// });
// }
// }

// =========== New Tab Connect Flow ===========
async function runNewTabWebConnectFlow() {
try {
Expand Down
10 changes: 0 additions & 10 deletions src/util/connect/connectFlowModels.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {PeraTeller} from "../network/teller/appTellerManager";
import {PeraWebWalletURLs} from "../peraWalletConstants";
import {AlgorandChainIDs} from "../peraWalletTypes";

interface ConnectFlowPromise {
Expand All @@ -13,14 +12,6 @@ interface RunWebConnectFlowTypes extends ConnectFlowPromise {
isCompactMode?: boolean;
}

interface EmbeddedConnectFlowTellerReducerParams extends ConnectFlowPromise {
event: MessageEvent<TellerMessage<PeraTeller>>;
peraWalletIframe: HTMLIFrameElement;
chainId: AlgorandChainIDs | undefined;
isIframeInitializedChecker: NodeJS.Timer;
webWalletURLs: PeraWebWalletURLs;
}

interface NewTabConnectFlowTellerReducerParams extends ConnectFlowPromise {
event: MessageEvent<TellerMessage<PeraTeller>>;
newPeraWalletTab: Window | null;
Expand All @@ -29,6 +20,5 @@ interface NewTabConnectFlowTellerReducerParams extends ConnectFlowPromise {
export type {
ConnectFlowPromise,
RunWebConnectFlowTypes,
EmbeddedConnectFlowTellerReducerParams,
NewTabConnectFlowTellerReducerParams
};
Loading

0 comments on commit 92659d7

Please sign in to comment.