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 metamask-snap support #208

Merged
merged 22 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 16 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
3 changes: 3 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"dev": "vite build --watch",
"test": "vitest"
},
"dependencies": {
"@module-federation/runtime": "^0.1.2"
avimak marked this conversation as resolved.
Show resolved Hide resolved
},
"devDependencies": {
"c8": "^7.12.0",
"happy-dom": "^6.0.4",
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/StarknetWindowObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export interface IStarknetWindowObject {
provider?: ProviderInterface | ProviderInterfaceV4
selectedAddress?: string
chainId?: string
isConnected: boolean
}

export interface ConnectedStarknetWindowObject extends IStarknetWindowObject {
Expand All @@ -118,6 +119,7 @@ declare global {
starknet?: StarknetWindowObject
starknet_braavos?: StarknetWindowObject
starknet_argentX?: StarknetWindowObject
starknet_metamask?: StarknetWindowObject
[key: `starknet_${string}`]: StarknetWindowObject | undefined
}
}
11 changes: 11 additions & 0 deletions packages/core/src/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ const wallets: WalletProvider[] = [
edge: "https://microsoftedge.microsoft.com/addons/detail/braavos-wallet/hkkpjehhcnhgefhbdcgfkeegglpjchdc",
},
},
{
id: "metamask",
name: "MetaMask",
icon: `data:image/svg+xml;utf8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyMTIiIGhlaWdodD0iMTg5IiB2aWV3Qm94PS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EgMCAwIDEgMTUwLjE4OCAwKSIvPjxwb2x5Z29uIGZpbGw9IiNFODhGMzUiIHBvaW50cz0iMTIuMzc1IC41NjMgODguODc1IDU4LjUgNzUuOTM4IDI3Ii8+PHBhdGggZmlsbD0iIzhFNUEzMCIgZD0iTTEyLjM3NTAwMDIsMC41NjI1MDAwMDggTDIuMjUwMDAwMDMsMzEuNTAwMDAwNSBMNy44NzUwMDAxMiw2NS4yNTAwMDEgTDMuOTM3NTAwMDYsNjcuNTAwMDAxIEw5LjU2MjUwMDE0LDcyLjU2MjUgTDUuMDYyNTAwMDgsNzYuNTAwMDAxMSBMMTEuMjUsODIuMTI1MDAxMiBMNy4zMTI1MDAxMSw4NS41MDAwMDEzIEwxNi4zMTI1MDAyLDk2Ljc1MDAwMTQgTDU4LjUwMDAwMDksODMuODEyNTAxMiBDNzkuMTI1MDAxMiw2Ny4zMTI1MDA0IDg5LjI1MDAwMTMsNTguODc1MDAwMyA4OC44NzUwMDEzLDU4LjUwMDAwMDkgQzg4LjUwMDAwMTMsNTguMTI1MDAwOSA2My4wMDAwMDA5LDM4LjgxMjUwMDYgMTIuMzc1MDAwMiwwLjU2MjUwMDAwOCBaIi8+PC9nPjwvZz48L3N2Zz4=`,
downloads: {
chrome:
"https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn",
firefox: "https://addons.mozilla.org/en-US/firefox/addon/ether-metamask/",
edge: "https://microsoftedge.microsoft.com/addons/detail/metamask/ejbalbakoplchlghecdalmeeeajnimhm?hl=en-US",
},
},
]

export default wallets
3 changes: 3 additions & 0 deletions packages/core/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { IStorageWrapper, LocalStorageWrapper } from "./localStorageStore"
import { pipe } from "./utils"
import { FilterList, filterBy, filterByPreAuthorized } from "./wallet/filter"
import { isWalletObj } from "./wallet/isWalletObject"
import { injectMetamaskBridge } from "./wallet/metamaskBridge"
import { scanObjectForWallets } from "./wallet/scan"
import { Sort, sortBy } from "./wallet/sort"

Expand Down Expand Up @@ -75,6 +76,8 @@ export function getStarknet(
}
const lastConnectedStore = storageFactoryImplementation("gsw-last")

injectMetamaskBridge()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pass ssrSafeWindow to avoid assuming window availability later inside injectMetamaskBridge

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed.


