Skip to content

Commit 44f5636

Browse files
committed
feat(single mode and support ready event): single mode and support ready event
1 parent 7d66a6e commit 44f5636

File tree

4 files changed

+108
-21
lines changed

4 files changed

+108
-21
lines changed

example/basic-dapp/index.html

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"width=device-width, initial-scale=1">
1010
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
1111
<link rel="stylesheet" href=
12-
"https://cdn.jsdelivr.net/npm/@picocss/pico@latest/css/pico.min.css">
12+
"./pico.min.css">
1313
<!-- Place favicon.ico in the root directory -->
1414
</head>
1515
<body>
@@ -178,12 +178,22 @@
178178
Result: <span id="identify_result">N/A</span>
179179
</footer>
180180
</article>
181+
182+
<article>
183+
<header>
184+
检查登录状态
185+
</header>
186+
<button id="checklogin_button">检查
187+
</button>
188+
<footer>
189+
Result: <span id="checklogin_result">N/A</span>
190+
</footer>
191+
</article>
181192
</div>
182193

183194
<script>
184195
const now = new Date()
185-
document.write(`<script type='text/javascript' src='../../dist/anyweb-js-sdk.umd.min.js?v=${now
186-
.getFullYear()}${now.getMonth()}${now.getDate()}'><\/script>`);
196+
document.write(`<script type='text/javascript' src='../../dist/anyweb-js-sdk.umd.min.js?v=${now.getFullYear()}${now.getMonth() + 1}${now.getDate()}'><\/script>`);
187197
</script>
188198

189199
<script type="module">

