Sign Message
Once the connection is complete, we will get the user's JoyID information, such as address, public key, credential, etc. In this guide, we will continue our previous journey in Connect by signing a challenge after the connection is complete.
You can use @joyid/evm
SDK to sign a challenge and you can also use @joyid/ethers
SDK to use JoyID provider to sign a challenge. See ethers adapter for more details.
To sign a challenge with the user's JoyID, we need to do the following steps:
Step 1: Save JoyID info
In the previous guide, we have already connected the user with JoyID, and we have got the user's JoyID information. Now we need to save the user's JoyID information. We can save it in the local storage, or in the state of the React component, or in the Vuex store of the Vue app, etc.
import * as React from "react";
import {connect} from "@joyid/evm";
import "./style.css";
export default function App() {
const [joyidInfo, setJoyidInfo] = React.useState(null);
const onConnect = async () => {
try {
const authData = await connect();
setJoyidInfo(authData);
} catch (error) {
console.log(error);
}
};
return (
<div>
<h1>Hello JoyID!</h1>
<button onClick={onConnect}>Connect JoyID</button>
</div>
);
}
Step 2: Sign a challenge
After the connection is complete, we need to add a button
element and listen to the click
event. When the user clicks the button, we will call the signChallenge
function to sign a challenge
with the user's JoyID.
Note that address
is required in the signChallenge
function. You can only sign the challenge
with the user's JoyID if you know the user's address. The address
is included in JoyID info.
Verify the credential before signing a challenge
import * as React from "react";
import {connect, signChallenge} from "@joyid/evm";
import {verifyCredential} from "@joyid/core";
import "./style.css";
export default function App() {
const [joyidInfo, setJoyidInfo] = React.useState(null);
const [challenge, setChallenge] = React.useState("Sign this for me");
const onConnect = async () => {
try {
const authData = await connect();
setJoyidInfo(authData);
} catch (error) {
console.log(error);
}
};
const onSign = async () => {
const {keyType, address, pubkey, alg} = joyidInfo;
if (keyType === "main_session_key" || keyType === "sub_session_key") {
const isValid = await verifyCredential(pubkey, address, keyType, alg);
if (!isValid) {
alert("Your key is expired, please re-authenticate with JoyID");
return;
}
}
const res = await signChallenge(challenge, joyidInfo.ethAddress);
if (res) {
alert("Sign message successfully");
console.log(`Sign message result: ${res}`);
}
};
return (
<div id="app">
<h1>Hello JoyID!</h1>
{joyidInfo ? null : <button onClick={onConnect}>Connect JoyID</button>}
{joyidInfo ? (
<div>
<textarea value={challenge} onChange={(e) => setChallenge(e.target.value)} />
<button onClick={onSign}>Sign With JoyID</button>
</div>
) : null}
</div>
);
}
signChallenge
function, please check the API Reference.challenge
vs. message