return {
getAvailableWallets: async (options = {}) => {
const availableWallets = scanObjectForWallets(
Expand Down
203 changes: 203 additions & 0 deletions packages/core/src/wallet/metamaskBridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { loadRemote, init } from "@module-federation/runtime"
import type {
IStarknetWindowObject,
RpcMessage,
StarknetWindowObject,
WalletEvents,
} from "../StarknetWindowObject"
import wallets, { WalletProvider } from "../discovery"

interface MetaMaskProvider {
isMetaMask: boolean
request(options: { method: string }): Promise<void>
}

declare global {
interface Window {
ethereum?: MetaMaskProvider
}
}

function detectMetaMaskProvider({ timeout = 3000 } = {}) {
let handled = false
return new Promise<MetaMaskProvider | null>((resolve) => {
if (window.ethereum) {
handleEthereum()
} else {
window.addEventListener("ethereum#initialized", handleEthereum, {
once: true,
})
setTimeout(() => {
handleEthereum()
}, timeout)
}
function handleEthereum() {
if (handled) {
return
}
handled = true
window.removeEventListener("ethereum#initialized", handleEthereum)
const { ethereum } = window
if (ethereum && ethereum.isMetaMask) {
resolve(ethereum)
} else {
resolve(null)
}
}
})
}

async function waitForMetaMaskProvider(
options: { timeout?: number; retries?: number } = {},
): Promise<MetaMaskProvider | null> {
const { timeout = 3000, retries = 0 } = options

let provider: MetaMaskProvider | null = null
try {
provider = await detectMetaMaskProvider({ timeout })
} catch {
// Silent error - do nothing
}

if (provider) {
return provider
}

if (retries === 0) {
return null
}

provider = await waitForMetaMaskProvider({ timeout, retries: retries - 1 })
return provider
}

async function hasSnapSupport(provider: MetaMaskProvider) {
try {
await provider.request({ method: "wallet_getSnaps" })
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use non-api call to check for starknet support (not just and snaps?)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi @avimak the life cycle of a snap is working like that way

  1. you detect where you have a install metamask
  2. you detect where you have an correct version of metamask -> which using similar method as above
  3. then you ask metamask to install the starknet snap -> that should be trigger by enable() / or any similar method

so you can only cehck if the metamask support starknet by first checking if it has supported snap

In addtional, metamask does not inject any extra method to the provider (window.ethereum) to verify if it is support snap, it means, you must using request method to determined

does it help to clarify your questions?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@avimak
After consulting with @stanleyyconsensys we decided to remove that check.

return true
} catch {
return false
}
}

async function detectMetamaskSupport() {
const provider = await waitForMetaMaskProvider({ retries: 3 })
if (!provider) {
return null
}

const snapSupport = await hasSnapSupport(provider)
if (!snapSupport) {
return null
}

return provider
}

function createMetaMaskProviderWrapper(
walletInfo: WalletProvider,
provider: unknown,
): StarknetWindowObject {
let metaMaskSnapWallet: IStarknetWindowObject | undefined
const metaMaskProviderWrapper: IStarknetWindowObject = {
id: walletInfo.id,
name: walletInfo.name,
icon: walletInfo.icon,
get version() {
return metaMaskSnapWallet?.version ?? "0.0.0"
},
get isConnected() {
return metaMaskSnapWallet?.isConnected ?? false
},
get provider() {
return metaMaskSnapWallet?.provider
},
get account() {
return metaMaskSnapWallet?.account
},
get selectedAddress() {
return metaMaskSnapWallet?.selectedAddress
},
get chainId() {
return metaMaskSnapWallet?.chainId
},
request<T extends RpcMessage>(
call: Omit<T, "result">,
): Promise<T["result"]> {
if (!metaMaskSnapWallet) {
throw new Error("Wallet not enabled")
}
return metaMaskSnapWallet.request(call)
},
async enable(): Promise<string[]> {
if (!metaMaskSnapWallet) {
await init({
name: "MetaMaskStarknetSnapWallet",
remotes: [
{
name: "MetaMaskStarknetSnapWallet",
alias: "MetaMaskStarknetSnapWallet",
entry:
"https://s3.eu-central-1.amazonaws.com/dev.snaps.consensys.io/get-starknet/remoteEntry.js",
},
],
})

const result = await loadRemote("MetaMaskStarknetSnapWallet/index")

const { MetaMaskSnapWallet } = result as {
MetaMaskSnapWallet: any
MetaMaskSnap: any
}

metaMaskSnapWallet = new MetaMaskSnapWallet(provider, "*")
}

return await metaMaskSnapWallet!.enable()
},
isPreauthorized() {
return metaMaskSnapWallet?.isPreauthorized() ?? Promise.resolve(false)
},
on<E extends WalletEvents>(
event: E["type"],
handleEvent: E["handler"],
): void {
if (!metaMaskSnapWallet) {
throw new Error("Wallet not enabled")
}
// @ts-ignore: Metamask currently doesn't support on method
return metaMaskSnapWallet.on(event, handleEvent)
},
off<E extends WalletEvents>(event: E["type"], handleEvent: E["handler"]) {
if (!metaMaskSnapWallet) {
throw new Error("Wallet not enabled")
}
// @ts-ignore: Metamask currently doesn't support off method
return metaMaskSnapWallet.off(event, handleEvent)
},
}

return metaMaskProviderWrapper as StarknetWindowObject
}

async function injectMetamaskBridge() {
if (window.hasOwnProperty("starknet_metamask")) {
return
}

const provider = await detectMetamaskSupport()
if (!provider) {
return
}

const metamaskWalletInfo = wallets.find((wallet) => wallet.id === "metamask")
if (!metamaskWalletInfo) {
return
}
window.starknet_metamask = createMetaMaskProviderWrapper(
metamaskWalletInfo,
provider,
)
}

export { injectMetamaskBridge }
2 changes: 1 addition & 1 deletion packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"@sveltejs/vite-plugin-svelte": "^1.0.1",
"@tsconfig/svelte": "^3.0.0",
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"postcss": "^8.4.21",
"svelte": "^3.49.0",
"svelte-check": "^2.8.0",
"svelte-preprocess": "^4.10.7",
Expand Down
Loading
Loading