@skip-go/client 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ import { getCosmosGasAmountForMessage } from './chunk-TV2XPAIF.js';
2
+ import { BigNumber } from './chunk-VQ5SIQWU.js';
3
+ import { getSigningStargateClient } from './chunk-72PK3PKI.js';
4
+ import { ClientState, balances } from './chunk-4XUWIG3Z.js';
5
+ import { GasPrice, calculateFee } from '@cosmjs/stargate';
6
+ import { Decimal } from '@cosmjs/math';
7
+
8
+ var validateCosmosGasBalance = async ({
9
+ chainId,
10
+ signerAddress,
11
+ messages,
12
+ getFallbackGasAmount,
13
+ getOfflineSigner,
14
+ txIndex,
15
+ simulate,
16
+ getCosmosPriorityFeeDenom
17
+ }) => {
18
+ const skipAssets = (await ClientState.getSkipAssets({ chainId }))?.[chainId];
19
+ const skipChains = await ClientState.getSkipChains();
20
+ const prioFeeDenom = await getCosmosPriorityFeeDenom?.(chainId);
21
+ const chain = skipChains?.find((c) => c.chainId === chainId);
22
+ if (!chain) {
23
+ throw new Error(`failed to find chain id '${chainId}'`);
24
+ }
25
+ const { feeAssets } = chain;
26
+ if (!feeAssets) {
27
+ throw new Error(`failed to find fee assets for chain id '${chainId}'`);
28
+ }
29
+ const estimatedGasAmount = await (async () => {
30
+ try {
31
+ if (!simulate) throw new Error("simulate");
32
+ if (txIndex !== 0 && chainId === "noble-1") {
33
+ return "0";
34
+ }
35
+ const { stargateClient } = await getSigningStargateClient({
36
+ chainId,
37
+ getOfflineSigner
38
+ });
39
+ const estimatedGas = await getCosmosGasAmountForMessage(
40
+ stargateClient,
41
+ signerAddress,
42
+ chainId,
43
+ messages
44
+ );
45
+ return estimatedGas;
46
+ } catch (e) {
47
+ const error = e;
48
+ if (error.message === "simulate" && !getFallbackGasAmount) {
49
+ throw new Error(`unable to get gas amount for ${chainId}'s message(s)`);
50
+ }
51
+ if (getFallbackGasAmount) {
52
+ const fallbackGasAmount = await getFallbackGasAmount(
53
+ chainId,
54
+ "cosmos" /* Cosmos */
55
+ );
56
+ if (!fallbackGasAmount) {
57
+ throw new Error(`unable to estimate gas for message(s) ${messages}`);
58
+ }
59
+ return String(fallbackGasAmount);
60
+ }
61
+ throw error;
62
+ }
63
+ })();
64
+ const fees = feeAssets.map((asset) => {
65
+ const gasPrice = (() => {
66
+ if (!asset?.gasPrice) return void 0;
67
+ let price = asset.gasPrice.average;
68
+ if (price === "") {
69
+ price = asset.gasPrice.high;
70
+ }
71
+ if (price === "") {
72
+ price = asset.gasPrice.low;
73
+ }
74
+ if (!price) return;
75
+ return new GasPrice(
76
+ Decimal.fromUserInput(BigNumber(price).toFixed(), 18),
77
+ asset?.denom ?? ""
78
+ );
79
+ })();
80
+ if (!gasPrice) {
81
+ return null;
82
+ }
83
+ if (chainId === "noble-1") {
84
+ if (asset.denom.toLowerCase() === "ibc/EF48E6B1A1A19F47ECAEA62F5670C37C0580E86A9E88498B7E393EB6F49F33C0".toLowerCase()) {
85
+ const fee2 = calculateFee(2e6, gasPrice);
86
+ return fee2;
87
+ }
88
+ const fee = calculateFee(2e5, gasPrice);
89
+ return fee;
90
+ }
91
+ return calculateFee(Math.ceil(parseFloat(estimatedGasAmount)), gasPrice);
92
+ });
93
+ const feeBalance = await balances({
94
+ chains: {
95
+ [chainId]: {
96
+ address: signerAddress,
97
+ denoms: feeAssets.map((asset) => asset.denom ?? "")
98
+ }
99
+ }
100
+ });
101
+ const validatedAssets = feeAssets.map((asset, index) => {
102
+ const chainAsset = skipAssets?.find((x) => x.denom === asset.denom);
103
+ const symbol = chainAsset?.recommendedSymbol?.toUpperCase();
104
+ const decimal = Number(chainAsset?.decimals);
105
+ if (!chainAsset) {
106
+ return {
107
+ error: `(${chain?.prettyName}) Unable to find asset for ${asset.denom}`
108
+ };
109
+ }
110
+ if (isNaN(decimal))
111
+ return {
112
+ error: `(${chain?.prettyName}) Unable to find decimal for ${symbol}`
113
+ };
114
+ const fee = fees[index];
115
+ if (!fee) {
116
+ return {
117
+ error: `(${chain?.prettyName}) Unable to calculate fee for ${symbol}`,
118
+ asset
119
+ };
120
+ }
121
+ if (txIndex !== 0 && chainId === "noble-1") {
122
+ return {
123
+ error: null,
124
+ asset,
125
+ fee
126
+ };
127
+ }
128
+ let balance = feeBalance?.chains?.[chainId]?.denoms?.[asset?.denom ?? ""];
129
+ if (!balance) {
130
+ balance = {
131
+ amount: "0",
132
+ formattedAmount: "0"
133
+ };
134
+ }
135
+ if (!fee.amount[0]?.amount) {
136
+ return {
137
+ error: `(${chain?.prettyName}) Unable to get fee for ${symbol}`,
138
+ asset
139
+ };
140
+ }
141
+ if (parseInt(balance?.amount ?? "") < parseInt(fee.amount[0]?.amount)) {
142
+ const userAmount = new BigNumber(parseFloat(balance?.amount ?? "")).shiftedBy(-decimal).toFixed(decimal);
143
+ const feeAmount = new BigNumber(parseFloat(fee.amount[0]?.amount)).shiftedBy(-decimal).toFixed(decimal);
144
+ return {
145
+ error: `Insufficient balance for gas on ${chain?.prettyName}. Need ${feeAmount} ${symbol} but only have ${userAmount} ${symbol}.`,
146
+ asset
147
+ };
148
+ }
149
+ return {
150
+ error: null,
151
+ asset,
152
+ fee
153
+ };
154
+ });
155
+ if (prioFeeDenom) {
156
+ const availableAssets = validatedAssets.filter(
157
+ (res) => res?.error === null
158
+ );
159
+ const prioFeeAsset = availableAssets.find(
160
+ (res) => res?.asset?.denom === prioFeeDenom
161
+ );
162
+ if (prioFeeAsset) {
163
+ return prioFeeAsset;
164
+ }
165
+ }
166
+ const feeUsed = validatedAssets.find((res) => res?.error === null);
167
+ if (!feeUsed) {
168
+ if (validatedAssets.length > 1) {
169
+ throw new Error(
170
+ validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chain.prettyName}.`
171
+ );
172
+ }
173
+ throw new Error(
174
+ validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chain.prettyName}.`
175
+ );
176
+ }
177
+ return feeUsed;
178
+ };
179
+
180
+ export { validateCosmosGasBalance };
@@ -1,5 +1,6 @@
1
+ import { validateCosmosGasBalance } from './chunk-35T3HXEL.js';
1
2
  import { waitForTransaction } from './chunk-COJAW7OW.js';
