forked from Phala-Network/js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flipper.tsx
95 lines (85 loc) · 2.52 KB
/
flipper.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import type {ApiPromise} from '@polkadot/api'
import {ContractPromise} from '@polkadot/api-contract'
import {useEffect, useState} from 'react'
import {signCertificate, CertificateData} from '@phala/sdk'
import {Button} from 'baseui/button'
import {ButtonGroup} from 'baseui/button-group'
import {toaster} from 'baseui/toast'
import {useAtom} from 'jotai'
import accountAtom from '../atoms/account'
import {getSigner} from '../lib/polkadotExtension'
import ContractLoader from '../components/ContractLoader'
const Flipper: Page = () => {
const [account] = useAtom(accountAtom)
const [certificateData, setCertificateData] = useState<CertificateData>()
const [api, setApi] = useState<ApiPromise>()
const [contract, setContract] = useState<ContractPromise>()
useEffect(
() => () => {
api?.disconnect()
},
[api]
)
useEffect(() => {
setCertificateData(undefined)
}, [account])
const onSignCertificate = async () => {
if (account && api) {
try {
const signer = await getSigner(account)
// Save certificate data to state, or anywhere else you want like local storage
setCertificateData(
await signCertificate({
api,
account,
signer,
})
)
toaster.positive('Certificate signed', {})
} catch (err) {
toaster.negative((err as Error).message, {})
}
}
}
const onQuery = async () => {
if (!certificateData || !contract) return
const {output} = await contract.query.get(certificateData as any, {})
// eslint-disable-next-line no-console
console.log(output?.toHuman())
toaster.info(JSON.stringify(output?.toHuman()), {})
}
const onCommand = async () => {
if (!contract || !account) return
const signer = await getSigner(account)
contract.tx.flip({}).signAndSend(account.address, {signer}, (status) => {
if (status.isInBlock) {
toaster.positive('In Block', {})
}
})
}
return contract ? (
<>
<ButtonGroup>
<Button disabled={!account} onClick={onSignCertificate}>
Sign Certificate
</Button>
<Button disabled={!certificateData} onClick={onQuery}>
Get
</Button>
<Button disabled={!account} onClick={onCommand}>
Flip
</Button>
</ButtonGroup>
</>
) : (
<ContractLoader
name="flipper"
onLoad={({api, contract}) => {
setApi(api)
setContract(contract)
}}
/>
)
}
Flipper.title = 'Flipper'
export default Flipper