-
Notifications
You must be signed in to change notification settings - Fork 524
Expand file tree
/
Copy pathuse-smart-account-fee.ts
More file actions
156 lines (136 loc) · 4.4 KB
/
use-smart-account-fee.ts
File metadata and controls
156 lines (136 loc) · 4.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { useCallback, useEffect, useMemo, useState } from "react";
import {
ALLOWED_DELEGATORS,
buildDummyAuthorizationList,
} from "@keplr-wallet/background";
import { computeEIP1559TxFees } from "@keplr-wallet/hooks-evm";
import { CoinPretty, Dec, Int } from "@keplr-wallet/unit";
import { useStore } from "../../../../../stores";
import { formatFee } from "../../utils";
type FeeState =
| { status: "loading" }
| { status: "success"; gasUsed: number }
| { status: "error" };
export function useSmartAccountFee(
chainId: string,
hexAddress: string,
isValid: boolean
) {
const { chainStore, queriesStore, priceStore, ethereumAccountStore } =
useStore();
const nativeCurrency = useMemo(() => {
try {
const unwrapped = chainStore.getModularChain(chainId).unwrapped;
if (unwrapped.type === "evm") return unwrapped.evm.nativeCurrency;
if (unwrapped.type === "ethermint") return unwrapped.evm.nativeCurrency;
return undefined;
} catch {
return undefined;
}
}, [chainStore, chainId]);
const evmChainId = useMemo(() => {
try {
const unwrapped = chainStore.getModularChain(chainId).unwrapped;
if (unwrapped.type === "evm") return unwrapped.evm.chainId;
if (unwrapped.type === "ethermint") return unwrapped.evm.chainId;
return 0;
} catch {
return 0;
}
}, [chainStore, chainId]);
const nativeSymbol = nativeCurrency?.coinDenom ?? "ETH";
const [feeState, setFeeState] = useState<FeeState>({ status: "loading" });
const [retryCount, setRetryCount] = useState(0);
useEffect(() => {
if (!isValid || !hexAddress || !evmChainId) return;
let cancelled = false;
setFeeState({ status: "loading" });
const ethereumAccount = ethereumAccountStore.getAccount(chainId);
ethereumAccount
.simulateGas(hexAddress, {
to: hexAddress,
value: "0x0",
data: "0x",
authorizationList: buildDummyAuthorizationList(
ALLOWED_DELEGATORS[0],
evmChainId
),
})
.then((result) => {
if (!cancelled) {
setFeeState({ status: "success", gasUsed: result.gasUsed });
}
})
.catch(() => {
if (!cancelled) setFeeState({ status: "error" });
});
return () => {
cancelled = true;
};
}, [
chainId,
hexAddress,
evmChainId,
isValid,
retryCount,
ethereumAccountStore,
]);
// Fee from reactive queries (feeHistory percentile + baseFee margin, fillUnsignedEVMTx와 동일 로직)
const ethereumQueries = queriesStore.get(chainId).ethereum;
const txFees = ethereumQueries
? computeEIP1559TxFees(ethereumQueries, "average", chainId)
: undefined;
const estimatedFeeWei = useMemo(() => {
if (feeState.status !== "success") return null;
const feePerGas = txFees?.maxFeePerGas ?? txFees?.gasPrice;
if (!feePerGas || feePerGas.isZero()) return null;
const gasLimit = Math.ceil(feeState.gasUsed * 1.3);
const fee = feePerGas.mul(new Dec(gasLimit)).truncate();
return "0x" + BigInt(fee.toString()).toString(16);
}, [feeState, txFees]);
const isEstimating = feeState.status === "loading";
const isFailed = feeState.status === "error";
const feeDisplay = useMemo(
() => (estimatedFeeWei ? formatFee(estimatedFeeWei, nativeSymbol) : null),
[estimatedFeeWei, nativeSymbol]
);
const feeUsd = useMemo(() => {
if (!estimatedFeeWei || !nativeCurrency) return null;
try {
const feeCoin = new CoinPretty(
nativeCurrency,
new Int(BigInt(estimatedFeeWei).toString())
);
const price = priceStore.calculatePrice(feeCoin);
return price ? price.toString() : null;
} catch {
return null;
}
}, [estimatedFeeWei, nativeCurrency, priceStore]);
const balance =
nativeCurrency && hexAddress
? queriesStore
.get(chainId)
.queryBalances.getQueryEthereumHexAddress(hexAddress)
.getBalance(nativeCurrency)
: undefined;
const balanceLoaded = !!balance?.response;
const insufficientBalance =
balance && balanceLoaded && estimatedFeeWei
? new Int(balance.balance.toCoin().amount).lt(
new Int(BigInt(estimatedFeeWei).toString())
)
: false;
const retry = useCallback(() => {
setRetryCount((prev) => prev + 1);
}, []);
return {
feeDisplay,
feeUsd,
isEstimating,
isFailed,
insufficientBalance,
balanceLoaded,
retry,
};
}