2
- import { getEncodeObjectFromCosmosMessage, getCosmosGasAmountForMessage, getEncodeObjectFromCosmosMessageInjective } from './chunk-TV2XPAIF.js';
3
+ import { getEncodeObjectFromCosmosMessage, getEncodeObjectFromCosmosMessageInjective } from './chunk-TV2XPAIF.js';
3
4
  import { getEVMGasAmountForMessage } from './chunk-GV2QOWB4.js';
4
5
  import { BigNumber } from './chunk-VQ5SIQWU.js';
5
6
  import { GAS_STATION_CHAIN_IDS } from './chunk-SWYON2RG.js';
@@ -13,7 +14,7 @@ import { ClientState, balances } from './chunk-4XUWIG3Z.js';
13
14
  import { ApiState, wait, createRequestClient, toCamel } from './chunk-YABXOO3H.js';
14
15
  import { PublicKey, Transaction, Connection, LAMPORTS_PER_SOL } from '@solana/web3.js';
15
16
  import { bech32m, bech32 } from 'bech32';
16
- import { StargateClient, GasPrice, calculateFee } from '@cosmjs/stargate';
17
+ import { StargateClient } from '@cosmjs/stargate';
17
18
  import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx.js';
18
19
  import { isOfflineDirectSigner, makeAuthInfoBytes, makeSignDoc, encodePubkey } from '@cosmjs/proto-signing';
