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 siwx cloud auth storage #3221

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
Draft
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
6 changes: 4 additions & 2 deletions apps/laboratory/src/pages/library/multichain-siwx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { AppKitButtons } from '../../components/AppKitButtons'
import { HuobiWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets'
import { MultiChainTestsEthersSolana } from '../../components/MultiChainTestsEthersSolana'
import { mainnet } from '@reown/appkit/networks'
import { DefaultSIWX } from '@reown/appkit-siwx'
import { CloudAuth, DefaultSIWX } from '@reown/appkit-siwx'

const networks = ConstantsUtil.AllNetworks

Expand All @@ -28,7 +28,9 @@ const modal = createAppKit({
},
termsConditionsUrl: 'https://reown.com/terms-of-service',
privacyPolicyUrl: 'https://reown.com/privacy-policy',
siwx: new DefaultSIWX()
siwx: new DefaultSIWX({
storage: new CloudAuth()
})
})

ThemeStore.setModal(modal)
Expand Down
6 changes: 0 additions & 6 deletions packages/adapters/ethers/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,6 @@ export class EthersAdapter {

public connectionControllerClient?: ConnectionControllerClient

public siweControllerClient = this.options?.siweConfig

public tokens = HelpersUtil.getCaipTokens(this.options?.tokens)

public defaultCaipNetwork: CaipNetwork | undefined = undefined
Expand Down Expand Up @@ -331,10 +329,6 @@ export class EthersAdapter {
const providerId = ProviderUtil.state.providerIds['eip155']

this.appKit?.setClientId(null)
if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
const { SIWEController } = await import('@reown/appkit-siwe')
await SIWEController.signOut()
}

const disconnectConfig = {
[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]: async () =>
Expand Down
6 changes: 0 additions & 6 deletions packages/adapters/ethers5/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,6 @@ export class Ethers5Adapter {

public connectionControllerClient?: ConnectionControllerClient

public siweControllerClient = this.options?.siweConfig

public tokens = HelpersUtil.getCaipTokens(this.options?.tokens)

public defaultCaipNetwork: CaipNetwork | undefined = undefined
Expand Down Expand Up @@ -331,10 +329,6 @@ export class Ethers5Adapter {
const providerId = ProviderUtil.state.providerIds['eip155']

this.appKit?.setClientId(null)
if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
const { SIWEController } = await import('@reown/appkit-siwe')
await SIWEController.signOut()
}

const disconnectConfig = {
[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]: async () =>
Expand Down
105 changes: 0 additions & 105 deletions packages/adapters/wagmi/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,30 +90,6 @@ export interface AdapterOptions<C extends Config>
defaultNetwork?: Chain
}

const OPTIONAL_METHODS = [
'eth_accounts',
'eth_requestAccounts',
'eth_sendRawTransaction',
'eth_sign',
'eth_signTransaction',
'eth_signTypedData',
'eth_signTypedData_v3',
'eth_signTypedData_v4',
'eth_sendTransaction',
'personal_sign',
'wallet_switchEthereumChain',
'wallet_addEthereumChain',
'wallet_getPermissions',
'wallet_requestPermissions',
'wallet_registerOnboarding',
'wallet_watchAsset',
'wallet_scanQRCode',
'wallet_getCallsStatus',
'wallet_sendCalls',
'wallet_getCapabilities',
'wallet_grantPermissions'
]

// @ts-expect-error: Overridden state type is correct
interface AppKitState extends PublicStateControllerState {
selectedNetworkId: number | undefined
Expand Down Expand Up @@ -143,8 +119,6 @@ export class WagmiAdapter implements ChainAdapter {

public tokens = HelpersUtil.getCaipTokens(this.options?.tokens)

public siweControllerClient = this.options?.siweConfig

public adapterType: AdapterType = 'wagmi'

public constructor(
Expand Down Expand Up @@ -307,81 +281,6 @@ export class WagmiAdapter implements ChainAdapter {
throw new Error('connectionControllerClient:getWalletConnectUri - connector is undefined')
}

const provider = (await connector.getProvider()) as Awaited<
ReturnType<(typeof UniversalProvider)['init']>
>

const clientId = await provider?.client?.core?.crypto?.getClientId()
if (clientId) {
this.appKit?.setClientId(clientId)
}

const siweParams = await this.options?.siweConfig?.getMessageParams?.()
const isSiweEnabled = this.options?.siweConfig?.options?.enabled
const isProviderSupported = typeof provider?.authenticate === 'function'
const isSiweParamsValid = siweParams && Object.keys(siweParams || {}).length > 0
const siweConfig = this.options?.siweConfig

if (isSiweEnabled && isProviderSupported && isSiweParamsValid && siweConfig) {
// @ts-expect-error - setting requested chains beforehand avoids wagmi auto disconnecting the session when `connect` is called because it things chains are stale
await connector.setRequestedChainsIds(siweParams.chains)

const { SIWEController, getDidChainId, getDidAddress } = await import(
'@reown/appkit-siwe'
)

const chains = this.caipNetworks
?.filter(network => network.chainNamespace === 'eip155')
.map(chain => chain.caipNetworkId) as string[]

siweParams.chains = this.caipNetworks
?.filter(network => network.chainNamespace === 'eip155')
.map(chain => chain.id) as number[]

const result = await provider.authenticate({
nonce: await siweConfig.getNonce(),
methods: [...OPTIONAL_METHODS],
...siweParams,
chains
})
// Auths is an array of signed CACAO objects https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
const signedCacao = result?.auths?.[0]

if (signedCacao) {
const { p, s } = signedCacao
const cacaoChainId = getDidChainId(p.iss)
const address = getDidAddress(p.iss)
if (address && cacaoChainId) {
SIWEController.setSession({
address,
chainId: parseInt(cacaoChainId, 10)
})
}

try {
// Kicks off verifyMessage and populates external states
const message = provider.client.formatAuthMessage({
request: p,
iss: p.iss
})

await SIWEController.verifyMessage({
message,
signature: s.s,
cacao: signedCacao
})
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error verifying message', error)
// eslint-disable-next-line no-console
await provider.disconnect().catch(console.error)
// eslint-disable-next-line no-console
await SIWEController.signOut().catch(console.error)
throw error
}
}
}

const chainId = this.appKit?.getCaipNetworkId<number>()
await connect(this.wagmiConfig, { connector, chainId })
},
Expand Down Expand Up @@ -432,10 +331,6 @@ export class WagmiAdapter implements ChainAdapter {
},
disconnect: async () => {
await disconnect(this.wagmiConfig)
if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
const { SIWEController } = await import('@reown/appkit-siwe')
await SIWEController.signOut()
}
SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID)
SafeLocalStorage.removeItem(SafeLocalStorageKeys.CONNECTED_CONNECTOR)
SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_NAME)
Expand Down
9 changes: 7 additions & 2 deletions packages/appkit/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,13 @@ export class AppKit {
// Set the SIWE client for EVM chains
if (evmAdapter) {
if (options.siweConfig) {
const { SIWEController } = await import('@reown/appkit-siwe')
SIWEController.setSIWEClient(options.siweConfig)
if (options.siwx) {
throw new Error('Cannot set both siweConfig and siwx')
}

const { mapToSIWX } = await import('@reown/appkit-siwe')
const siwx = await mapToSIWX(options.siweConfig)
OptionsController.setSIWX(siwx)
}
}
}
Expand Down
116 changes: 7 additions & 109 deletions packages/appkit/src/universal-adapter/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,33 +34,6 @@ type Metadata = {
icons: string[]
}

const OPTIONAL_METHODS = [
'eth_accounts',
'eth_requestAccounts',
'eth_sendRawTransaction',
'eth_sign',
'eth_signTransaction',
'eth_signTypedData',
'eth_signTypedData_v3',
'eth_signTypedData_v4',
'eth_sendTransaction',
'personal_sign',
'wallet_switchEthereumChain',
'wallet_addEthereumChain',
'wallet_getPermissions',
'wallet_requestPermissions',
'wallet_registerOnboarding',
'wallet_watchAsset',
'wallet_scanQRCode',
// EIP-5792
'wallet_getCallsStatus',
'wallet_sendCalls',
'wallet_getCapabilities',
// EIP-7715
'wallet_grantPermissions',
'wallet_revokePermissions'
]

// -- Client --------------------------------------------------------------------
export class UniversalAdapterClient {
private walletConnectProviderInitPromise?: Promise<void>
Expand Down Expand Up @@ -88,7 +61,7 @@ export class UniversalAdapterClient {
public reportedAlertErrors: Record<string, boolean> = {}

public constructor(options: AppKitOptionsWithCaipNetworks) {
const { siweConfig, metadata } = options
const { metadata } = options

this.caipNetworks = options.networks

Expand Down Expand Up @@ -144,94 +117,19 @@ export class UniversalAdapterClient {
) {
const adapter = ChainController.state.chains.get(ChainController.state.activeChain)
await adapter?.connectionControllerClient?.connectWalletConnect?.(onUri)
this.setWalletConnectProvider()
} else {
const siweParams = await siweConfig?.getMessageParams?.()
const isSiweEnabled = siweConfig?.options?.enabled
const isProviderSupported = typeof WalletConnectProvider?.authenticate === 'function'
const isSiweParamsValid = siweParams && Object.keys(siweParams || {}).length > 0
const clientId = await WalletConnectProvider?.client?.core?.crypto?.getClientId()
if (clientId) {
this.appKit?.setClientId(clientId)
}
if (
siweConfig &&
isSiweEnabled &&
siweParams &&
isProviderSupported &&
isSiweParamsValid &&
ChainController.state.activeChain === CommonConstantsUtil.CHAIN.EVM
) {
const { SIWEController, getDidChainId, getDidAddress } = await import(
'@reown/appkit-siwe'
)

const chains = this.caipNetworks
?.filter(network => network.chainNamespace === CommonConstantsUtil.CHAIN.EVM)
.map(chain => chain.caipNetworkId) as string[]

siweParams.chains = this.caipNetworks
?.filter(network => network.chainNamespace === CommonConstantsUtil.CHAIN.EVM)
.map(chain => chain.id) as number[]

const result = await WalletConnectProvider.authenticate({
nonce: await siweConfig?.getNonce?.(),
methods: [...OPTIONAL_METHODS],
...siweParams,
chains
})
// Auths is an array of signed CACAO objects https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
const signedCacao = result?.auths?.[0]

if (signedCacao) {
const { p, s } = signedCacao
const cacaoChainId = getDidChainId(p.iss)
const address = getDidAddress(p.iss)
if (address && cacaoChainId) {
SIWEController.setSession({
address,
chainId: parseInt(cacaoChainId, 10)
})
}

try {
// Kicks off verifyMessage and populates external states
const message = WalletConnectProvider.client.formatAuthMessage({
request: p,
iss: p.iss
})

await SIWEController.verifyMessage({
message,
signature: s.s,
cacao: signedCacao
})
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error verifying message', error)
// eslint-disable-next-line no-console
await WalletConnectProvider.disconnect().catch(console.error)
// eslint-disable-next-line no-console
await SIWEController.signOut().catch(console.error)
throw error
}
}
} else {
const optionalNamespaces = WcHelpersUtil.createNamespaces(this.caipNetworks)
await WalletConnectProvider.connect({ optionalNamespaces })
}
this.setWalletConnectProvider()
const optionalNamespaces = WcHelpersUtil.createNamespaces(this.caipNetworks)
await WalletConnectProvider.connect({ optionalNamespaces })
}

this.appKit?.setClientId(await WalletConnectProvider.client.core.crypto.getClientId())

this.setWalletConnectProvider()
},

disconnect: async () => {
SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID)

if (siweConfig?.options?.signOutOnDisconnect) {
const { SIWEController } = await import('@reown/appkit-siwe')
await SIWEController.signOut()
}

await this.walletConnectProvider?.disconnect()

this.appKit?.resetAccount(CommonConstantsUtil.CHAIN.EVM)
Expand Down
Loading