@raydius/react
v0.1.8
Published
## Getting Started
Downloads
133
Readme
@raydius/react
Getting Started
Install
npm install @raydius/react
Usage
- Initialization
Aptos
- import aptos connector like import evm connector, and injected to RaydiusProvider
import { aptosNightlyConnector, aptosPetraConnector } from '@raydius/connector'
const config = {
appId: 'xxxxx'
connectors: [
metamaskConnector({
dappMetadata: {
name: 'custom-metadata-name',
},
}),
aptosNightlyConnector(),
aptosPetraConnector(),
],
// ...otherConfig
}
<RaydiusProvider config={config}>{children}</RaydiusProvider>
- get Account and network
- use
useAccount
fromwagmi
import { useAccount } from 'wagmi' const {address} =useAccount() console.log(address) // string, like '0x87987897vxvxcvsdfdsf98789789789798798'
- use
useAptos
from@raydius/react
import { useRaydius, useAptos } from '@raydius/react' const { network, account } = useAptos() console.log(network) // { name: string, chainId: string, url?: string; } console.log(account) // {address: string; publicKey: string | string[]; minKeysRequire: number; ansName?: string | null;}
- use
- signMessage
const {
signMessageAndVerify,
signMessage,
} = useAptos()
const onSignMessage = async () => {
const payload = {
message: message1 || 'Hello from Aptos Wallet Adapter',
nonce: Math.random().toString(16),
}
const response = await signMessage(payload)
console.log(response)
}
const onSignMessageAndVerify = async () => {
const payload = {
message: 'Hello from Aptos Wallet Adapter',
nonce: Math.random().toString(16),
}
const response = await signMessageAndVerify(payload)
console.log('response', response)
}
- sign Transcation and submit
const {
account,
client:aptosClient,
signTransaction,
signMessageAndVerify,
signMessage,
signAndSubmitTransaction,
} = useAptos()
const address = account?.address
const onSignTransaction = async () => {
try {
const payload = {
type: 'entry_function_payload',
function: '0x1::coin::transfer',
type_arguments: ['0x1::aptos_coin::AptosCoin'],
arguments: [address, 1], // 1 is in Octas
}
const response = await signTransaction(payload)
console.log(response)
} catch (error) {
console.error(error)
}
}
const onSignAndSubmitTransaction = useCallback(async () => {
if (!address) return
const transaction = {
data: {
function: '0x1::coin::transfer',
typeArguments: [APTOS_COIN],
functionArguments: [address, 1], // 1 is in Octas
},
}
try {
const response = await signAndSubmitTransaction(transaction)
await aptosClient.waitForTransaction({
transactionHash: response.hash,
})
} catch (error) {
console.error(error)
}
}, [address, aptosClient])
Solana
- import solana connector like import evm connector, and injected to RaydiusProvider
import { solanaPhantomConnector } from '@raydius/connector'
const config = {
appId: 'xxxxx'
connectors: [
solanaPhantomConnector()
...otherconnector()
],
// ...otherConfig
}
<RaydiusProvider config={config}>{children}</RaydiusProvider>
- get Account
- use
useAccount
fromwagmi
import { useAccount } from 'wagmi' const {address} =useAccount() console.log(address) // string, like 'MemoSq4gqxxxxxMyWCqXgDLGmfcHr'
- use
useSolana
from@raydius/react
import { useRaydius, useSolana } from '@raydius/react' const { wallet, wallets, publicKey, address } = useSolana()
- use
- signMessage
import bs58 from 'bs58'
import { useRaydius, useSolana } from '@raydius/react'
const { signMessage signIn,publicKey } = useSolana()
async function onSignMessage() {
const message = 'Hello2'
const messageBuffer = Buffer.from(message) // the same with new TextEncoder().encode(message)
const signature = await signMessage?.(messageBuffer)
if (signature) {
// console.log(
// 'bs58.encode(signature)22',
// bs58.encode(signature),
// Buffer.from(signature).toString('hex')
// )
toast({
title: 'Signature successfully',
description: bs58.encode(signature),
})
}
}
async function onSignIn() {
try {
if (!signIn)
throw new Error('Wallet does not support Sign In With Solana!')
const input = {
domain: window.location.host,
address: publicKey ? publicKey.toBase58() : undefined,
statement: 'Please sign in.',
}
const output = await signIn(input)
toast({
title: `success`,
description: `Message signature: ${bs58.encode(output.signature)}`,
})
} catch (error: any) {
toast({
title: `error`,
description: `Sign In failed: ${error?.message}`,
})
}
}
- sign Transcation and send Transcation
import { useSolana } from '@raydius/react'
import bs58 from 'bs58'
import {
PublicKey,
Transaction,
TransactionInstruction,
TransactionMessage,
VersionedTransaction,
LAMPORTS_PER_SOL,
} from '@solana/web3.js'
import type { SolanaSignInInput } from '@solana/wallet-standard-features'
const {
wallet,
wallets,
publicKey,
address,
connection,
signMessage,
sendTransaction,
signTransaction,
signIn,
} = useSolana()
async function onSignTransaction() {
try {
if (!publicKey) throw new Error('Wallet not connected!')
if (!signTransaction)
throw new Error('Wallet does not support transaction signing!')
const { blockhash } = await connection.getLatestBlockhash()
let transaction = new Transaction({
feePayer: publicKey,
recentBlockhash: blockhash,
}).add(
new TransactionInstruction({
data: Buffer.from(
'Hello, from the Solana Wallet Adapter example app!'
),
keys: [],
programId: new PublicKey(
'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
),
})
)
transaction = await signTransaction(transaction)
if (!transaction.signature) throw new Error('Transaction not signed!')
const signature = bs58.encode(transaction.signature)
toast({
title: `Transaction signed ${signature}`,
})
if (!transaction.verifySignatures())
throw new Error(`Transaction signature invalid! ${signature}`)
toast({
title: `Transaction signature valid! ${signature}`,
})
} catch (error: any) {
toast({
title: `Transaction signing failed! ${error?.message}`,
})
}
}
async function onSendV0Transaction() {
try {
if (!publicKey) throw new Error('Wallet not connected!')
if (!supportedTransactionVersions)
throw new Error("Wallet doesn't support versioned transactions!")
if (!supportedTransactionVersions.has(0))
throw new Error("Wallet doesn't support v0 transactions!")
/**
* This lookup table only exists on devnet and can be replaced as
* needed. To create and manage a lookup table, use the `solana
* address-lookup-table` commands.
*/
const { value: lookupTable } = await connection.getAddressLookupTable(
new PublicKey('F3MfgEJe1TApJiA14nN2m4uAH4EBVrqdBnHeGeSXvQ7B')
)
if (!lookupTable) throw new Error("Address lookup table wasn't found!")
const {
context: { slot: minContextSlot },
value: { blockhash, lastValidBlockHeight },
} = await connection.getLatestBlockhashAndContext()
const message = new TransactionMessage({
payerKey: publicKey,
recentBlockhash: blockhash,
instructions: [
{
data: Buffer.from(
'Hello, from the Solana Wallet Adapter example app!'
),
keys: lookupTable.state.addresses.map((pubkey, index) => ({
pubkey,
isWritable: index % 2 == 0,
isSigner: false,
})),
programId: new PublicKey(
'Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo'
),
},
],
})
const transaction = new VersionedTransaction(
message.compileToV0Message([lookupTable])
)
const signature = await sendTransaction?.(transaction, connection, {
minContextSlot,
})
toast({
title: `Transaction sent: ${signature}`,
})
// @ts-ignore
await connection?.confirmTransaction?.({
blockhash,
lastValidBlockHeight,
signature,
})
toast({
title: `Transaction successful!: ${signature}`,
})
} catch (error: any) {
toast({
title: `Transaction failed! ${error?.message}`,
})
}
}
async function onSendLegacyTransaction() {
try {
if (!publicKey) throw new Error('Wallet not connected!')
if (!supportedTransactionVersions)
throw new Error("Wallet doesn't support versioned transactions!")
if (!supportedTransactionVersions.has('legacy'))
throw new Error("Wallet doesn't support legacy transactions!")
const {
context: { slot: minContextSlot },
value: { blockhash, lastValidBlockHeight },
} = await connection.getLatestBlockhashAndContext()
const message = new TransactionMessage({
payerKey: publicKey,
recentBlockhash: blockhash,
instructions: [
{
data: Buffer.from(
'Hello, from the Solana Wallet Adapter example app!'
),
keys: [],
programId: new PublicKey(
'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'
),
},
],
})
const transaction = new VersionedTransaction(
message.compileToLegacyMessage()
)
const signature = await sendTransaction?.(transaction, connection, {
minContextSlot,
})
toast({
title: `Transaction sent: ${signature}`,
})
// @ts-ignore
await connection.confirmTransaction({
blockhash,
lastValidBlockHeight,
signature,
})
toast({
title: `Transaction successful!: ${signature}`,
})
} catch (error: any) {
toast({
title: `Transaction failed! ${error?.message}`,
})
}
}