19
20
  import { fromBase64, toBase64 } from '@cosmjs/encoding';
@@ -22,7 +23,7 @@ import { BigNumberInBase, DEFAULT_BLOCK_TIMEOUT_HEIGHT, DEFAULT_STD_FEE } from '
22
23
  import { pubkeyType as pubkeyType$1, makeSignDoc as makeSignDoc$1, encodeSecp256k1Pubkey } from '@cosmjs/amino';
23
24
  import { PubKey } from 'cosmjs-types/cosmos/crypto/secp256k1/keys.js';
24
25
  import { Any } from 'cosmjs-types/google/protobuf/any.js';
25
- import { Int53, Decimal } from '@cosmjs/math';
26
+ import { Int53 } from '@cosmjs/math';
26
27
  import { SignMode } from 'cosmjs-types/cosmos/tx/signing/v1beta1/signing.js';
27
28
  import { isAddress, publicActions, maxUint256, formatUnits } from 'viem';
28
29
 
@@ -819,157 +820,6 @@ var executeSvmTransaction = async (tx, options) => {
819
820
  }
820
821
  }
821
822
  };
822
- var validateCosmosGasBalance = async ({
823
- chainId,
824
- signerAddress,
825
- messages: messages2,
826
- getFallbackGasAmount,
827
- getOfflineSigner,
828
- txIndex,
829
- simulate
830
- }) => {
831
- const skipAssets = (await ClientState.getSkipAssets({ chainId }))?.[chainId];
832
- const skipChains = await ClientState.getSkipChains();
833
- const chain = skipChains?.find((c) => c.chainId === chainId);
834
- if (!chain) {
835
- throw new Error(`failed to find chain id '${chainId}'`);
836
- }
837
- const { feeAssets } = chain;
838
- if (!feeAssets) {
839
- throw new Error(`failed to find fee assets for chain id '${chainId}'`);
840
- }
841
- const estimatedGasAmount = await (async () => {
842
- try {
843
- if (!simulate) throw new Error("simulate");
844
- if (txIndex !== 0 && chainId === "noble-1") {
845
- return "0";
846
- }
847
- const { stargateClient } = await getSigningStargateClient({
848
- chainId,
849
- getOfflineSigner
850
- });
851
- const estimatedGas = await getCosmosGasAmountForMessage(
852
- stargateClient,
853
- signerAddress,
854
- chainId,
855
- messages2
856
- );
857
- return estimatedGas;
858
- } catch (e) {
859
- const error = e;
860
- if (error.message === "simulate" && !getFallbackGasAmount) {
861
- throw new Error(`unable to get gas amount for ${chainId}'s message(s)`);
862
- }
863
- if (getFallbackGasAmount) {
864
- const fallbackGasAmount = await getFallbackGasAmount(chainId, "cosmos" /* Cosmos */);
865
- if (!fallbackGasAmount) {
866
- throw new Error(`unable to estimate gas for message(s) ${messages2}`);
867
- }
868
- return String(fallbackGasAmount);
869
- }
870
- throw error;
871
- }
872
- })();
873
- const fees = feeAssets.map((asset) => {
874
- const gasPrice = (() => {
875
- if (!asset?.gasPrice) return void 0;
876
- let price = asset.gasPrice.average;
877
- if (price === "") {
878
- price = asset.gasPrice.high;
879
- }
880
- if (price === "") {
881
- price = asset.gasPrice.low;
882
- }
883
- if (!price) return;
884
- return new GasPrice(
885
- Decimal.fromUserInput(BigNumber(price).toFixed(), 18),
886
- asset?.denom ?? ""
887
- );
888
- })();
889
- if (!gasPrice) {
890
- return null;
891
- }
892
- if (chainId === "noble-1") {
893
- const fee = calculateFee(2e5, gasPrice);
894
- return fee;
895
- }
896
- return calculateFee(Math.ceil(parseFloat(estimatedGasAmount)), gasPrice);
897
- });
898
- const feeBalance = await balances({
899
- chains: {
900
- [chainId]: {
901
- address: signerAddress,
902
- denoms: feeAssets.map((asset) => asset.denom ?? "")
903
- }
904
- }
905
- });
906
- const validatedAssets = feeAssets.map((asset, index) => {
907
- const chainAsset = skipAssets?.find((x) => x.denom === asset.denom);
908
- const symbol = chainAsset?.recommendedSymbol?.toUpperCase();
909
- const decimal = Number(chainAsset?.decimals);
910
- if (!chainAsset) {
911
- return {
912
- error: `(${chain?.prettyName}) Unable to find asset for ${asset.denom}`
913
- };
914
- }
915
- if (isNaN(decimal))
916
- return {
917
- error: `(${chain?.prettyName}) Unable to find decimal for ${symbol}`
918
- };
919
- const fee = fees[index];
920
- if (!fee) {
921
- return {
922
- error: `(${chain?.prettyName}) Unable to calculate fee for ${symbol}`,
923
- asset
924
- };
925
- }
926
- if (txIndex !== 0 && chainId === "noble-1") {
927
- return {
928
- error: null,
929
- asset,
930
- fee
931
- };
932
- }
933
- let balance = feeBalance?.chains?.[chainId]?.denoms?.[asset?.denom ?? ""];
934
- if (!balance) {
935
- balance = {
936
- amount: "0",
937
- formattedAmount: "0"
938
- };
939
- }
940
- if (!fee.amount[0]?.amount) {
941
- return {
942
- error: `(${chain?.prettyName}) Unable to get fee for ${symbol}`,
943
- asset
944
- };
945
- }
946
- if (parseInt(balance?.amount ?? "") < parseInt(fee.amount[0]?.amount)) {
947
- const userAmount = new BigNumber(parseFloat(balance?.amount ?? "")).shiftedBy(-decimal).toFixed(decimal);
948
- const feeAmount = new BigNumber(parseFloat(fee.amount[0]?.amount)).shiftedBy(-decimal).toFixed(decimal);
949
- return {
950
- error: `Insufficient balance for gas on ${chain?.prettyName}. Need ${feeAmount} ${symbol} but only have ${userAmount} ${symbol}.`,
951
- asset
952
- };
953
- }
954
- return {
955
- error: null,
956
- asset,
957
- fee
958
- };
959
- });
960
- const feeUsed = validatedAssets.find((res) => res?.error === null);
961
- if (!feeUsed) {
962
- if (validatedAssets.length > 1) {
963
- throw new Error(
964
- validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chain.prettyName}.`
965
- );
966
- }
967
- throw new Error(
968
- validatedAssets[0]?.error || `Insufficient fee token to initiate transfer on ${chain.prettyName}.`
969
- );
970
- }
971
- return feeUsed;
972
- };
973
823
  var validateEvmTokenApproval = async ({
974
824
  requiredErc20Approvals,
975
825
  signer,
@@ -1209,7 +1059,8 @@ var validateGasBalances = async ({
1209
1059
  simulate,
1210
1060
  disabledChainIds,
1211
1061
  enabledChainIds,
1212
- useUnlimitedApproval
1062
+ useUnlimitedApproval,
1063
+ getCosmosPriorityFeeDenom
1213
1064
  }) => {
1214
1065
  const validateResult = await Promise.all(
1215
1066
  txs.map(async (tx, i) => {
@@ -1231,7 +1082,8 @@ var validateGasBalances = async ({
1231
1082
  getFallbackGasAmount,
1232
1083
  getOfflineSigner: getCosmosSigner,
1233
1084
  txIndex: i,
1234
- simulate
1085
+ simulate,
1086
+ getCosmosPriorityFeeDenom
1235
1087
  });
1236
1088
  return res;
1237
1089
  } catch (e) {
@@ -1359,7 +1211,8 @@ var executeTransactions = async (options) => {
1359
1211
  getEvmSigner,
1360
1212
  onValidateGasBalance,
1361
1213
  simulate,
1362
- disabledChainIds: validateChainIds
1214
+ disabledChainIds: validateChainIds,
1215
+ getCosmosPriorityFeeDenom: options.getCosmosPriorityFeeDenom
1363
1216
  });
1364
1217
  const validateEnabledChainIds = async (chainId) => {
1365
1218
  await validateGasBalances({
@@ -1369,7 +1222,8 @@ var executeTransactions = async (options) => {
1369
1222
  getEvmSigner,
1370
1223
  onValidateGasBalance,
1371
1224
  simulate,
1372
- enabledChainIds: !batchSimulate ? [chainId] : validateChainIds
1225
+ enabledChainIds: !batchSimulate ? [chainId] : validateChainIds,
1226
+ getCosmosPriorityFeeDenom: options.getCosmosPriorityFeeDenom
1373
1227
  });
1374
1228
  };
1375
1229
  let signedTxs = [];
package/dist/index.d.ts CHANGED
@@ -25,6 +25,7 @@ export { SetApiOptionsProps, setApiOptions } from './public-functions/setApiOpti
25
25
  export { waitForTransaction } from './public-functions/waitForTransaction.js';
26
26
  export { getCosmosGasAmountForMessage } from './public-functions/getCosmosGasAmountForMessage.js';
27
27
  export { getEVMGasAmountForMessage } from './public-functions/getEvmGasAmountForMessage.js';
28
+ export { validateCosmosGasBalance } from './public-functions/validateCosmosGasBalance.js';
28
29
  export { SubmitRequest, SubmitResponse, submit } from './api/postSubmit.js';
29
30
  import '@cosmjs/amino';
30
31
  import '@cosmjs/proto-signing';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { setClientOptions } from './chunk-A4M35XLF.js';
2
- export { executeRoute } from './chunk-TTLOL6VT.js';
2
+ export { executeRoute } from './chunk-PFJUQWAV.js';
3
+ export { validateCosmosGasBalance } from './chunk-35T3HXEL.js';
3
4
  export { waitForTransaction } from './chunk-COJAW7OW.js';
4
5
  export { transactionStatus } from './chunk-XZV42PVV.js';
5
6
  export { getCosmosGasAmountForMessage } from './chunk-TV2XPAIF.js';
@@ -58,6 +58,11 @@ type ExecuteRouteOptions = SignerGetters & GasOptions & TransactionCallbacks & P
58
58
  * Specify actions to perform after the route is completed
59
59
  */
60
60
  postRouteHandler?: PostHandler;
61
+ /**
62
+ * If `cosmosPriorityFeeDenom` is provided, it will be used to set the priority fee for Cosmos transactions.
63
+ * It should be a function that takes a chainId and returns the denom for the priority fee.
64
+ */
65
+ getCosmosPriorityFeeDenom?: (chainId: string) => Promise<string | undefined>;
61
66
  };
62
67
  declare const executeRoute: (options: ExecuteRouteOptions) => Promise<void>;
63
68
 
@@ -1,4 +1,5 @@
1
- export { executeRoute } from '../chunk-TTLOL6VT.js';
1
+ export { executeRoute } from '../chunk-PFJUQWAV.js';
2
+ import '../chunk-35T3HXEL.js';
2
3
  import '../chunk-COJAW7OW.js';
3
4
  import '../chunk-XZV42PVV.js';
4
5
  import '../chunk-TV2XPAIF.js';
@@ -0,0 +1,42 @@
1
+ import * as _cosmjs_stargate from '@cosmjs/stargate';
2
+ import { W as CosmosMsg, a3 as FeeAsset } from '../swaggerTypes-BpJPRbC3.js';
3
+ import { OfflineSigner } from '@cosmjs/proto-signing';
4
+ import { ExecuteRouteOptions } from './executeRoute.js';
5
+ import { G as GetFallbackGasAmount } from '../client-types-DRmsTfeT.js';
6
+ import '../callbacks-CPh0dr86.js';
7
+ import '../generateApi-D7KXciAd.js';
8
+ import '../api/postTrackTransaction.js';
9
+ import '@cosmjs/amino';
10
+ import 'viem';
11
+ import '@solana/wallet-adapter-base';
12
+
13
+ type ValidateCosmosGasBalanceProps = {
14
+ chainId: string;
15
+ signerAddress: string;
16
+ messages?: CosmosMsg[];
17
+ getOfflineSigner?: (chainId: string) => Promise<OfflineSigner>;
18
+ getFallbackGasAmount?: GetFallbackGasAmount;
19
+ txIndex?: number;
20
+ simulate?: ExecuteRouteOptions["simulate"];
21
+ getCosmosPriorityFeeDenom?: ExecuteRouteOptions["getCosmosPriorityFeeDenom"];
22
+ };
23
+ /**
24
+ *
25
+ * Validate gas balance for cosmos messages returns a fee asset and StdFee to be used
26
+ *
27
+ */
28
+ declare const validateCosmosGasBalance: ({ chainId, signerAddress, messages, getFallbackGasAmount, getOfflineSigner, txIndex, simulate, getCosmosPriorityFeeDenom, }: ValidateCosmosGasBalanceProps) => Promise<{
29
+ error: string;
30
+ asset?: undefined;
31
+ fee?: undefined;
32
+ } | {
33
+ error: string;
34
+ asset: FeeAsset;
35
+ fee?: undefined;
36
+ } | {
37
+ error: null;
38
+ asset: FeeAsset;
39
+ fee: _cosmjs_stargate.StdFee;
40
+ }>;
41
+
42
+ export { type ValidateCosmosGasBalanceProps, validateCosmosGasBalance };
@@ -0,0 +1,9 @@
1
+ export { validateCosmosGasBalance } from '../chunk-35T3HXEL.js';
2
+ import '../chunk-TV2XPAIF.js';
3
+ import '../chunk-TD63P2AG.js';
4
+ import '../chunk-VQ5SIQWU.js';
5
+ import '../chunk-72PK3PKI.js';
6
+ import '../chunk-36MCR5DZ.js';
7
+ import '../chunk-4XUWIG3Z.js';
8
+ import '../chunk-YABXOO3H.js';
9
+ import '../chunk-UXUJNZOA.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@skip-go/client",
3
3
  "description": "JavaScript SDK for Skip Go API",
4
- "version": "1.2.1",
4
+ "version": "1.2.2",
5
5
  "repository": "https://github.com/skip-mev/skip-go",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",