SessionKeyButton.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { useState } from "react"
  2. import { Button } from "@chakra-ui/react"
  3. import { useWallet } from "@solana/wallet-adapter-react"
  4. import { useSessionWallet } from "@magicblock-labs/gum-react-sdk"
  5. import { useGameState } from "@/contexts/GameStateProvider"
  6. import { program } from "@/utils/anchor"
  7. const SessionKeyButton = () => {
  8. const { publicKey } = useWallet()
  9. const { gameState } = useGameState()
  10. const sessionWallet = useSessionWallet()
  11. const [isLoading, setIsLoading] = useState(false)
  12. const handleCreateSession = async () => {
  13. setIsLoading(true)
  14. const topUp = true
  15. const expiryInMinutes = 600
  16. try {
  17. const session = await sessionWallet.createSession(
  18. program.programId,
  19. topUp,
  20. expiryInMinutes
  21. )
  22. console.log("Session created:", session)
  23. } catch (error) {
  24. console.error("Failed to create session:", error)
  25. } finally {
  26. setIsLoading(false)
  27. }
  28. }
  29. const handleRevokeSession = async () => {
  30. setIsLoading(true)
  31. try {
  32. await sessionWallet.revokeSession()
  33. console.log("Session revoked")
  34. } catch (error) {
  35. console.error("Failed to revoke session:", error)
  36. } finally {
  37. setIsLoading(false)
  38. }
  39. }
  40. return (
  41. <>
  42. {publicKey && gameState && (
  43. <Button
  44. isLoading={isLoading}
  45. onClick={
  46. sessionWallet && sessionWallet.sessionToken == null
  47. ? handleCreateSession
  48. : handleRevokeSession
  49. }
  50. >
  51. {sessionWallet && sessionWallet.sessionToken == null
  52. ? "Create session"
  53. : "Revoke Session"}
  54. </Button>
  55. )}
  56. </>
  57. )
  58. }
  59. export default SessionKeyButton