Sign Transaction
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 transactions to send CKB after the connection is complete.
You can use @joyid/ckb
SDK to sign a transaction to send CKB native token to others.
To sign a transaction 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/ckb'
import './style.css'
export default function App() {
const onConnect = async () => {
try {
const authData = await connect()
console.log(`JoyID user info:`, authData)
} catch (error) {
console.log(error)
}
}
return (
<div>
<h1>Hello JoyID!</h1>
<button onClick={onConnect}>Connect JoyID</button>
</div>
)
}
Step 2: Sign a Transaction
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 signTransaction
to sign a CKB transaction with the user's JoyID.
Before sending CKB token to others, you can claim CKB token on Testnet from CKB Faucet (opens in a new tab) to your ckb address.
import * as React from 'react'
import { connect, signTransaction } from '@joyid/ckb'
import './style.css'
export default function App() {
const [joyidInfo, setJoyidInfo] = React.useState(null)
const [toAddress, setToAddress] = React.useState(
'ckt1qrfrwcdnvssswdwpn3s9v8fp87emat306ctjwsm3nmlkjg8qyza2cqgqqxv6drphrp47xalweq9pvr6ll3mvkj225quegpcw',
)
const [amount, setAmount] = React.useState('100')
const onConnect = async () => {
try {
const authData = await connect()
setJoyidInfo(authData)
} catch (error) {
console.log(error)
}
}
const onSign = async () => {
const signedTx = await signTransaction({
to: toAddress,
from: joyidInfo.address,
amount: BigInt(Number(amount) * 10 ** 8).toString(),
})
console.log('signedTx', signedTx)
// You can use CKB RPC `sendTransaction` to send the `signedTx` to the blockchain.
}
return (
<div>
<h1>Hello JoyID!</h1>
{joyidInfo ? null : <button onClick={onConnect}>Connect JoyID</button>}
{joyidInfo ? (
<div>
<textarea value={toAddress} onChange={e => setToAddress(e.target.value)} />
<textarea value={amount} onChange={e => setAmount(e.target.value)} />
<button onClick={onSign}>Sign</button>
</div>
) : null}
</div>
)
}
To learn more about the signTransaction
function, please check the API Reference.