import { Web3Exception } from "@injectivelabs/exceptions"
import { WalletStrategy } from "@injectivelabs/wallet-strategy"
import { ChainGrpcWasmApi } from "@injectivelabs/sdk-ts/client/wasm"
import { Network, getNetworkEndpoints } from "@injectivelabs/networks"
import { getInjectiveAddress } from "@injectivelabs/sdk-ts/utils"
const chainId = ChainId.Testnet // Injective 测试网 Chain ID
const evmChainId = EvmChainId.TestnetEvm // Injective Evm 测试网 Chain ID
export const evmRpcEndpoint = `https://eth-sepolia.g.alchemy.com/v2/${process.env.APP_EVM_RPC_KEY}`
const NETWORK = Network.Testnet
const ENDPOINTS = getNetworkEndpoints(NETWORK)
const chainGrpcWasmApi = new ChainGrpcWasmApi(ENDPOINTS.grpc)
export const walletStrategy = new WalletStrategy({
chainId,
evmOptions: {
evmChainId,
rpcUrl: evmRpcEndpoint,
},
})
export const getAddresses = async (): Promise<string[]> => {
const addresses = await walletStrategy.getAddresses()
if (addresses.length === 0) {
throw new Web3Exception(
new Error("此钱包中没有链接的地址。")
)
}
return addresses
}
const msgBroadcastClient = new MsgBroadcaster({
walletStrategy,
network: NETWORK,
})
const [address] = await getAddresses()
const injectiveAddress = getInjectiveAddress(getInjectiveAddress)
async function fetchCount() {
const response = (await chainGrpcWasmApi.fetchSmartContractState(
COUNTER_CONTRACT_ADDRESS, // 合约地址
toBase64({ get_count: {} }) // 我们需要将查询转换为 Base64
)) as { data: string }
const { count } = fromBase64(response.data) as { count: number } // 我们需要将响应从 Base64 转换
console.log(count)
}
async function increment(){
const msg = MsgExecuteContractCompat.fromJSON({
contractAddress: COUNTER_CONTRACT_ADDRESS,
sender: injectiveAddress,
msg: {
increment: {},
},
})
// 签名和广播消息
await msgBroadcastClient.broadcast({
msgs: msg,
injectiveAddress: injectiveAddress,
})
}
async function main() {
await fetchCount() // 这将记录: {count: 5}
await increment() // 这会打开你的钱包以签名交易并广播它
await fetchCount() // 计数现在是 6。记录: {count: 6}
}
main()