Skip to content

Commit

Permalink
restore signAndBroadcast; introduce gasPrice param in provider; comme…
Browse files Browse the repository at this point in the history
…nts on setting fee in demo app
  • Loading branch information
BurntVal committed Oct 11, 2024
1 parent 67e5152 commit 7db321c
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 75 deletions.
1 change: 1 addition & 0 deletions apps/demo-app/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const legacyConfig = {

const treasuryConfig = {
treasury: "xion1h82c0efsxxq4pgua754u6xepfu6avglup20fl834gc2ah0ptgn5s2zffe9", // Example XION treasury contract with /cosmwasm.wasm.v1.MsgExecuteContract grant
// gasPrice: "0uxion", // This defaults to "0uxion" on testnet and "0.025uxion" on mainnet. If you feel the need to change the gasPrice when connecting to signer, set this value. Please stick to the string format seen in example
// Optional params to activate mainnet config
// rpcUrl: "https://rpc.xion-mainnet-1.burnt.com:443",
// restUrl: "https://api.xion-mainnet-1.burnt.com:443",
Expand Down
39 changes: 17 additions & 22 deletions apps/demo-app/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import {
} from "@burnt-labs/abstraxion";
import { Button } from "@burnt-labs/ui";
import "@burnt-labs/ui/dist/index.css";
import type { DeliverTxResponse } from "@cosmjs/cosmwasm-stargate";
import type { ExecuteResult } from "@cosmjs/cosmwasm-stargate";
import { SignArb } from "../components/sign-arb.tsx";

const seatContractAddress =
"xion1z70cvc08qv5764zeg3dykcyymj5z6nu4sqr7x8vl4zjef2gyp69s9mmdka";

type ExecuteResultOrUndefined = ExecuteResult | undefined;

export default function Page(): JSX.Element {
// Abstraxion hooks
const { data: account } = useAbstraxionAccount();
Expand All @@ -26,9 +28,8 @@ export default function Page(): JSX.Element {
React.Dispatch<React.SetStateAction<boolean>>,
] = useModal();
const [loading, setLoading] = useState(false);
const [executeResult, setExecuteResult] = useState<
DeliverTxResponse | undefined
>(undefined);
const [executeResult, setExecuteResult] =
useState<ExecuteResultOrUndefined>(undefined);

const blockExplorerUrl = `https://explorer.burnt.com/xion-testnet-1/tx/${executeResult?.transactionHash}`;

Expand Down Expand Up @@ -57,29 +58,23 @@ export default function Page(): JSX.Element {
};

try {
const msgSerialized = new TextEncoder().encode(JSON.stringify(msg));
const msgExecuteContract = {
typeUrl: "/cosmwasm.wasm.v1.MsgExecuteContract",
value: {
sender: account.bech32Address,
contract: seatContractAddress,
msg: msgSerialized,
funds: [],
},
};

const claimRes = await client?.signAndBroadcast(account.bech32Address, [
msgExecuteContract,
]);
// Use "auto" fee for most transactions
const claimRes = await client?.execute(
account.bech32Address,
seatContractAddress,
msg,
"auto",
);

// OR
// Default cosmsjs gas multiplier for simulation is 1.4
// If you're finding that transactions are undersimulating, you can bump up the gas multiplier by setting fee to a number, ex. 1.5
// Fee amounts shouldn't stray too far away from the defaults
// Example:
// const claimRes = await client?.execute(
// account.bech32Address,
// seatContractAddress,
// msg,
// "auto",
// "",
// [],
// 1.5,
// );

setExecuteResult(claimRes);
Expand Down
53 changes: 4 additions & 49 deletions packages/abstraxion-core/src/GranteeSignerClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,15 @@ import {
EncodeObject,
OfflineSigner,
} from "@cosmjs/proto-signing";
import {
calculateFee,
GasPrice,
type Account,
type SignerData,
type StdFee,
} from "@cosmjs/stargate";
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import type { Account, SignerData, StdFee } from "@cosmjs/stargate";
import type { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";
import { MsgExec } from "cosmjs-types/cosmos/authz/v1beta1/tx";
import {
HttpEndpoint,
Tendermint37Client,
TendermintClient,
} from "@cosmjs/tendermint-rpc";
import { customAccountFromAny } from "@burnt-labs/signers";
import { xionGasValues } from "@burnt-labs/constants";

interface GranteeSignerOptions {
readonly granterAddress: string;
Expand Down Expand Up @@ -100,7 +93,7 @@ export class GranteeSignerClient extends SigningCosmWasmClient {
public async signAndBroadcast(
signerAddress: string,
messages: readonly EncodeObject[],
fee: StdFee | "auto" | number = "auto",
fee: StdFee | "auto" | number,
memo = "",
): Promise<DeliverTxResponse> {
// Figure out if the signerAddress is a granter
Expand All @@ -118,45 +111,7 @@ export class GranteeSignerClient extends SigningCosmWasmClient {
];
}

let usedFee: StdFee;
const {
gasPrice: gasPriceString,
gasAdjustment,
gasAdjustmentMargin,
} = xionGasValues;
if (fee == "auto" || typeof fee === "number") {
const gasEstimation = await this.simulate(signerAddress, messages, memo);
const multiplier = typeof fee == "number" ? fee : gasAdjustment;
const gasPrice = GasPrice.fromString(gasPriceString);
// usedFee = calculateFee(Math.round(gasEstimation * multiplier), gasPrice);
const calculatedFee = calculateFee(gasEstimation, gasPrice);
let gas = Math.ceil(
parseInt(calculatedFee.gas) * multiplier + gasAdjustmentMargin,
).toString();

const chainId = await this.getChainId();
if (/testnet/.test(chainId)) {
usedFee = { amount: [{ amount: "0", denom: "uxion" }], gas };
} else {
usedFee = { amount: calculatedFee.amount, gas };
}
} else {
usedFee = fee;
}

const txRaw = await this.sign(
signerAddress,
messages,
usedFee,
memo,
undefined,
);
const txBytes = TxRaw.encode(txRaw).finish();
return this.broadcastTx(
txBytes,
this.broadcastTimeoutMs,
this.broadcastPollIntervalMs,
);
return super.signAndBroadcast(signerAddress, messages, fee, memo);
}

public async sign(
Expand Down
2 changes: 2 additions & 0 deletions packages/abstraxion/src/components/Abstraxion/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export interface AbstraxionConfig {
bank?: SpendLimit[];
callbackUrl?: string;
treasury?: string;
gasPrice?: string;
}

export function AbstraxionProvider({
Expand All @@ -87,6 +88,7 @@ export function AbstraxionProvider({
bank={config.bank}
callbackUrl={config.callbackUrl}
treasury={config.treasury}
gasPrice={config.gasPrice}
>
{children}
</AbstraxionContextProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export interface AbstraxionContextProps {
stake?: boolean;
bank?: SpendLimit[];
treasury?: string;
gasPrice?: string;
logout: () => void;
}

Expand All @@ -50,6 +51,7 @@ export function AbstraxionContextProvider({
bank,
callbackUrl,
treasury,
gasPrice,
}: {
children: ReactNode;
contracts?: ContractGrantDescription[];
Expand All @@ -60,6 +62,7 @@ export function AbstraxionContextProvider({
bank?: SpendLimit[];
callbackUrl?: string;
treasury?: string;
gasPrice?: string;
}): JSX.Element {
const [abstraxionError, setAbstraxionError] = useState("");
const [isConnected, setIsConnected] = useState(false);
Expand Down Expand Up @@ -160,6 +163,7 @@ export function AbstraxionContextProvider({
bank,
treasury,
logout,
gasPrice,
}}
>
{children}
Expand Down
24 changes: 20 additions & 4 deletions packages/abstraxion/src/hooks/useAbstraxionSigningClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useContext, useEffect, useState } from "react";
import { testnetChainInfo } from "@burnt-labs/constants";
import { testnetChainInfo, xionGasValues } from "@burnt-labs/constants";
import { GasPrice } from "@cosmjs/stargate";
import {
GranteeSignerClient,
Expand All @@ -15,8 +15,14 @@ export const useAbstraxionSigningClient = (): {
| undefined;
readonly logout: (() => void) | undefined;
} => {
const { isConnected, abstraxionAccount, granterAddress, rpcUrl, logout } =
useContext(AbstraxionContext);
const {
isConnected,
abstraxionAccount,
granterAddress,
rpcUrl,
logout,
gasPrice,
} = useContext(AbstraxionContext);
const [signArbWallet, setSignArbWallet] = useState<
SignArbSecp256k1HdWallet | undefined
>(undefined);
Expand Down Expand Up @@ -45,12 +51,22 @@ export const useAbstraxionSigningClient = (): {
return accounts[0].address;
});

let gasPriceDefault: GasPrice;
const { gasPrice: gasPriceConstant } = xionGasValues;
if (rpcUrl.includes("mainnet")) {
gasPriceDefault = GasPrice.fromString(gasPriceConstant);
} else {
gasPriceDefault = GasPrice.fromString("0uxion");
}

const directClient = await GranteeSignerClient.connectWithSigner(
// Should be set in the context but defaulting here just in case
rpcUrl || testnetChainInfo.rpc,
abstraxionAccount,
{
gasPrice: GasPrice.fromString("0uxion"),
gasPrice: gasPrice
? GasPrice.fromString(gasPrice)
: gasPriceDefault,
granterAddress,
granteeAddress,
},
Expand Down

0 comments on commit 7db321c

Please sign in to comment.