### Install Project Dependencies Source: https://github.com/okx/okxconnectdemo/blob/main/README.md Run this command to install all necessary project dependencies using Yarn. ```sh yarn install ``` -------------------------------- ### Compile and Run in Development Mode Source: https://github.com/okx/okxconnectdemo/blob/main/README.md Use this command to compile the project and start it in hot-reloading development mode with Yarn. ```sh yarn dev ``` -------------------------------- ### Aptos Message Signing and Transaction Building Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXAptosProvider to sign messages and build/sign/submit transactions on the Aptos blockchain. Ensure the Aptos SDK is installed. ```typescript import { OKXAptosProvider } from "@okxconnect/aptos-provider"; import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk"; // Create Aptos provider const aptosProvider = new OKXAptosProvider(provider); const chainId = "aptos:mainnet"; // Sign a message const signedMessage = await aptosProvider.signMessage( { address: true, application: true, chainId: true, message: "Hello Aptos", nonce: "1234", }, chainId ); // Build and sign a transaction const config = new AptosConfig({ network: Network.MAINNET }); const aptos = new Aptos(config); const account = aptosProvider.getAccount(chainId); const transaction = await aptos.transaction.build.simple({ sender: account.address, data: { function: "0x80273859084bc47f92a6c2d3e9257ebb2349668a1b0fb3db1d759a04c7628855::router::swap_exact_coin_for_coin_x1", typeArguments: [ "0x1::aptos_coin::AptosCoin", "0x111ae3e5bc816a5e63c2da97d0aa3886519e0cd5e4b046659fa35796bd11542a::stapt_token::StakedApt", "0x0163df34fccbf003ce219d3f1d9e70d140b60622cb9dd47599c25fb2f797ba6e::curves::Uncorrelated", "0x80273859084bc47f92a6c2d3e9257ebb2349668a1b0fb3db1d759a04c7628855::router::BinStepV0V05", ], functionArguments: ["10000", ["9104"], ["5"], ["true"]], }, }); const signedTx = await aptosProvider.signTransaction(transaction, chainId); // Sign and submit transaction const submittedTx = await aptosProvider.signAndSubmitTransaction(transaction, chainId); ``` -------------------------------- ### Get Connected Sui Account Source: https://context7.com/okx/okxconnectdemo/llms.txt Retrieve the currently connected account's address using the OKXSuiProvider. This is a prerequisite for signing messages or transactions. ```typescript import { OKXSuiProvider } from "@okxconnect/sui-provider"; import { SuiClient } from "@mysten/sui/client"; import { Transaction as SuiTransaction } from "@mysten/sui/transactions"; import { verifyPersonalMessageSignature } from "@mysten/sui/verify"; // Create Sui provider const suiProvider = new OKXSuiProvider(provider); // Get connected account const account = suiProvider.getAccount(); console.log("Address:", account?.address); ``` -------------------------------- ### Initialize OKX Connect with UI Modal Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXUniversalConnectUI for a ready-to-use modal interface for wallet connections. Customize theming and language. Requires specific dappMetaData and actionsConfiguration. ```typescript import { OKXUniversalConnectUI, THEME } from "@okxconnect/ui"; // Initialize OKX Connect with UI modal const provider = await OKXUniversalConnectUI.init({ dappMetaData: { icon: "https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png", name: "OKX Connect UI Example", }, actionsConfiguration: { returnStrategy: "none", modals: "all", }, language: "en_US", uiPreferences: { theme: THEME.LIGHT, }, }); // Open connection modal with specified chain namespaces await provider.openModal({ namespaces: { eip155: { chains: ["eip155:1"], defaultChain: "eip155:1", }, }, }); ``` -------------------------------- ### Initialize OKX Universal Provider Programmatically Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXUniversalProvider for programmatic control over wallet connections without a built-in UI. Listen for connection and disconnection events. ```typescript import { OKXUniversalProvider } from "@okxconnect/universal-provider"; // Initialize provider without UI const provider = await OKXUniversalProvider.init({ dappMetaData: { icon: "https://static.okx.com/cdn/assets/imgs/247/58E63FEA47A2B7D7.png", name: "OKX Connect Example", }, }); // Connect programmatically with chain namespaces await provider.connect({ namespaces: { eip155: { chains: ["eip155:1"], defaultChain: "eip155:1", }, }, }); // Listen for connection events provider.on("connect", (session) => { console.log("Connected:", session); }); provider.on("disconnect", ({ topic }) => { console.log("Disconnected:", topic); }); ``` -------------------------------- ### Handle Provider Connection Lifecycle Events Source: https://context7.com/okx/okxconnectdemo/llms.txt Manage wallet connection states by listening to provider events like connection, disconnection, and session updates. Ensure necessary imports for OKXUniversalConnectUI and SessionTypes. ```typescript import { OKXUniversalConnectUI, type SessionTypes } from "@okxconnect/ui"; // Add event listeners to provider provider.on("display_uri", (uri: string) => { // Display QR code for mobile wallet connection console.log("Connection URI:", uri); }); provider.on("connect", (session: SessionTypes.Struct) => { // Handle successful connection const chain = Object.values(session.namespaces)[0].chains[0]; console.log("Connected to chain:", chain); localStorage.setItem("connectedChain", chain); }); provider.on("reconnect", (session: SessionTypes.Struct) => { // Handle reconnection console.log("Reconnected:", session); }); provider.on("disconnect", ({ topic }: { topic: string }) => { // Handle disconnection console.log("Disconnected:", topic); localStorage.removeItem("connectedChain"); }); provider.on("session_update", (session: SessionTypes.Struct) => { // Handle session updates console.log("Session updated:", session); }); provider.on("session_delete", ({ topic }: { topic: string }) => { // Handle session deletion console.log("Session deleted:", topic); }); // Disconnect wallet await provider.disconnect(); ``` -------------------------------- ### Cosmos Arbitrary and Amino Message Signing Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXCosmosProvider for Cosmos operations, including arbitrary message signing with verification and Amino signing. Requires @cosmjs/encoding and @keplr-wallet/cosmos. ```typescript import { OKXCosmosProvider } from "@okxconnect/universal-provider"; import { fromBech32 } from "@cosmjs/encoding"; import { verifyADR36Amino } from "@keplr-wallet/cosmos"; // Create Cosmos provider const cosmosProvider = new OKXCosmosProvider(provider); const chainId = "cosmos:osmosis-1"; // Get connected account const account = cosmosProvider.getAccount(chainId); // Sign arbitrary message with verification const signResult = await cosmosProvider.signArbitrary( chainId, account.address, "test cosmos" ); // Verify the signature const { prefix } = fromBech32(account.address); const isValid = await verifyADR36Amino( prefix, account.address, "test cosmos", new Uint8Array(Buffer.from(signResult.pub_key.value, "base64")), new Uint8Array(Buffer.from(signResult.signature, "base64")) ); // Sign Amino transaction const aminoTx = await cosmosProvider.signAmino(chainId, account.address, { chain_id: "osmosis-1", account_number: "630104", sequence: "480", fee: { gas: "683300", amount: [{ denom: "uosmo", amount: "2818" }] }, msgs: [ { type: "osmosis/poolmanager/swap-exact-amount-in", value: { sender: account.address, routes: [{ pool_id: "1096", token_out_denom: "ibc/..." }], token_in: { denom: "uosmo", amount: "100" }, token_out_min_amount: "8", }, }, ], memo: "FE", }); ``` -------------------------------- ### Send Bitcoin Source: https://context7.com/okx/okxconnectdemo/llms.txt Send Bitcoin using OKXBtcProvider. Specify the recipient address, amount in satoshis, and optionally a fee rate. ```typescript // Send Bitcoin const txHash = await btcProvider.sendBitcoin( chainId, "1NKnZ3uAuQLnmExA3WY44u1efwCgTiAxBn", // recipient address 17100, // satoshis { feeRate: 16 } ); ``` -------------------------------- ### Sign and Verify Solana Message Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXSolanaProvider to sign a message and verify its authenticity. Ensure the provider is initialized with the correct connection details. ```typescript import { OKXSolanaProvider } from "@okxconnect/solana-provider"; import { Connection, PublicKey, SystemProgram, Transaction, TransactionMessage, VersionedTransaction, } from "@solana/web3.js"; import nacl from "tweetnacl"; // Create Solana provider const solProvider = new OKXSolanaProvider(provider); const chainId = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"; // Sign a message and verify const message = await solProvider.signMessage("Hello Solana", chainId); const isValid = nacl.sign.detached.verify( new TextEncoder().encode("Hello Solana"), message.signature, new PublicKey(message.publicKey).toBytes() ); ``` -------------------------------- ### Sign Bitcoin Message Source: https://context7.com/okx/okxconnectdemo/llms.txt Use OKXBtcProvider to sign a message on the Bitcoin network. This is useful for authentication or proving ownership. ```typescript import { OKXBtcProvider } from "@okxconnect/universal-provider"; // Create Bitcoin provider const btcProvider = new OKXBtcProvider(provider); const chainId = "btc:mainnet"; // Sign a message const signature = await btcProvider.signMessage( chainId, "Welcome to UniSat!\n\nClick to sign in and accept the Terms of Service." ); ``` -------------------------------- ### TRON Operations with OKXTronProvider Source: https://context7.com/okx/okxconnectdemo/llms.txt Perform TRON blockchain operations including signing messages, transferring TRX, and interacting with smart contracts. Requires importing OKXTronProvider and TronWeb. ```typescript import { OKXTronProvider } from "@okxconnect/universal-provider"; import { TronWeb } from "tronweb"; // Create TRON provider const tronProvider = new OKXTronProvider(provider); const chainId = "tron:mainnet"; // Get connected account const account = tronProvider.getAccount(chainId); // Sign message and verify const signature = await tronProvider.signMessageV2("Hello Tron", chainId); const tronWeb = new TronWeb({ fullHost: "https://api.trongrid.io" }); const recoveredAddress = await tronWeb.trx.verifyMessageV2("Hello Tron", signature); const isValid = recoveredAddress === account.address; // Build and send TRX transfer const transaction = await tronWeb.transactionBuilder.sendTrx( "TGBcVLMnVtvJzjPWZpPiYBgwwb7th1w3BF", // recipient 1000, // amount in SUN account.address ); const signedTx = await tronProvider.signTransaction(transaction, chainId); // Sign and send in one step const txResult = await tronProvider.signAndSendTransaction(transaction, chainId); // Interact with smart contract const contractAddress = "41e95812d8d5b5412d2b9f3a4d5a87ca15c5c51f33"; const contractTx = await tronWeb.transactionBuilder.triggerSmartContract( contractAddress, "quote(uint256,uint256,uint256)", {}, [{ type: "uint256", value: 1 }, { type: "uint256", value: 1 }, { type: "uint256", value: 1 }], account.address ); const contractResult = await tronProvider.signAndSendTransaction(contractTx.transaction, chainId); ``` -------------------------------- ### Sign and Broadcast Solana Versioned Transaction Source: https://context7.com/okx/okxconnectdemo/llms.txt Build, sign, and broadcast a versioned transaction on Solana using OKXSolanaProvider. This includes fetching the latest blockhash and compiling the transaction message. ```typescript // Build and sign a versioned transaction const connection = new Connection("https://www.okx.com/fullnode/sol/discover/rpc"); const account = solProvider.getAccount(); const { blockhash } = await connection.getLatestBlockhash(); const txMessage = new TransactionMessage({ payerKey: account.publicKey, recentBlockhash: blockhash, instructions: [ SystemProgram.transfer({ fromPubkey: account.publicKey, toPubkey: account.publicKey, lamports: 100, }), ], }).compileToV0Message(); const versionedTx = new VersionedTransaction(txMessage); const signedTx = await solProvider.signTransaction(versionedTx, chainId); // Sign and send in one step const txHash = await solProvider.signAndSendTransaction(versionedTx, chainId); ``` -------------------------------- ### Sign and Execute Sui Transaction Source: https://context7.com/okx/okxconnectdemo/llms.txt Sign and execute a Sui transaction block using OKXSuiProvider. This method combines signing with immediate execution on the network. ```typescript // Sign and execute transaction const executedTx = await suiProvider.signAndExecuteTransaction({ transactionBlock: tx, account: {}, chain: "sui:mainnet", options: { showEffects: true }, }); ``` -------------------------------- ### Sign and Broadcast Bitcoin PSBT Source: https://context7.com/okx/okxconnectdemo/llms.txt Sign and broadcast a PSBT in a single step using OKXBtcProvider. This is convenient for immediate transaction submission after signing. ```typescript // Sign and broadcast PSBT const broadcastResult = await btcProvider.signAndPushPsbt( chainId, psbtHex, { autoFinalized: true } ); ``` -------------------------------- ### TON Connection and Transaction Sending Source: https://context7.com/okx/okxconnectdemo/llms.txt Utilize OKXTonProvider for TON blockchain operations, including connecting with TON proof for authentication and sending transactions. Ensure TONCHAIN is correctly set. ```typescript import { OKXTonProvider } from "@okxconnect/universal-provider"; import { TONCHAIN } from "@okxconnect/core"; // Connect with TON proof for authentication const tonNamespaces = { ton: { chains: ["ton:-239"], defaultChain: "ton:-239", params: { ton_addr: { name: "ton_addr" }, ton_proof: { name: "ton_proof", payload: "your-proof-payload", }, }, }, }; // Create TON provider const tonProvider = new OKXTonProvider(provider); // Get connected account const account = tonProvider.account(); console.log("Address:", account?.address); // Send a transaction const result = await tonProvider.sendTransaction({ messages: [ { address: "EQARULUYsmJq1RiZ-YiH-IJLcAZUVkVff-KBPwEmmaQGH6aC", amount: "205000000", // in nanotons payload: "te6cckEBAgEAhwABbQ+KfqUAAADNgG7tIEATEtAIAO87mQKicbKgHIk4pSPP4k5xhHqutqYgAB7USnesDnCcECwbgQMBAJUlk4VhgBD3JEg1TUr75iTijBghOKm/sxNDXUBl7CD6WMut0Q85x4RafwA/Es89DBXoTxuqxVFxyBbzt9Rav2HBUKl7hmkvLuKHLBCW57aK", }, ], validUntil: 1792481054, network: TONCHAIN.MAINNET, }); ``` -------------------------------- ### Send Bitcoin Inscription Source: https://context7.com/okx/okxconnectdemo/llms.txt Send a Bitcoin inscription (NFT/Ordinal) using OKXBtcProvider. Requires the receiver's address, the inscription ID, and fee rate. ```typescript // Send an inscription (NFT/Ordinal) const inscriptionTx = await btcProvider.sendInscription( chainId, "bc1p...", // receiver address "inscription_id_here", { feeRate: "15" } ); ``` -------------------------------- ### Sign and Verify Sui Personal Message Source: https://context7.com/okx/okxconnectdemo/llms.txt Sign a personal message on the Sui network using OKXSuiProvider and verify the signature against the sender's public key. The message must be a Uint8Array. ```typescript // Sign a message and verify const message = new Uint8Array([76, 111, 103, 105, 110]); // "Login" const signResult = await suiProvider.signPersonalMessage({ message }); const pubKey = await verifyPersonalMessageSignature(message, signResult.signature); const isValid = account?.address === pubKey.toSuiAddress(); ``` -------------------------------- ### EVM Chain Operations: ETH Transfer and Typed Data Signing Source: https://context7.com/okx/okxconnectdemo/llms.txt Perform EVM-compatible operations like sending ETH transfers and signing typed data (EIP-712) using the unified provider. Requires connected accounts and specific transaction parameters. ```typescript import { OKXUniversalConnectUI, type RequestArguments } from "@okxconnect/ui"; // Get connected accounts const accounts: string[] = await provider.request({ method: "eth_requestAccounts", }, "eip155"); const address = accounts[0]; // Send ETH transfer transaction const transferTx = await provider.request({ method: "eth_sendTransaction", params: { to: address, from: address, chainId: "0x1", value: "0x5af3107a4000", // 0.0001 ETH maxPriorityFeePerGas: "0x3b9aca00", gas: "0x5e56", maxFeePerGas: "0x2643b9db8", }, } as RequestArguments, "eip155:1"); // Sign typed data (EIP-712) const typedDataSignature = await provider.request({ method: "eth_signTypedData_v4", params: [ address, { types: { EIP712Domain: [ { name: "name", type: "string" }, { name: "version", type: "string" }, { name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" }, ], Mail: [ { name: "from", type: "Person" }, { name: "to", type: "Person" }, { name: "contents", type: "string" }, ], Person: [ { name: "name", type: "string" }, { name: "wallet", type: "address" }, ], }, primaryType: "Mail", domain: { name: "Ether Mail", version: "1", chainId: 1, verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC", }, message: { from: { name: "Cow", wallet: "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826" }, to: { name: "Bob", wallet: "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB" }, contents: "Hello, Bob!", }, }, ], }, "eip155"); ``` -------------------------------- ### Sign Sui Transfer Transaction Source: https://context7.com/okx/okxconnectdemo/llms.txt Construct and sign a Sui transfer transaction using OKXSuiProvider. This involves creating a transaction block, splitting coins, and defining the transfer. ```typescript // Build and sign a transfer transaction const recipientAddress = "0x72f798f8b709902453d4bb55c65661e9e04154a506765f2333dfb7e7834056d2"; const tx = new SuiTransaction(); const [coin] = tx.splitCoins(tx.gas, [109]); tx.transferObjects([coin], recipientAddress); const signedTx = await suiProvider.signTransaction({ transactionBlock: tx, account: {}, chain: "sui:mainnet", options: { showEffects: true }, }); ``` -------------------------------- ### Sign Bitcoin PSBT Source: https://context7.com/okx/okxconnectdemo/llms.txt Sign a Partially Signed Bitcoin Transaction (PSBT) using OKXBtcProvider. The `autoFinalized` option controls whether the transaction is finalized after signing. ```typescript // Sign a PSBT (Partially Signed Bitcoin Transaction) const signedPsbt = await btcProvider.signPsbt( chainId, psbtHex, { autoFinalized: false } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.