Skip to content

Commit

Permalink
refactor: logic for new address and chain event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
zoruka committed Nov 15, 2024
1 parent bcab8ea commit ccc25f4
Showing 1 changed file with 9 additions and 25 deletions.
34 changes: 9 additions & 25 deletions packages/scaffold-ui/src/modal/w3m-modal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { UiHelperUtil, customElement, initializeTheming } from '@reown/appkit-ui
import { LitElement, html } from 'lit'
import { state } from 'lit/decorators.js'
import styles from './styles.js'
import { type CaipAddress, type CaipNetwork } from '@reown/appkit-common'
import { type CaipAddress } from '@reown/appkit-common'

// -- Helpers --------------------------------------------- //
const SCROLL_LOCK = 'scroll-lock'
Expand All @@ -32,8 +32,6 @@ export class W3mModal extends LitElement {

@state() private caipAddress = ChainController.state.activeCaipAddress

@state() private caipNetwork = ChainController.state.activeCaipNetwork

@state() private shake = ModalController.state.shake

public constructor() {
Expand All @@ -44,7 +42,6 @@ export class W3mModal extends LitElement {
...[
ModalController.subscribeKey('open', val => (val ? this.onOpen() : this.onClose())),
ModalController.subscribeKey('shake', val => (this.shake = val)),
ChainController.subscribeKey('activeCaipNetwork', val => this.onNewNetwork(val)),
ChainController.subscribeKey('activeCaipAddress', val => this.onNewAddress(val))
]
)
Expand Down Expand Up @@ -165,32 +162,19 @@ export class W3mModal extends LitElement {
}

private async onNewAddress(caipAddress?: CaipAddress) {
const nextConnected = caipAddress ? CoreHelperUtil.getPlainAddress(caipAddress) : undefined

this.caipAddress = caipAddress

await SIWXUtil.initializeIfEnabled()
const currentNetwork = CoreHelperUtil.getNetworkId(this.caipAddress)
const nextNetwork = CoreHelperUtil.getNetworkId(caipAddress)
const isNextConnected = Boolean(CoreHelperUtil.getPlainAddress(caipAddress))

if (!nextConnected) {
ModalController.close()
}
}

private onNewNetwork(nextCaipNetwork: CaipNetwork | undefined) {
if (!this.caipAddress) {
this.caipNetwork = nextCaipNetwork
if (currentNetwork && nextNetwork && currentNetwork !== nextNetwork) {
RouterController.goBack()

return
} else if (!isNextConnected) {
ModalController.close()
}

const prevCaipNetworkId = this.caipNetwork?.caipNetworkId?.toString()
const nextNetworkId = nextCaipNetwork?.caipNetworkId?.toString()
await SIWXUtil.initializeIfEnabled()

if (prevCaipNetworkId && nextNetworkId && prevCaipNetworkId !== nextNetworkId) {
RouterController.goBack()
}
this.caipNetwork = nextCaipNetwork
this.caipAddress = caipAddress
}
}

Expand Down

0 comments on commit ccc25f4

Please sign in to comment.