example/basic-dapp/index.js

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,11 @@ const confluxFaucetContract = new Conflux().Contract({
423423
type: 'address',
424424
},
425425
{ internalType: 'uint256', name: 'interval', type: 'uint256' },
426-
{ internalType: 'uint256', name: 'amount', type: 'uint256' },
426+
{
427+
internalType: 'uint256',
428+
name: 'amount',
429+
type: 'uint256',
430+
},
427431
],
428432
name: 'setClaimSetting',
429433
outputs: [],
@@ -516,6 +520,10 @@ const abi = [
516520
const provider = new window.AnyWeb.Provider({
517521
appId: '693b6401-135a-4dc3-846b-1c05ad2572f6',
518522
}) //
523+
console.log('开始监听是否准备好')
524+
provider.on('ready', async () => {
525+
walletInitialized()
526+
})
519527

520528
function getElement(id) {
521529
return document.getElementById(id)
@@ -577,6 +585,7 @@ async function walletInitialized() {
577585
const importAddressInput = getElement('import_address_input')
578586
const importAddressNameInput = getElement('import_address_name_input')
579587
const identifyButton = getElement('identify_button')
588+
const checkLoginButton = getElement('checklogin_button')
580589

581590
const deployContract = getElement('deploy_contract')
582591

@@ -619,19 +628,6 @@ async function walletInitialized() {
619628
identifyButton.disabled = true
620629
}
621630

622-
provider.on('accountsChanged', (accounts) => {
623-
console.log('accountsChanged, accounts = ', accounts)
624-
if (!accounts || !accounts.length || accounts.length === 0) {
625-
return unAuthed()
626-
}
627-
authed(accounts[0])
628-
})
629-
630-
provider.on('chainChanged', (chainId) => {
631-
console.log('chainChanged called', chainId)
632-
getElement('chainId').innerHTML = chainId
633-
})
634-
635631
try {
636632
provider.request({ method: 'anyweb_version' }).then((version) => {
637633
getElement('version').innerHTML = version
@@ -673,6 +669,19 @@ async function walletInitialized() {
673669
console.error('try 到错误了', e)
674670
}
675671

672+
provider.on('accountsChanged', (accounts) => {
673+
console.log('accountsChanged, accounts = ', accounts)
674+
if (!accounts || !accounts.length || accounts.length === 0) {
675+
return unAuthed()
676+
}
677+
authed(accounts[0])
678+
})
679+
680+
provider.on('chainChanged', (chainId) => {
681+
console.log('chainChanged called', chainId)
682+
getElement('chainId').innerHTML = chainId
683+
})
684+
676685
connectButton.onclick = async () => {
677686
const data = await provider.request({
678687
method: 'cfx_accounts',
@@ -914,6 +923,19 @@ async function walletInitialized() {
914923
console.log('err', err)
915924
}
916925
}
926+
927+
checkLoginButton.onclick = async () => {
928+
try {
929+
provider
930+
.request({ method: 'anyweb_loginstate', params: [] })
931+
.then((result) => {
932+
getElement('checklogin_result').innerHTML = result
933+
console.log('result', result)
934+
})
935+
} catch (err) {
936+
console.log('err', err)
937+
}
938+
}
917939
}
918940

919941
window.addEventListener('load', async () => {
@@ -927,10 +949,10 @@ window.addEventListener('load', async () => {
927949
}
928950

929951
if (isAnyWebInstall()) {
952+
console.log('DApp 已经检查到OK了')
930953
provider.request({ method: 'anyweb_version' }).then((version) => {
931954
getElement('version').innerHTML = version
932955
})
933-
walletInitialized()
934956
} else {
935957
alert('找不到AnyWeb SDK, 请检查是否正确配置')
936958
}

example/basic-dapp/pico.min.css

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/provider.ts

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@
66
import {
77
IAuthResult,
88
IBaseProviderOptions,
9+
IIframeData,
910
IIframeOptions,
1011
IProvider,
1112
IProviderConnectInfo,
1213
IProviderMessage,
1314
IProviderRpcError,
1415
IRequestArguments,
1516
} from './interface/provider'
16-
import { callIframe, createIframe } from './utils/common'
17+
import { callIframe, createIframe, isObject } from './utils/common'
1718
import config from '../package.json'
1819
import { AddressType, getAddressType } from './utils/address'
1920
import { ConsoleLike } from './utils/types'
@@ -27,9 +28,11 @@ import { ConsoleLike } from './utils/types'
2728
* const provider = new Provider()
2829
*/
2930
export class Provider implements IProvider {
30-
logger: ConsoleLike
31-
public readonly appId: string
31+
logger!: ConsoleLike
32+
public readonly appId!: string
3233
private chainId = 1
34+
private static instance: Provider
35+
public static ready = false
3336

3437
events: {
3538
onConnect?: (connectInfo: IProviderConnectInfo) => void
@@ -38,9 +41,15 @@ export class Provider implements IProvider {
3841
onAccountsChanged?: (accounts: string[]) => void
3942
onMessage?: (message: IProviderMessage) => void
4043
onNetworkChanged?: (networkId: string) => void
44+
onReady?: () => void
4145
} = {}
4246

4347
constructor({ logger, appId }: IBaseProviderOptions) {
48+
if (Provider.instance) {
49+
return Provider.instance
50+
}
51+
Provider.instance = this
52+
4453
if (!logger) {
4554
logger = console
4655
}
@@ -58,11 +67,44 @@ export class Provider implements IProvider {
5867
window.anyweb = this
5968
}
6069

70+
const messageHandler = (event: MessageEvent) => {
71+
if (
72+
event.data &&
73+
isObject(event.data) &&
74+
'type' in event.data &&
75+
event.data.type === 'anyweb'
76+
) {
77+
const IframeData = event.data.data as IIframeData
78+
if (
79+
IframeData.type == 'event' &&
80+
IframeData.data == 'ready' &&
81+
IframeData.success
82+
) {
83+
console.debug('[AnyWeb] SDK初始化完成')
84+
Provider.ready = true
85+
this.events.onReady && this.events.onReady()
86+
window.removeEventListener('message', messageHandler)
87+
}
88+
}
89+
}
90+
window.addEventListener('message', messageHandler)
91+
6192
createIframe('pages/index/home')
6293
.then()
6394
.catch((e) => console.error('[AnyWeb] createIframe error', e))
6495
}
6596

97+
public static getInstance(params?: IBaseProviderOptions) {
98+
if (!Provider.instance) {
99+
if (params) {
100+
Provider.instance = new Provider(params)
101+
} else {
102+
throw new Error('[AnyWeb] Provider is not initialized')
103+
}
104+
}
105+
return Provider.instance
106+
}
107+
66108
/**
67109
* Deprecated: use `request` instead
68110
* @param arg
@@ -125,6 +167,11 @@ export class Provider implements IProvider {
125167
* @protected
126168
*/
127169
protected async rawRequest(method: string, params?: any): Promise<unknown> {
170+
if (!Provider.ready) {
171+
throw new Error(
172+
"[AnyWeb] Provider is not ready, please use on('ready', callback) to listen to ready event"
173+
)
174+
}
128175
switch (method) {
129176
case 'cfx_requestAccounts':
130177
return this.rawRequest('cfx_accounts')
@@ -349,6 +396,9 @@ export class Provider implements IProvider {
349396
case 'networkChanged':
350397
this.events.onNetworkChanged = listener
351398
break
399+
case 'ready':
400+
this.events.onReady = listener
401+
break
352402
default:
353403
break
354404
}

0 commit comments

Comments
 (0)