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 7 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
4 changes: 4 additions & 0 deletions example/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,9 @@ import { defineConfig } from "vite"

// https://vitejs.dev/config/
export default defineConfig({
build: {
target: "es2020",
},
plugins: [react()],
optimizeDeps: { esbuildOptions: { target: "es2020" } },
})
4 changes: 4 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
"dev": "vite build --watch",
"test": "vitest"
},
"dependencies": {
"@consensys/get-starknet": "1.0.0-dev-998a4b7-202312151810",
"@metamask/detect-provider": "^2.0.0"
},
"devDependencies": {
"c8": "^7.12.0",
"happy-dom": "^6.0.4",
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/StarknetWindowObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,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 @@ -30,6 +30,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,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIH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wNjMgMTE5LjgxMyIgdHJhbnNmb3JtPSJtYXRyaXgoLTEgMCAwIDEgMTUwLjE4OCAwKSIvPjxwb2x5Z29uIGZpbGw9IiNFODhGMzUiIHBvaW50cz0iMTIuMzc1IC41NjMgODguODc1IDU4LjUgNzUuOTM4IDI3Ii8+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
116 changes: 116 additions & 0 deletions packages/core/src/wallet/metamaskBridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import {
DisconnectedStarknetWindowObject,
RpcMessage,
} from "../StarknetWindowObject"
import wallets, { WalletProvider } from "../discovery"
import type { MetaMaskProvider } from "@consensys/get-starknet/dist/type"
import detectEthereumProvider from "@metamask/detect-provider"
import type { ProviderInterface } from "starknet"

class EmptyMetaMaskProvider implements DisconnectedStarknetWindowObject {
id: string
name: string
icon: string
version = "0.0.0"
isConnected = false as const
provider: undefined | ProviderInterface
constructor(
private metamaskProvider: MetaMaskProvider,
walletInfo: WalletProvider,
) {
this.id = walletInfo.id
this.name = walletInfo.name
this.icon = walletInfo.icon
}
request<T extends RpcMessage>(): Promise<T["result"]> {
throw new Error("Wallet not enabled")
}
async enable(options?: { starknetVersion?: "v4" | "v5" }): Promise<string[]> {
const { MetaMaskSnapWallet } = await import("@consensys/get-starknet")
const metaMaskSnapWallet = new MetaMaskSnapWallet(this.metamaskProvider)
naorye2 marked this conversation as resolved.
Show resolved Hide resolved

Object.assign(this, metaMaskSnapWallet)
this.constructor.prototype = metaMaskSnapWallet.constructor.prototype
naorye2 marked this conversation as resolved.
Show resolved Hide resolved

return await this.enable(options)
naorye2 marked this conversation as resolved.
Show resolved Hide resolved
}
isPreauthorized() {
return Promise.resolve(false)
}
on() {
throw new Error("Wallet not enabled")
}
off() {
throw new Error("Wallet not enabled")
}
}

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

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

if (provider) {
return provider
}

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

provider = await waitForEthereumProvider({ 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 waitForEthereumProvider({ retries: 3 })
if (!provider) {
return null
}

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

return provider
}

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 = new EmptyMetaMaskProvider(
provider,
metamaskWalletInfo,
)
}

export { injectMetamaskBridge }
2 changes: 2 additions & 0 deletions packages/core/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default defineConfig({
// the proper extensions will be added
fileName: "core",
},
target: "es2020",
},
plugins: [
dts({
Expand All @@ -31,4 +32,5 @@ export default defineConfig({
exclude: ["**/node_modules/**", "**/*.mock.ts"],
},
},
optimizeDeps: { esbuildOptions: { target: "es2020" } },
})
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
2 changes: 2 additions & 0 deletions packages/ui/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export default defineConfig({
// the proper extensions will be added
fileName: "ui",
},
target: "es2020",
},
plugins: [
svelte({ emitCss: false }),
Expand All @@ -21,4 +22,5 @@ export default defineConfig({
insertTypesEntry: true,
}),
],
optimizeDeps: { esbuildOptions: { target: "es2020" } },
})
Loading
Loading