import { ChainGrpcWasmApi, getInjectiveAddress } from "@injectivelabs/sdk-ts";
import { Network, getNetworkEndpoints } from "@injectivelabs/networks";
import { WalletStrategy } from "@injectivelabs/wallet-strategy";
import { Web3Exception } from "@injectivelabs/exceptions";
// These imports are from .env
import {
CHAIN_ID,
ETHEREUM_CHAIN_ID,
IS_TESTNET,
alchemyRpcEndpoint,
alchemyWsRpcEndpoint,
} from "/constants";
const NETWORK = Network.Testnet;
const ENDPOINTS = getNetworkEndpoints(NETWORK);
const chainGrpcWasmApi = new ChainGrpcWasmApi(ENDPOINTS.grpc);
const walletStrategy = new WalletStrategy({
chainId: CHAIN_ID,
ethereumOptions: {
ethereumChainId: ETHEREUM_CHAIN_ID,
rpcUrl: alchemyRpcEndpoint,
},
});
export const getAddresses = async (): Promise<string[]> => {
const addresses = await walletStrategy.getAddresses();
if (addresses.length === 0) {
throw new Web3Exception(
new Error("There are no addresses linked in this wallet.")
);
}
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, // The address of the contract
toBase64({ get_count: {} }) // We need to convert our query to Base64
)) as { data: string };
const { count } = fromBase64(response.data) as { count: number }; // we need to convert the response from Base64
console.log(count)
}
async function increment(){
const msg = MsgExecuteContractCompat.fromJSON({
contractAddress: COUNTER_CONTRACT_ADDRESS,
sender: injectiveAddress,
msg: {
increment: {},
},
});
// Signing and broadcasting the message
await msgBroadcastClient.broadcast({
msgs: msg,
injectiveAddress: injectiveAddress,
});
}
async function main() {
await fetchCount() // this will log: {count: 5}
await increment() // this opens up your wallet to sign the transaction and broadcast it
await fetchCount() // the count now is 6. log: {count: 6}
}
main()