From 55258097df75a2273d0f6496b67b19240f37a349 Mon Sep 17 00:00:00 2001
From: Francis <710892027dongyi@gmail.com>
Date: Tue, 15 Oct 2024 14:39:07 +0800
Subject: [PATCH] add log
---
examples/example-wallet-react/src/App.tsx | 2 +
examples/tg-mini-app/package.json | 1 +
examples/tg-mini-app/src/App.tsx | 5 +
examples/tg-mini-app/src/contexts/okx.ts | 278 +++++++++++++++++++
examples/tg-mini-app/src/pages/okx/index.tsx | 211 ++++++--------
examples/tg-mini-app/src/pages/okx/index.txt | 159 +++++++++++
6 files changed, 537 insertions(+), 119 deletions(-)
create mode 100644 examples/tg-mini-app/src/contexts/okx.ts
create mode 100644 examples/tg-mini-app/src/pages/okx/index.txt
diff --git a/examples/example-wallet-react/src/App.tsx b/examples/example-wallet-react/src/App.tsx
index de8df9f..f69f48f 100644
--- a/examples/example-wallet-react/src/App.tsx
+++ b/examples/example-wallet-react/src/App.tsx
@@ -87,6 +87,8 @@ function App() {
+
+
okx wallet sdk
>
)
}
diff --git a/examples/tg-mini-app/package.json b/examples/tg-mini-app/package.json
index c4b5ea4..9076b02 100644
--- a/examples/tg-mini-app/package.json
+++ b/examples/tg-mini-app/package.json
@@ -33,6 +33,7 @@
"react-router-dom": "^6.3.0",
"tailwindcss": "^3.4.4",
"typescript": "^4.7.4",
+ "vconsole": "^3.15.1",
"vite-plugin-svg-icons": "^2.0.1",
"web-vitals": "^2.1.4"
},
diff --git a/examples/tg-mini-app/src/App.tsx b/examples/tg-mini-app/src/App.tsx
index 3962d84..e39c144 100644
--- a/examples/tg-mini-app/src/App.tsx
+++ b/examples/tg-mini-app/src/App.tsx
@@ -5,6 +5,7 @@ import { GlobalProvider } from './contexts/GlobalContext'
import { useTelegram } from './hooks'
import { RenderRouter } from './routes'
import { useStores } from './stores'
+import VConsole from 'vconsole'
const App = observer(() => {
const VITE_TEL_APP_URL = import.meta.env.VITE_TEL_APP_URL
@@ -12,6 +13,10 @@ const App = observer(() => {
const { userStore } = useStores()
+ if (typeof navigator !== 'undefined' && /mobile|android|iphone|ipad|phone/i.test(navigator.userAgent.toLowerCase())) {
+ new VConsole()
+ }
+
return (
<>
diff --git a/examples/tg-mini-app/src/contexts/okx.ts b/examples/tg-mini-app/src/contexts/okx.ts
new file mode 100644
index 0000000..8165ff3
--- /dev/null
+++ b/examples/tg-mini-app/src/contexts/okx.ts
@@ -0,0 +1,278 @@
+import { useEffect, useState, useCallback } from "react";
+import { OKXUniversalProvider } from "@okxconnect/universal-provider";
+import { formatEther } from "ethers/lib/utils";
+import { Transaction } from "ethers/lib/ethers";
+
+export interface IOkx {
+ okxConnect: () => Promise;
+ okxDisconnect(): Promise;
+ okxSetDefaultChainToXterBNB: () => void;
+ okxSetDefaultChainToXterBNBTest: () => void;
+ okxSwitchChain: (chainId: string) => Promise;
+ okxAddXterBNBChain: () => Promise;
+ okxAddXterBNBChainTest: () => Promise;
+ okxGetAddress: () => Promise;
+ okxGetChainId: () => Promise;
+ okxGetBalance: (address: string) => Promise;
+ okxSendTransaction: (tx: Partial, isXterBNBTest?: boolean, chain155?: string) => Promise;
+}
+
+export const useOkx = (): IOkx => {
+ const [okxProvider, setOkxProvider] = useState();
+
+ const DEFAULT_CHAIN = "eip155:1";
+ const XTERBNB_CHAIN = "eip155:112358";
+ const XTERBNB_CHAIN_TEST = "eip155:1637450";
+
+ useEffect(() => {
+ const initProvider = async () => {
+ const provider = await OKXUniversalProvider.init({
+ dappMetaData: {
+ name: "xter",
+ icon: "https://resources.xter.io/ft/aod/roar.png",
+ },
+ });
+ setOkxProvider(provider);
+ };
+ initProvider();
+ }, []);
+
+ useEffect(() => {
+ const displayUriHandler = (uri: string) => {
+ console.log(uri);
+ alert(uri);
+ };
+
+ const sessionUpdateHandler = (session: any) => {
+ console.log(JSON.stringify(session));
+ alert(JSON.stringify(session));
+ };
+
+ const sessionDeleteHandler = ({ topic }: { topic: string }) => {
+ console.log(topic);
+ alert(topic);
+ };
+
+ // 添加事件监听器
+ if (okxProvider) {
+ console.log('event added')
+ okxProvider.events.on("display_uri", displayUriHandler);
+ okxProvider.events.on("session_update", sessionUpdateHandler);
+ okxProvider.events.on("session_delete", sessionDeleteHandler);
+ }
+
+ // 清除事件监听器
+ return () => {
+ if (okxProvider) {
+ okxProvider.events.off("display_uri", displayUriHandler);
+ okxProvider.events.off("session_update", sessionUpdateHandler);
+ okxProvider.events.off("session_delete", sessionDeleteHandler);
+ }
+ };
+ }, [okxProvider]);
+
+ const okxConnect = useCallback(async () => {
+ console.log('okxConnect start');
+ if (okxProvider) {
+ const session = await okxProvider.connect({
+ namespaces: {
+ eip155: {
+ chains: ["eip155:1"],
+ rpcMap: {
+ // Ethereum Mainnet
+ 1: "https://ethereum-rpc.publicnode.com",
+ },
+ defaultChain: "1",
+ },
+ },
+ optionalNamespaces: {
+ eip155: {
+ chains: ["eip155:112358", "eip155:1637450"],
+ rpcMap: {
+ // Xterio Chain (BNB)
+ 112358: "https://xterio-bnb.alt.technology",
+ // Xterio Testnet (BNB)
+ 1637450: 'https://xterio-testnet.alt.technology/'
+ },
+ defaultChain: "112358",
+ },
+ },
+ sessionConfig: {
+ redirect: "tg://resolve",
+ },
+ });
+ console.log('session ==', JSON.stringify(session))
+ // alert(JSON.stringify(session));
+ } else {
+ alert('okxProvider not init');
+ }
+ console.log('okxConnect end');
+ }, [okxProvider]);
+
+ const okxSetDefaultChainToXterBNB = useCallback(() => {
+ console.log('okxSetDefaultChainToXterBNB start');
+ if (okxProvider) {
+ okxProvider.setDefaultChain(
+ "eip155:112358",
+ "https://xterio-bnb.alt.technology"
+ );
+ }
+ // alert(okxProvider?.client.session?.namespaces)
+ console.log('okxSetDefaultChainToXterBNB end');
+
+
+ }, [okxProvider]);
+
+ const okxSetDefaultChainToXterBNBTest = useCallback(() => {
+ console.log('okxSetDefaultChainToXterBNBTest start');
+ if (okxProvider) {
+ okxProvider.setDefaultChain(
+ "eip155:1637450",
+ "https://xterio-testnet.alt.technology/"
+ );
+ }
+ console.log('okxSetDefaultChainToXterBNBTest end');
+ }, [okxProvider]);
+
+ const okxSwitchChain = useCallback(async (chainId: string) => {
+ console.log('okxSwitchChain start');
+ if (okxProvider) {
+ const data = {
+ method: "wallet_switchEthereumChain",
+ params: { chainId },
+ };
+ const switchResult = await okxProvider.request(
+ data,
+ DEFAULT_CHAIN
+ );
+ }
+ console.log('okxSwitchChain end');
+ }, [okxProvider]);
+
+ const okxAddXterBNBChain = useCallback(async () => {
+ alert('okxAddXterBNBChain start')
+ console.log('okxAddXterBNBChain start');
+ if (okxProvider) {
+ const data = {
+ method: "wallet_addEthereumChain",
+ params: {
+ blockExplorerUrls: ["https://bnb.xterscan.io"],
+ chainId: "0x1B6E6", // 112358
+ chainName: "Xter BNB",
+ nativeCurrency: { name: "XTER BNB", symbol: "XBNB", decimals: 18 },
+ rpcUrls: ["https://xterio-bnb.alt.technology"],
+ },
+ };
+ const res = await okxProvider.request(
+ data,
+ DEFAULT_CHAIN
+ );
+ alert(res);
+ }
+ console.log('okxAddXterBNBChain end');
+ }, [okxProvider]);
+
+ const okxAddXterBNBChainTest = useCallback(async () => {
+ console.log('okxAddXterBNBChainTest start');
+ if (okxProvider) {
+ const data = {
+ method: "wallet_addEthereumChain",
+ params: {
+ blockExplorerUrls: ["https://testnet.xterscan.io"],
+ chainId: "0x1B6E6", //1637450
+ chainName: "Xterio Testnet",
+ nativeCurrency: { name: "Test BNB", symbol: "tBNB", decimals: 18 },
+ rpcUrls: ["https://xterio-testnet.alt.technology/"],
+ },
+ };
+ const res = await okxProvider.request(
+ data,
+ DEFAULT_CHAIN
+ );
+ alert(res);
+ }
+ console.log('okxAddXterBNBChainTest end');
+ }, [okxProvider]);
+
+ const okxGetAddress = useCallback(async () => {
+ console.log('okxGetAddress start');
+ if (okxProvider) {
+ const ethRequestAccountsResult = await okxProvider.request({
+ method: "eth_requestAccounts",
+ });
+ console.log('okxGetAddress end');
+ return ethRequestAccountsResult as string
+ }
+ console.log('okxGetAddress end');
+ }, [okxProvider]);
+
+ const okxGetChainId = useCallback(async () => {
+ console.log('okxGetChainId start');
+ if (okxProvider) {
+ const chainIdResult = await okxProvider.request({
+ method: "eth_chainId",
+ });
+ console.log('okxGetChainId end');
+ return chainIdResult as string
+ }
+ console.log('okxGetChainId end');
+ }, [okxProvider]);
+
+ const okxGetBalance = useCallback(async (address: string) => {
+ console.log('okxGetBalance start');
+ if (okxProvider) {
+ const data = {
+ method: "eth_getBalance",
+ params: [address, "latest"],
+ };
+ const getBalanceResult = await okxProvider.request(data);
+ // alert(formatEther(BigInt(getBalanceResult as string).toString()));
+ console.log('okxGetBalance end');
+ return getBalanceResult as string
+ }
+ console.log('okxGetBalance end');
+ }, [okxProvider]);
+
+ const okxDisconnect = useCallback(async () => {
+ console.log('okxDisconnect start');
+ if (okxProvider) {
+ await okxProvider.disconnect();
+ }
+ console.log('okxDisconnect end');
+ }, [okxProvider]);
+
+ const okxSendTransaction = useCallback(async (
+ tx: Partial,
+ isXterBNBTest?: boolean,
+ chain155?: string, // in 'eip155:chainid' format
+ ) => {
+ console.log('okxSendTransaction start');
+ if (okxProvider) {
+ const data = {
+ method: "eth_sendTransaction",
+ params: [tx],
+ };
+ const sendTransactionResult = await okxProvider.request(
+ data,
+ isXterBNBTest ? XTERBNB_CHAIN_TEST : chain155 ?? XTERBNB_CHAIN
+ );
+ console.log('okxSendTransaction end');
+ return sendTransactionResult as string;
+ }
+ console.log('okxSendTransaction end');
+ }, [okxProvider]);
+
+ return {
+ okxConnect,
+ okxDisconnect,
+ okxSetDefaultChainToXterBNB,
+ okxSetDefaultChainToXterBNBTest,
+ okxSwitchChain,
+ okxAddXterBNBChain,
+ okxAddXterBNBChainTest,
+ okxGetAddress,
+ okxGetChainId,
+ okxGetBalance,
+ okxSendTransaction
+ };
+};
\ No newline at end of file
diff --git a/examples/tg-mini-app/src/pages/okx/index.tsx b/examples/tg-mini-app/src/pages/okx/index.tsx
index daaf43c..3b2a99c 100644
--- a/examples/tg-mini-app/src/pages/okx/index.tsx
+++ b/examples/tg-mini-app/src/pages/okx/index.tsx
@@ -4,112 +4,84 @@ import { SvgIcon } from 'src/components/ui'
import { useEffect, useState } from 'react'
import { OKXUniversalProvider } from '@okxconnect/universal-provider'
import { formatEther } from 'ethers/lib/utils'
+import { useOkx } from 'src/contexts/okx'
const Okx = observer(() => {
- const [okxUniversalProvider, setOkxUniversalProvider] = useState()
+ const {
+ okxGetAddress,
+ okxGetChainId,
+ okxConnect,
+ okxDisconnect,
+ okxSetDefaultChainToXterBNB,
+ okxSetDefaultChainToXterBNBTest,
+ okxSendTransaction,
+ okxAddXterBNBChain,
+ okxAddXterBNBChainTest,
+ okxGetBalance // 假设存在这个方法
+ } = useOkx()
const [chainId, setChainId] = useState()
const [address, setAddress] = useState()
const [balance, setBalance] = useState()
- const defaultChain = 'eip155:1'
+ const handleGetAddress = async () => {
+ const address = await okxGetAddress()
+ alert(address)
+ setAddress(address)
+ }
- useEffect(() => {
- const initProvider = async () => {
- const provider = await OKXUniversalProvider.init({
- dappMetaData: {
- name: 'xter',
- icon: 'https://resources.xter.io/ft/aod/roar.png'
- }
- })
- setOkxUniversalProvider(provider)
- }
- initProvider()
- }, [])
+ const handleGetChainId = async () => {
+ const chainId = await okxGetChainId()
+ alert(chainId)
+ setChainId(chainId)
+ }
const handleConnect = async () => {
- if (okxUniversalProvider) {
- var session = await okxUniversalProvider.connect({
- namespaces: {
- eip155: {
- chains: ['eip155:1', 'eip155:137'],
- rpcMap: {
- // Ethereum Mainnet
- 1: 'https://ethereum-rpc.publicnode.com',
- 137: 'https://polygon-bor.publicnode.com'
- },
- defaultChain: '1'
- }
- },
- optionalNamespaces: {
- eip155: {
- chains: ['eip155:112358'],
- rpcMap: {
- // Xterio Chain (BNB)
- 112358: 'https://xterio-bnb.alt.technology'
- },
- defaultChain: '112358'
- }
- },
- sessionConfig: {
- redirect: 'tg://resolve'
- }
- })
- setChainId('1')
- alert(JSON.stringify(session))
- }
+ await okxConnect()
+ handleGetAddress()
+ handleGetChainId()
}
- const getDefaultChainAddress = async () => {
- if (okxUniversalProvider) {
- // okxUniversalProvider.setDefaultChain('eip155:112358', 'https://xterio-bnb.alt.technology')
- const ethRequestAccountsResult = await okxUniversalProvider.request({ method: 'eth_requestAccounts' })
- setAddress(ethRequestAccountsResult as any)
- const chainIdResult = await okxUniversalProvider.request({ method: 'eth_chainId' })
- setChainId(chainIdResult as any)
- }
+ const handleConnectAndAddXterBNBChain = async () => {
+ await okxConnect()
+ // setTimeout(() => {
+ // alert('5s timeout')
+ // }, 5000)
+ // await okxAddXterBNBChain()
}
- const switchChain = async () => {
- if (okxUniversalProvider) {
- const data = { method: 'wallet_switchEthereumChain', params: { chainId: '112358' } }
- const switchResult = await okxUniversalProvider.request(data, defaultChain)
- alert(switchResult ?? 'switchResult is undefined')
- setChainId('112358')
- }
+ const handleDisconnect = async () => {
+ await okxDisconnect()
+ setAddress(undefined)
+ setChainId(undefined)
+ setBalance(undefined)
}
- const addEthereumChain = async () => {
- if (okxUniversalProvider) {
- const data = {
- method: 'wallet_addEthereumChain',
- params: {
- blockExplorerUrls: ['https://bnb.xterscan.io'],
- chainId: '112358',
- chainName: 'Xter BNB',
- nativeCurrency: { name: 'XTER BNB', symbol: 'XBNB', decimals: 18 },
- rpcUrls: ['https://xterio-bnb.alt.technology']
- }
- }
- const addEthereumChainResult = await okxUniversalProvider.request(data, defaultChain)
- alert(addEthereumChainResult)
- }
+ const handleSetDefaultChainToXterBNB = async () => {
+ await okxSetDefaultChainToXterBNB()
+ }
+
+ const handleSetDefaultChainToXterBNBTest = async () => {
+ await okxSetDefaultChainToXterBNBTest()
+ }
+
+ const handleSendTransaction = async () => {
+ // await okxSendTransaction()
+ }
+
+ const handleAddXterBNBChain = async () => {
+ await okxAddXterBNBChain()
}
- const getBalance = async () => {
- if (okxUniversalProvider) {
- if (address) {
- okxUniversalProvider.setDefaultChain('eip155:112358', 'https://xterio-bnb.alt.technology')
+ const handleAddXterBNBChainTest = async () => {
+ await okxAddXterBNBChainTest()
+ }
- const data = { method: 'eth_getBalance', params: ['0x5eac656ceb0330b8f10f616da6cdeddd212682b5', 'latest'] }
- // const data = { method: 'eth_getBalance', params: [address, 'latest'] }
- const getBalanceResult = await okxUniversalProvider.request(data)
- // const getBalanceResult = await okxUniversalProvider.request(data, `eip155:${chainId}`)
- alert(formatEther(BigInt(getBalanceResult as string).toString()))
- setBalance(getBalanceResult as any)
- } else {
- alert('no address')
- }
+ const handleFetchBalance = async () => {
+ if (address) {
+ const currentBalance = await okxGetBalance(address) // 需要实现这个方法
+ alert(formatEther(BigInt(currentBalance as string).toString()))
+ setBalance(formatEther(BigInt(currentBalance as string).toString())) // 格式化余额
}
}
@@ -118,39 +90,40 @@ const Okx = observer(() => {
链ID: {chainId}
地址: {address}
- 余额: {formatEther(BigInt(balance as string).toString())}
+ 余额: {balance}
-
-
-
-
-
{'Connect your okx evm wallet'}
-
-
-
-
-
-
- {/* 添加每个方法对应的点击 div */}
-
-
获取默认链的地址信息
-
-
-
切换链
-
-
-
添加链
-
-
-
获取余额
-
+
+
连接钱包并添加 XterBNB 链
+
+
+
连接钱包
+
+
+
获取地址
+
+
+
获取链ID
+
+
+
断开连接
+
+
+
设置默认链为 XterBNB
+
+
+
设置默认链为 XterBNB 测试
+
+
+
发送交易
+
+
+
添加 XterBNB 链
+
+
+
添加 XterBNB 测试链
+
+
+
获取余额
)
diff --git a/examples/tg-mini-app/src/pages/okx/index.txt b/examples/tg-mini-app/src/pages/okx/index.txt
new file mode 100644
index 0000000..efae15e
--- /dev/null
+++ b/examples/tg-mini-app/src/pages/okx/index.txt
@@ -0,0 +1,159 @@
+import { useBoolean } from 'ahooks'
+import { observer } from 'mobx-react-lite'
+import { SvgIcon } from 'src/components/ui'
+import { useEffect, useState } from 'react'
+import { OKXUniversalProvider } from '@okxconnect/universal-provider'
+import { formatEther } from 'ethers/lib/utils'
+
+const Okx = observer(() => {
+ const [okxUniversalProvider, setOkxUniversalProvider] = useState()
+
+ const [chainId, setChainId] = useState()
+ const [address, setAddress] = useState()
+ const [balance, setBalance] = useState()
+
+ const defaultChain = 'eip155:1'
+
+ useEffect(() => {
+ const initProvider = async () => {
+ const provider = await OKXUniversalProvider.init({
+ dappMetaData: {
+ name: 'xter',
+ icon: 'https://resources.xter.io/ft/aod/roar.png'
+ }
+ })
+ setOkxUniversalProvider(provider)
+ }
+ initProvider()
+ }, [])
+
+ const handleConnect = async () => {
+ if (okxUniversalProvider) {
+ var session = await okxUniversalProvider.connect({
+ namespaces: {
+ eip155: {
+ chains: ['eip155:1', 'eip155:137'],
+ rpcMap: {
+ // Ethereum Mainnet
+ 1: 'https://ethereum-rpc.publicnode.com',
+ 137: 'https://polygon-bor.publicnode.com'
+ },
+ defaultChain: '1'
+ }
+ },
+ optionalNamespaces: {
+ eip155: {
+ chains: ['eip155:112358'],
+ rpcMap: {
+ // Xterio Chain (BNB)
+ 112358: 'https://xterio-bnb.alt.technology'
+ },
+ defaultChain: '112358'
+ }
+ },
+ sessionConfig: {
+ redirect: 'tg://resolve'
+ }
+ })
+ setChainId('1')
+ alert(JSON.stringify(session))
+ }
+ }
+
+ const getDefaultChainAddress = async () => {
+ if (okxUniversalProvider) {
+ // okxUniversalProvider.setDefaultChain('eip155:112358', 'https://xterio-bnb.alt.technology')
+ const ethRequestAccountsResult = await okxUniversalProvider.request({ method: 'eth_requestAccounts' })
+ setAddress(ethRequestAccountsResult as any)
+ const chainIdResult = await okxUniversalProvider.request({ method: 'eth_chainId' })
+ setChainId(chainIdResult as any)
+ }
+ }
+
+ const switchChain = async () => {
+ if (okxUniversalProvider) {
+ const data = { method: 'wallet_switchEthereumChain', params: { chainId: '112358' } }
+ const switchResult = await okxUniversalProvider.request(data, defaultChain)
+ alert(switchResult ?? 'switchResult is undefined')
+ setChainId('112358')
+ }
+ }
+
+ const addEthereumChain = async () => {
+ if (okxUniversalProvider) {
+ const data = {
+ method: 'wallet_addEthereumChain',
+ params: {
+ blockExplorerUrls: ['https://bnb.xterscan.io'],
+ chainId: '112358',
+ chainName: 'Xter BNB',
+ nativeCurrency: { name: 'XTER BNB', symbol: 'XBNB', decimals: 18 },
+ rpcUrls: ['https://xterio-bnb.alt.technology']
+ }
+ }
+ const addEthereumChainResult = await okxUniversalProvider.request(data, defaultChain)
+ alert(addEthereumChainResult)
+ }
+ }
+
+ const getBalance = async () => {
+ if (okxUniversalProvider) {
+ if (address) {
+ okxUniversalProvider.setDefaultChain('eip155:112358', 'https://xterio-bnb.alt.technology')
+
+ const data = { method: 'eth_getBalance', params: ['0x5eac656ceb0330b8f10f616da6cdeddd212682b5', 'latest'] }
+ // const data = { method: 'eth_getBalance', params: [address, 'latest'] }
+ const getBalanceResult = await okxUniversalProvider.request(data)
+ // const getBalanceResult = await okxUniversalProvider.request(data, `eip155:${chainId}`)
+ alert(formatEther(BigInt(getBalanceResult as string).toString()))
+ setBalance(getBalanceResult as any)
+ } else {
+ alert('no address')
+ }
+ }
+ }
+
+ return (
+
+
+
链ID: {chainId}
+ 地址: {address}
+ 余额: {balance}
+
+
+
+
+
+
{'Connect your okx evm wallet'}
+
+
+
+
+
+
+ {/* 添加每个方法对应的点击 div */}
+
+
获取默认链的地址信息
+
+
+
切换链
+
+
+
添加链
+
+
+
获取余额
+
+
+
+ )
+})
+
+export default Okx