Last active
December 25, 2022 13:47
-
-
Save 0x8f701/739c665a0c0bdaa5f05b76f501a7e377 to your computer and use it in GitHub Desktop.
cosmjs-homework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
assertIsDeliverTxSuccess, | |
SigningStargateClient, | |
} from '@cosmjs/stargate' | |
import type { ChainInfo } from '@keplr-wallet/types' | |
import React, { useEffect, useState } from 'react' | |
import osmo from '../config/osmosis' | |
function Keplr() { | |
const [chain, setChain] = useState<ChainInfo>(osmo) | |
const [selected, setSelected] = useState<string>('OSMO') | |
const [client, setClient] = useState<any>() | |
const [address, setAddress] = useState<any>() | |
const [balance, setBalance] = useState<any>() | |
const [recipent, setRecipent] = useState<any>( | |
'osmo1r9ufesd4ja09g4rcxxetpx675eu09m45q05wv7' | |
) | |
const [tx, setTx] = useState<any>() | |
const [sendHash, setSendHash] = useState<any>() | |
const [txRes, setTxRes] = useState<any>() | |
// 初始化 chain | |
useEffect(() => { | |
connectWallet() | |
}, [chain]) | |
// 查余额 | |
useEffect(() => { | |
if (!address && !client) return | |
getBalances() | |
}, [address, client, sendHash]) | |
// 连接keplr钱包 Todo | |
const connectWallet = async () => { | |
if (!window.keplr || !window.getOfflineSigner) { | |
console.log(1) | |
return | |
} | |
await window.keplr.experimentalSuggestChain(chain) | |
await window.keplr.enable(chain.chainId) | |
const offlineSigner = window.keplr.getOfflineSigner(chain.chainId) | |
const accounts = await offlineSigner.getAccounts() | |
const client = await SigningStargateClient.connectWithSigner( | |
chain.rpc, | |
offlineSigner | |
) | |
setAddress(accounts[0].address) | |
setClient(client) | |
} | |
// 余额查询 Todo | |
const getBalances = async () => { | |
const balance = await client.getBalance(address, 'osmo') | |
setBalance(balance) | |
} | |
// txhash查询 Todo | |
const getTx = async () => { | |
if (!tx) return | |
const result = await client.getTx(tx) | |
setTxRes(result) | |
} | |
// 转账 Todo | |
const sendToken = async () => { | |
const amount = { | |
denom: 'osmo', | |
amount: '10000000', | |
} | |
const fee = { | |
amount: [ | |
{ | |
denom: 'osmo', | |
amount: 0.025, | |
}, | |
], | |
gas: '200000', | |
} | |
try { | |
const result = await client.sendTokens(address, recipent, amount, fee, '') | |
assertIsDeliverTxSuccess(result) | |
if (result.code == 0) { | |
setTx(result.transactionHash) | |
} | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
return ( | |
<div className="keplr"> | |
<h2>Keplr Wallet</h2> | |
<label> | |
<span> | |
Chain: | |
<select | |
className="select" | |
value={selected} | |
onChange={(e) => setSelected(e.target.value)} | |
> | |
<option value="OSMO">OSMO</option> | |
<option value="SPX">SPX</option> | |
</select> | |
</span>{' '} | |
| |
<button onClick={connectWallet}> | |
{address ? '已连接' : '连接keplr'} | |
</button> | |
</label> | |
<div className="weight">地址:{address}</div> | |
<div className="weight"> | |
<span style={{ whiteSpace: 'nowrap' }}>余额: </span> | |
<div> | |
{balance?.amount && ( | |
<> | |
<span> | |
{parseFloat( | |
String(Number(balance?.amount) / Math.pow(10, 6)) | |
).toFixed(2)} | |
</span> | |
<span> {balance?.denom}</span> | |
</> | |
)} | |
</div> | |
</div> | |
<hr /> | |
<label>1、sendTokens() & broadcastTx</label> | |
<div> | |
<input | |
type="text" | |
value={recipent} | |
placeholder="address" | |
style={{ width: '350px' }} | |
onChange={(e) => setRecipent(e.target.value)} | |
/> | |
| |
<button onClick={sendToken}> | |
发送 10 {chain.feeCurrencies[0].coinMinimalDenom} | |
</button> | |
</div> | |
<label>2、getTx()</label> | |
<div> | |
<input value={tx} readOnly style={{ width: '350px' }} /> | |
| |
<button onClick={getTx}>查询</button> | |
</div> | |
<div className="tx"> | |
{txRes && ( | |
<> | |
<div>height:{txRes?.height} </div> | |
<div>gasUsed:{txRes?.gasUsed} </div> | |
<div>gasWanted:{txRes?.gasWanted} </div> | |
</> | |
)} | |
</div> | |
</div> | |
) | |
} | |
export default Keplr |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing' | |
import { | |
Account, | |
Block, | |
Coin, | |
SequenceResponse, | |
StargateClient, | |
} from '@cosmjs/stargate' | |
import React, { useEffect, useState } from 'react' | |
import chain from '../config/osmosis' | |
import { useInterval } from '../Hooks/useInterval' | |
function Stargate() { | |
const [mnemonic, setMnemonic] = useState<string>( | |
localStorage.getItem('mnemonic') | |
) | |
const [address, setAddress] = useState<string | null>(null) | |
const [balance, setBalance] = useState<Coin>() | |
const [allBalance, setAllBalances] = useState<Coin[]>() | |
const [client, setClient] = useState<StargateClient | null>(null) | |
const [height, setHeight] = useState<number>() | |
const [chainId, setChainId] = useState<string>() | |
const [account, setAccount] = useState<Account>() | |
const [block, setBlock] = useState<Block>() | |
const [sequence, setSequence] = useState<SequenceResponse>() | |
const [timestamp, setTimestamp] = useState(0) | |
useInterval(() => setTimestamp(new Date().getTime()), 1000) | |
// 连接 | |
useEffect(() => { | |
if (!chain) return | |
connect() | |
}, [chain]) | |
useEffect(() => { | |
if (!mnemonic) return | |
getAddressByMnemonic() | |
}, [mnemonic]) | |
// 余额查询 | |
useEffect(() => { | |
if (!address || !client) return | |
getBalance() | |
}, [timestamp, address, client]) | |
// 实现stargate基础api | |
useEffect(() => { | |
if (!address || !client) return | |
getOthers() | |
}, [address, client]) | |
// 创建账户 Todo | |
const createAccount = async () => { | |
const wallet = await DirectSecp256k1HdWallet.generate(12, { | |
prefix: 'osmo', | |
}) | |
const [firstAccount] = await wallet.getAccounts() | |
setAddress(firstAccount.address) | |
setMnemonic(wallet.mnemonic) | |
localStorage.setItem('mnemonic', wallet.mnemonic) | |
} | |
// 通过助记词钱包获得地址 Todo | |
const getAddressByMnemonic = async () => { | |
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { | |
prefix: 'osmo', | |
}) | |
const [firstAccount] = await wallet.getAccounts() | |
setAddress(firstAccount.address) | |
} | |
// 余额查询 Todo | |
const getBalance = async () => { | |
const balance = await client.getBalance(address, 'osmo') | |
setBalance(balance) | |
} | |
// strageClient 基础 api 使用 Todo | |
const getOthers = async () => { | |
const chainId = await client.getChainId() | |
const height = await client.getHeight() | |
const block = await client.getBlock() | |
setChainId(chainId) | |
setHeight(height) | |
setBlock(block) | |
try { | |
const sequence = await client.getSequence(address) | |
const account = await client.getAccount(address) | |
const allBalances = await client.getAllBalances(address) | |
setSequence(sequence) | |
setAccount(account) | |
setAllBalances(allBalances as any) | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
// connect client Todo | |
const connect = async () => { | |
const client = await StargateClient.connect(chain.rpc) | |
setClient(client) | |
if (!mnemonic) return | |
await getAddressByMnemonic() | |
} | |
// disconnect client Todo | |
const disConnect = async () => { | |
client.disconnect() | |
setClient(null) | |
setAddress(null) | |
} | |
return ( | |
<div className="stargate"> | |
<h2>StargateClient</h2> | |
<label> | |
<span>Chain: Osmosis </span> | |
<button onClick={client ? disConnect : connect}> | |
{client ? '断开' : '连接'} | |
</button> | |
</label> | |
<div className="weight"> | |
<span> | |
助记词: | |
<input | |
type="text" | |
value={mnemonic} | |
placeholder="mnemonic" | |
style={{ width: '400px' }} | |
onChange={(e) => setMnemonic(e.target.value.trim())} | |
/> | |
<button onClick={createAccount}>创建账户</button> | |
</span> | |
| |
</div> | |
<div className="weight"> | |
<span style={{ whiteSpace: 'nowrap' }}>余额: </span> | |
{balance?.amount && ( | |
<> | |
<span> | |
{parseFloat( | |
String(Number(balance?.amount) / Math.pow(10, 6)) | |
).toFixed(2)} | |
</span> | |
<span>{balance?.denom}</span> | |
</> | |
)} | |
</div> | |
<hr /> | |
<label>1、水龙头</label> | |
<div> | |
<span> | |
Address: <b>{address}</b> | |
</span> | |
| |
{address && ( | |
<a href="https://faucet.osmosis.zone/" target="_blank"> | |
获取 | |
</a> | |
)} | |
</div> | |
<label>2、getChainId()</label> | |
<div> | |
<span>ChainId: {chainId} </span> | |
</div> | |
<label>3、getBalance()</label> | |
<div> | |
<span>Balance: </span> | |
{balance?.amount && ( | |
<> | |
<span> | |
{parseFloat( | |
String(Number(balance?.amount) / Math.pow(10, 6)) | |
).toFixed(2)} | |
</span> | |
<span> {balance?.denom}</span> | |
</> | |
)} | |
</div> | |
<label>4、getAccount()</label> | |
<div> | |
<div>address: {account?.address}</div> | |
<div>accountNumber: {account?.accountNumber}</div> | |
<div>sequence: {account?.sequence}</div> | |
</div> | |
<label>5、getHeight()</label> | |
<div>Height: {height}</div> | |
<label>6、getBlock()</label> | |
<div>Blockhash:{block?.id}</div> | |
<label>7、getAllBalances()</label> | |
<div> | |
{allBalance?.map((item) => { | |
return ( | |
<div className="ell" key={item.denom}> | |
{parseFloat( | |
String(Number(item?.amount) / Math.pow(10, 6)) | |
).toFixed(2)} | |
| |
{item?.denom} | |
</div> | |
) | |
})} | |
</div> | |
<label>8、getSequence()</label> | |
<div> | |
<div>accountNumber :{sequence?.accountNumber}</div> | |
<div>sequence :{sequence?.sequence}</div> | |
</div> | |
{/* <label>9、getQueryClient()</label> | |
<div>queryClient: {JSON.stringify(queryAccount?.toString())}</div> */} | |
</div> | |
) | |
} | |
export default Stargate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment