@swapkit/toolboxes 6.3.0 → 6.4.1
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.
- package/CHANGELOG.md +19 -0
- package/dist/chunk-1shb645r.js +1 -0
- package/dist/{chunk-exyqap7m.js → chunk-pz8xe0qj.js} +1 -1
- package/dist/{chunk-xdkdc1f0.js → chunk-qk8kg62t.js} +1 -1
- package/dist/chunk-vdabez6b.js +2 -0
- package/dist/src/aleo/index.js +1 -1
- package/dist/src/aptos/index.js +1 -1
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- package/dist/src/evm/index.js +1 -1
- package/dist/src/hypercore/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/lightspark/index.js +1 -0
- package/dist/src/near/index.js +1 -1
- package/dist/src/radix/index.js +1 -1
- package/dist/src/ripple/index.js +1 -1
- package/dist/src/solana/index.js +1 -1
- package/dist/src/starknet/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/substrate/index.js +1 -1
- package/dist/src/sui/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/src/tron/index.js +1 -1
- package/dist/src/utxo/index.js +1 -1
- package/dist/types/evm/helpers.d.ts +4 -0
- package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -1
- package/dist/types/evm/toolbox/evm.d.ts +24 -24
- package/dist/types/evm/toolbox/op.d.ts +2 -2
- package/dist/types/hypercore/payin.d.ts +0 -1
- package/dist/types/lightspark/__tests__/vendorMissing.probe.d.ts +1 -0
- package/dist/types/lightspark/helpers.d.ts +13 -0
- package/dist/types/lightspark/index.d.ts +3 -0
- package/dist/types/lightspark/invoiceAssert.d.ts +18 -0
- package/dist/types/lightspark/toolbox.d.ts +13 -0
- package/dist/types/lightspark/types.d.ts +196 -0
- package/dist/types/starknet/types.d.ts +1 -0
- package/dist/types/sui/__tests__/grpcClientMock.d.ts +37 -0
- package/package.json +6 -2
- package/dist/chunk-ncc6qmj6.js +0 -1
- package/dist/chunk-ygq25ce3.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.4.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#457](https://github.com/swapkit/sdk/pull/457) [`59568bc`](https://github.com/swapkit/sdk/commit/59568bcafbe907e7efa3a6ee0eb55a8c2500bac4) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM `signTypedData` now accepts standard EIP-712 payloads that include `EIP712Domain` in `types`, as wallets and backends produce them for `eth_signTypedData_v4`. Such payloads previously threw; callers no longer need to strip `EIP712Domain` before signing. If the declared `EIP712Domain` does not exactly match the fields of `domain` (names, types and canonical order), signing rejects with `toolbox_evm_typed_data_domain_mismatch` instead of signing a different domain. Payloads without it sign exactly as before.
|
|
8
|
+
- [#452](https://github.com/swapkit/sdk/pull/452) [`8f3ecb0`](https://github.com/swapkit/sdk/commit/8f3ecb0522e2433f38012277446fd56ba1a223c5) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The Sui toolbox now talks to Sui over gRPC instead of JSON-RPC, which Sui's public fullnodes stopped serving. Balances, transfers, sweeps, fee estimates and swaps from Sui work again with the default RPC. A custom Sui RPC set in `rpcUrls` must now serve gRPC.
|
|
9
|
+
- [#459](https://github.com/swapkit/sdk/pull/459) [`29bda2c`](https://github.com/swapkit/sdk/commit/29bda2c7a7f69112fc9403c042cb4aee7c2010a5) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Wallets now declare all their signing capabilities per chain in one `signingSupport` map on `createWallet`: `direct` (signs the transaction the API builds for a route), `typedData` (EIP-712) and `btcMessage` (BIP-137), with the names exported as `SigningCapability`. Undeclared capabilities count as unsupported, and each connected chain wallet carries its capabilities as `signing`. Use `walletSupportsDirectSigning(wallet)` to check for direct signing; it understands wallets from both old and new connectors. (via @swapkit/helpers@6.3.0)
|
|
10
|
+
- [#462](https://github.com/swapkit/sdk/pull/462) [`adf132c`](https://github.com/swapkit/sdk/commit/adf132ce1b856153be10f132372cb4fd6cabe7d6) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM wallets wrapped by `prepareNetworkSwitch` now switch to the chain's network before `signTypedData`, as they already do before sending a transaction. A refused or impossible switch fails with `helpers_failed_to_switch_network` before anything is signed. Message signing (`signMessage`) is unchanged. (via @swapkit/helpers@6.3.0)
|
|
11
|
+
- [#453](https://github.com/swapkit/sdk/pull/453) [`e8988db`](https://github.com/swapkit/sdk/commit/e8988dbd06040f6b134163e7d9cba1910b9ee711) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.3.0)
|
|
12
|
+
|
|
13
|
+
## 6.4.0
|
|
14
|
+
|
|
15
|
+
### Minor Changes
|
|
16
|
+
|
|
17
|
+
- [#373](https://github.com/swapkit/sdk/pull/373) [`218e46d`](https://github.com/swapkit/sdk/commit/218e46d12d423e0420143ec410f0a4c8d102ab8d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Add a standalone Lightning toolbox backed by Lightspark at `@swapkit/toolboxes/lightspark`, re-exported from `@swapkit/server`. It ships with no `Chain` enum member and no core or wallet wiring.
|
|
18
|
+
- [#449](https://github.com/swapkit/sdk/pull/449) [`e105e04`](https://github.com/swapkit/sdk/commit/e105e0417e77c486406706ecf1c0ed12c77c4375) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The Starknet toolbox uses a wallet-provided account only to sign and send. Network reads and fee estimates go through the configured Starknet RPC, so wallets that bundle an older starknet.js (such as OKX Wallet) no longer fail with `getClassHashAt` of undefined or an "Invalid block id" error.
|
|
19
|
+
- [#373](https://github.com/swapkit/sdk/pull/373) [`218e46d`](https://github.com/swapkit/sdk/commit/218e46d12d423e0420143ec410f0a4c8d102ab8d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Add the `toolbox_lightspark_*` block (91301 to 91313) to `SwapKitError.ErrorCode` for the new Lightning toolbox: `toolbox_lightspark_missing_credentials`, `toolbox_lightspark_invalid_invoice`, `toolbox_lightspark_invoice_amount_mismatch`, `toolbox_lightspark_invoice_destination_mismatch`, `toolbox_lightspark_invoice_expired`, `toolbox_lightspark_invoice_already_settled`, `toolbox_lightspark_fee_limit_exceeded`, `toolbox_lightspark_invalid_params`, `toolbox_lightspark_api_error`, `toolbox_lightspark_invalid_amount`, `toolbox_lightspark_invalid_destination`, `toolbox_lightspark_network_mismatch` and `toolbox_lightspark_signing_key_unavailable`. An unloadable node signing key is reported as `toolbox_lightspark_signing_key_unavailable`, distinct from `toolbox_lightspark_missing_credentials`, so an integrator branching on the code can tell an unloaded key from an absent credential. (via @swapkit/helpers@6.2.0)
|
|
20
|
+
- [#447](https://github.com/swapkit/sdk/pull/447) [`b827853`](https://github.com/swapkit/sdk/commit/b827853cd1bfa68a9bd733843b3740f10ecab359) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.2.0)
|
|
21
|
+
|
|
3
22
|
## 6.3.0
|
|
4
23
|
|
|
5
24
|
### Minor Changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-vdabez6b.js";import"./chunk-qk8kg62t.js";import"./chunk-pz8xe0qj.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var d=((a)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
|
|
2
|
-
export{d as
|
|
2
|
+
export{d as ka};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{AssetValue as o,getChainConfig as l}from"@swapkit/helpers";import{SwapKitApi as m}from"@swapkit/helpers/api";var d=typeof process<"u"&&process.pid?process.pid.toString(36):"",i=0;function C(){function t(){let e=Date.now(),n=i||e;return i=n,e>i?e:n+1}return d+t().toString(36)}function h(t){return async function(n,r=!0){let c=await m.getChainBalance({address:n,chain:t,scamFilter:r}),{baseDecimal:p}=l(t),s=c.map(({identifier:a,value:u,decimal:f})=>new o({decimal:f||p,identifier:a,value:u}));if(!s.some((a)=>a.isGasAsset))return[o.from({chain:t}),...s];return s}}
|
|
2
|
-
export{C as
|
|
2
|
+
export{C as ia,h as ja};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ja as Se}from"./chunk-qk8kg62t.js";import{ka as ye}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as On}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as Ct,SKConfig as Ft,SwapKitError as z}from"@swapkit/helpers";import{FallbackProvider as At,getAddress as _e,Interface as Mt,JsonRpcProvider as se,Network as Gt}from"ethers";import{match as Ce}from"ts-pattern";function Bt(e){return new se(e)}async function kn(e,t){return Bt(t||await Ct(e))}function Fe(e){let t=Ft.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new z("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Gt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new At(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function B(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Ae(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Ot({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Me(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Ot({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return Ce(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Ge(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var Ee=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),It=(e)=>{try{return typeof e==="string"&&!!_e(e)}catch{return!1}};function Vt(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new z({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};Ce(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!It(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!Ee(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!Ee(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Be(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Be(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new z({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Nn({chain:e,abi:t,data:n,to:o}){let r=new Mt(t).parseTransaction({data:n});if(!r)throw new z({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:_e(o)},y=Be(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:y,...i}}}function Ie(e,t){if(!Array.isArray(e)||e.length===0)throw new z({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(Vt(o,n),t!==void 0&&o.chainId!==t)throw new z({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Cn,FeeOption as Fn,resolveDerivationPath as An}from"@swapkit/helpers";import{HDNodeWallet as Mn}from"ethers";import{match as Gn,P as ot}from"ts-pattern";var Ve=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as St,applyFeeMultiplierToBigInt as M,Chain as O,EVMChains as Rt,FeeOption as d,isGasAsset as kt,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Nt,Contract as Ne,getAddress as ee,getBytes as Lt,Interface as Le,isError as U,resolveAddress as Dt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Se(e)}}function Hn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=O.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:en({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:fn({chain:e,provider:t,signer:n}),createContract:Ht({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:nn({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Ae(e),isApproved:Zt({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:on({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:y}=Oe(c);return await n.signTypedData(l,u,y)}:void 0,transfer:tn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Nt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Ht({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var zt=["payable","nonpayable"];function Kt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&zt.includes(n.stateMutability)}function Jn(e){return ee(e)}var qt=30000,Re=new WeakMap,ke=()=>{};function jt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>qt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function Ue({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:ke,settle:ke};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=jt(a,r,i),l=!1,u=(y)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),y)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(U(e,"NONCE_EXPIRED")||U(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function de(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function He(e){return U(e,"NETWORK_ERROR")||U(e,"SERVER_ERROR")||U(e,"TIMEOUT")}function Wt(e){return He(e)||U(e,"UNSUPPORTED_OPERATION")}function ze(e){return He(e)||de(e)}function Ke(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function Xt({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await Ke(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,y={...u,...t&&i!==void 0&&{gas:B(BigInt(i))},...t&&s!==void 0&&{gasPrice:B(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:B(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:B(BigInt(l))},value:B(BigInt(o||0))};return e.send("eth_sendTransaction",[y])}}function Yn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var $t=Rt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Jt={...$t,[O.Optimism]:"0x4200000000000000000000000000000000000042",[O.Polygon]:"0x0000000000000000000000000000000000001010"},Yt=[O.Arbitrum,O.Aurora,O.Base,O.Optimism,O.Robinhood];function xe({chain:e,symbol:t,ticker:n},o){try{let a=e===O.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===O.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Yt.includes(e)&&t==="ETH"&&n==="ETH",c=e===O.Arc&&t==="USDC"&&n==="USDC";if(i||a||r||s||c)return Jt[o];return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:B(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(O.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:M(a,d.Average),maxPriorityFeePerGas:M(r,d.Average)},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(O.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[d.Average]:{gasPrice:r},[d.Fast]:{gasPrice:M(r,d.Fast)},[d.Fastest]:{gasPrice:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[d.Average]:{gasPrice:i},[d.Fast]:{gasPrice:M(i,d.Fast)},[d.Fastest]:{gasPrice:M(i,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Qt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let y=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await Dt(u,n),{nonce:G,release:R,settle:N}=await Ue({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await y[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!ze(_))R();throw _}finally{N()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:y=d.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=Kt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Qt({chain:o,contract:f,contractProvider:p,feeOption:y,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function Zt({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function en({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=d.Fast,amount:c,gasLimitFallback:l,from:u,nonce:y}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:y}})}}function tn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=d.Fast,sender:y,sweep:p,...b}){let f=y||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function nn({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let y=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:y})}}function on({signer:e}){if(!e)return;return(t)=>Ge(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,an=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),rn=(e,t=!0)=>{if(We(e))return"eip7702";if(an(e)||t)return"eip1559";return"legacy"};function sn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:B(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:B(t.maxFeePerGas),maxPriorityFeePerGas:B(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=d.Fast,sweep:s,...c}){let{from:l,to:u,data:y,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:y||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:N}=await Ue({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=rn(f,a);if(E==="eip7702")Ie(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),V={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),S=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:sn(E,(await F())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(I){throw new m("toolbox_evm_error_estimating_gas_limit",{error:I})}return{...V,gasLimit:h,...S}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let V=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:V};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(de(w)){let h=await Xt({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Wt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let L=U(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:P})}catch(h){if(L)R();let I={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let I={...F,fallbackError:h};if(de(h)){let H=pe.from(S).hash;if(H)return H}if(fe(h)){let H=pe.from(S).hash;if(H&&await Ke(C,H))return H;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:I},I)}if(L&&!ze(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}}}finally{N()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function cn(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function un(e){return Lt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function ln({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)D(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function mn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),y=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=cn((await y())[a],i),f={...l,...p,data:t,from:r,to:c},P=un(t)*b;if(u-P<=0n)D(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(I){if(me(I))D(u,P);throw I}}let G=C*b;if(u-G<=0n)D(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;D(u,_)}let V=w*b,F=u-V;if(F<=0n)D(u,V);let L=await ln({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:V,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),S=F-L;if(S<=0n)D(u,V+L);return{...f,gasLimit:w,value:B(S)}}async function pn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:y,feeOptionKey:p=d.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...N}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(kt(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=y||L(S(l||""));if(!P)return{...N,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:B(_)};return mn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:N.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),F=P?await pn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return V({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:N.nonce}})}}function fn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),y=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(y)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=d.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=St.from({chain:n}),{gasPrice:u,maxFeePerGas:y,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(y&&p){let b=(y+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as q,Chain as Qe,derivationPathToString as yn,FeeOption as k,getChainConfig as bn,resolveDerivationPath as gn,SwapKitError as j}from"@swapkit/helpers";import{Contract as xn,HDNodeWallet as Pn}from"ethers";import{match as Tn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var wn="0x420000000000000000000000000000000000000f";function re(e){return new xn(wn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new j("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new j({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new j({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function hn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new j({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function vn(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function En(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=q(t,e),a=q(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function _n(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new j("toolbox_evm_no_fee_data");return{[k.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:k.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[k.Fast]:{gasPrice:q(i,k.Fast),l1GasPrice:q(r||0n,k.Fast),...Te({feeOption:k.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[k.Fastest]:{gasPrice:q(i,k.Fastest),l1GasPrice:q(r||0n,k.Fastest),...Te({feeOption:k.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new j("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=Tn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Pn.fromPhrase(p,void 0,yn(gn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(bn(e).chainId),s=we(n,i),c=hn(n,i),l=he(n),u=e===Qe.Optimism?_n(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:En(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:vn(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=Fn.Fast){let s=await t.createContractTxObject({abi:Ve,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),yo=v(T.Botanix),ft=v(T.Core),dt=v(T.Corn),yt=v(T.Cronos),bt=v(T.Gnosis),gt=v(T.Robinhood),xt=v(T.Hyperevm),Pt=v(T.Linea),Tt=v(T.Polygon),wt=v(T.MegaETH),ht=v(T.Monad),vt=v(T.Plasma),ve=v(T.Sonic),Et=ie(T.Unichain),_t=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Me(e),r=Gn(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Mn.fromPhrase(s,void 0,Cn(An({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function In(e,t){return On(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ve(t)).with(x.Core,()=>ft(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>yt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>bt(t)).with(x.Hyperevm,()=>xt(t)).with(x.Linea,()=>Pt(t)).with(x.MegaETH,()=>wt(t)).with(x.Monad,()=>ht(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>vt(t)).with(x.Polygon,()=>Tt(t)).with(x.Robinhood,()=>gt(t)).with(x.Sonic,()=>ve(t)).with(x.Unichain,()=>Et(t)).with(x.XLayer,()=>_t(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Fe(e)};return In(e,n)}
|
|
2
|
+
export{Y as b,Hn as c,Bt as d,kn as e,Fe as f,B as g,Ae as h,Me as i,Ge as j,Vt as k,Be as l,Oe as m,Nn as n,Ie as o,be as p,te as q,Ut as r,ne as s,ge as t,Ht as u,Kt as v,Jn as w,oe as x,Yn as y,Jt as z,xe as A,W as B,X as C,We as D,an as E,rn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,yo as T,ft as U,dt as V,yt as W,bt as X,gt as Y,xt as Z,Pt as _,Tt as $,wt as aa,ht as ba,vt as ca,ve as da,Et as ea,_t as fa,In as ga,To as ha};
|
package/dist/src/aleo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as it}from"../../chunk-xdkdc1f0.js";import{ja as x}from"../../chunk-exyqap7m.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
|
|
1
|
+
import{ja as it}from"../../chunk-qk8kg62t.js";import{ka as x}from"../../chunk-pz8xe0qj.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
|
package/dist/src/aptos/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ka as B}from"../../chunk-pz8xe0qj.js";import{AssetValue as b,Chain as A,derivationPathToString as tt,getChainConfig as v,getRPCUrlSync as W,NetworkDerivationPath as nt,SwapKitError as s}from"@swapkit/helpers";import{match as j,P as R}from"ts-pattern";var w={COIN_TYPE:"0x1::aptos_coin::AptosCoin",FUNGIBLE_ASSET_METADATA:"0x1::fungible_asset::Metadata",FUNGIBLE_STORE_TRANSFER:"0x1::primary_fungible_store::transfer",TRANSFER:"0x1::aptos_account::transfer"},st=2000,at=/^[0-9a-fA-F]+$/;function x(e){if(!e||typeof e!=="string"||!e.startsWith("0x"))return!1;let i=e.slice(2);if(i.length===0||i.length>64)return!1;return at.test(i)}function Y(e,i,d){if(e<=0n)throw new s({errorKey:"toolbox_sweep_amount_too_low",info:{amount:e.toString(),asset:i.toString(),...d}});return e}async function ot({aptos:e,assetValue:i,senderAddress:d}){let c=i.address;if(!c)throw new s("toolbox_aptos_missing_asset_type");let[y]=await e.getCurrentFungibleAssetBalances({options:{limit:1,where:{asset_type:{_eq:c},is_primary:{_eq:!0},owner_address:{_eq:d}}}});return Y(BigInt(y?.amount??0),i)}function et({derivationPath:e,provider:i,...d}={}){let c,y=tt(e||nt[A.Aptos],{allHardened:!0});async function T(){if(c)return c;return c=await j(d).with({phrase:R.string},async({phrase:n})=>{let{Ed25519Account:t}=await import("@aptos-labs/ts-sdk");return t.fromDerivationPath({mnemonic:n,path:y})}).with({signer:R.any},({signer:n})=>n).otherwise(()=>{return}),c}async function _(){let{Aptos:n,AptosConfig:t,Network:a}=await import("@aptos-labs/ts-sdk"),r=new t({clientConfig:{http2:!1},fullnode:i||W(A.Aptos),network:a.MAINNET});return new n(r)}async function S(){return(await T())?.accountAddress.toString()||""}async function G(n){let t=n||await S();if(!t)throw new s("toolbox_aptos_address_required");let{baseDecimal:a,chain:r}=v(A.Aptos);try{let u=await _(),p=await u.getAccountAPTAmount({accountAddress:t}),g=[b.from({chain:r,fromBaseDecimal:a,value:p.toString()})],f=await u.getCurrentFungibleAssetBalances({options:{where:{owner_address:{_eq:t}}}});for(let o of f){if(o.asset_type===w.COIN_TYPE||Number(o.amount)<=0)continue;let m=o.asset_type;if(m){let l=("metadata"in o&&typeof o.metadata==="object"&&o.metadata!==null?o.metadata:void 0)?.decimals??a;g.push(b.from({asset:`${A.Aptos}.APT-${m}`,fromBaseDecimal:l,value:String(o.amount)}))}}return g}catch{return[b.from({chain:r})]}}async function H(n){if(!n){let{baseDecimal:g}=v(A.Aptos),f=i||W(A.Aptos),o=await fetch(`${f}/estimate_gas_price`),{gas_estimate:m}=await o.json();return b.from({chain:A.Aptos,fromBaseDecimal:g,value:String(m)})}let t=await N(n),a=await _(),[r]=await a.transaction.simulate.simple({transaction:t});if(!r)throw new s("toolbox_aptos_transaction_creation_error");let u=BigInt(r.gas_used)*BigInt(r.gas_unit_price),{baseDecimal:p}=v(A.Aptos);return b.from({chain:A.Aptos,fromBaseDecimal:p,value:u.toString()})}async function N({recipient:n,assetValue:t,maxGasAmount:a,sender:r,accountSequenceNumber:u,gasUnitPrice:p,sweep:g}){if(!x(n))throw new s("core_transaction_invalid_recipient_address");let f=r||await S();if(!f)throw new s("toolbox_aptos_no_sender");let{AccountAddress:o}=await import("@aptos-labs/ts-sdk"),m=await _(),C=o.from(f);try{let l=t.isGasAsset?w.TRANSFER:w.FUNGIBLE_STORE_TRANSFER,z=t.address,E=(P,O)=>{let k=j({address:z,isGasAsset:t.isGasAsset}).with({isGasAsset:!0},()=>[o.from(n),P]).with({address:R.string},({address:V})=>[o.from(V),o.from(n),P]).otherwise(()=>null);if(!k)throw new s("toolbox_aptos_missing_asset_type");let q=O?.maxGasAmount??a,K=O?.gasUnitPrice??p;return m.transaction.build.simple({data:{function:l,functionArguments:k,typeArguments:t.isGasAsset?[]:[w.FUNGIBLE_ASSET_METADATA]},options:q!==void 0||K!==void 0||u!==void 0?{accountSequenceNumber:u,gasUnitPrice:K,maxGasAmount:q}:void 0,sender:C})};if(!g)return E(t.getBaseValue("bigint"));if(!t.isGasAsset){let P=await ot({aptos:m,assetValue:t,senderAddress:f});return E(P)}let U=BigInt(await m.getAccountAPTAmount({accountAddress:f})),J=await E(1n,{maxGasAmount:a??st}),[h]=await m.transaction.simulate.simple({options:{estimateMaxGasAmount:a===void 0},transaction:J});if(!h)throw new s("toolbox_aptos_transaction_creation_error");if(!h.success)throw new s({errorKey:"toolbox_aptos_transaction_creation_error",info:{vmStatus:h.vm_status}});let D=BigInt(h.gas_used),M=D>0n?(D*6n+4n)/5n:1n,L=M*BigInt(h.gas_unit_price),Z=Y(U-L,t,{balance:U.toString(),fee:L.toString()});return E(Z,{gasUnitPrice:Number(h.gas_unit_price),maxGasAmount:Number(M)})}catch(l){if(l instanceof s)throw l;throw new s("toolbox_aptos_transaction_creation_error",l)}}async function F(n){let t=await T();if(!t)throw new s("toolbox_aptos_no_signer");return(await _()).transaction.sign({signer:t,transaction:n})}async function Q({assetValue:n,maxGasAmount:t,recipient:a,sweep:r}){let u=await T();if(!u)throw new s("toolbox_aptos_no_signer");if(!x(a))throw new s("core_transaction_invalid_recipient_address");try{let p=u.accountAddress.toString(),g=await N({assetValue:n,maxGasAmount:t,recipient:a,sender:p,sweep:r});return(await(await _()).signAndSubmitTransaction({signer:u,transaction:g})).hash}catch(p){if(p instanceof s)throw p;throw new s("toolbox_aptos_transaction_creation_error",p)}}async function I({senderAuthenticator:n,transaction:t}){try{return(await(await _()).transaction.submit.simple({senderAuthenticator:n,transaction:t})).hash}catch(a){throw new s("toolbox_aptos_broadcast_error",a)}}async function X(n){let t=await F(n);return I({senderAuthenticator:t,transaction:n})}return{broadcastTransaction:I,createTransaction:N,estimateTransactionFee:H,getAddress:S,getBalance:G,signAndBroadcastTransaction:X,signTransaction:F,transfer:Q,validateAddress:x}}function rt({provider:e}){return async function({assetValue:d,recipient:c,sweep:y}){if(y)throw new s({errorKey:"toolbox_not_supported",info:{chain:A.Aptos,feature:"extension_provider_sweep",reason:"Aptos extension providers cannot query balances or simulate transactions"}});if(!x(c))throw new s("core_transaction_invalid_recipient_address");let{AccountAddress:T}=await import("@aptos-labs/ts-sdk");if(d.isGasAsset)return(await e.signAndSubmitTransaction({arguments:[T.from(c).toString(),d.getBaseValue("string")],function:w.TRANSFER,type:"entry_function_payload",type_arguments:[]})).hash;let _=d.address;if(!_)throw new s("toolbox_aptos_missing_asset_type");return(await e.signAndSubmitTransaction({arguments:[_,T.from(c).toString(),d.getBaseValue("string")],function:w.FUNGIBLE_STORE_TRANSFER,type:"entry_function_payload",type_arguments:[w.FUNGIBLE_ASSET_METADATA]})).hash}}export{rt as createAptosExtensionTransfer,et as getAptosToolbox,x as validateAptosAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ka as C}from"../../chunk-pz8xe0qj.js";import{hex as W}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";var V=0,it=258;function w(t){return new st("toolbox_cardano_sign_transaction_failed",{message:t})}async function q(t){let{Decoder:e}=await import("@stricahq/cbors"),n=Buffer.from(W.decode(t)),{value:s}=e.decode(n);if(!Array.isArray(s)||s.length!==4)throw w("Invalid Cardano transaction");let[a,i]=s;if(!(a instanceof Map)||!(i instanceof Map))throw w("Invalid Cardano transaction");return{body:a,bytes:n,witnessSet:i}}async function G(t){let{crypto:e}=await import("@stricahq/typhonjs"),{body:n,bytes:s}=await q(t),[a,i]=n.getByteSpan();return{body:n,bodyHash:e.hash32(s.subarray(a,i)).toString("hex")}}async function Y(t,e){let{Encoder:n}=await import("@stricahq/cbors"),{bytes:s,witnessSet:a}=await q(t),i=a.get(V)??[];if(!Array.isArray(i))throw w("Unsupported Cardano witness set");let r=e.map(({publicKey:l,signature:p})=>[Buffer.from(l),Buffer.from(p)]);a.set(V,[...i,...r]);let[c,d]=a.getByteSpan();return Buffer.concat([s.subarray(0,c),n.encode(a),s.subarray(d)]).toString("hex")}async function Pt(t){let{CborTag:e,Decoder:n}=await import("@stricahq/cbors"),{value:s}=n.decode(Buffer.from(W.decode(t)));if(!(s instanceof Map))throw w("Invalid Cardano witness set");if([...s.keys()].some((r)=>r!==V))throw w("Unsupported Cardano witness set");let a=s.get(V),i=a instanceof e&&a.tag===it?a.value:a;if(!Array.isArray(i)||i.length===0)throw w("Cardano witness set has no signatures");return i.map((r)=>{let[c,d]=Array.isArray(r)?r:[];if(!(c instanceof Uint8Array&&d instanceof Uint8Array))throw w("Invalid Cardano witness");if(c.length!==32||d.length!==64)throw w("Invalid Cardano witness");return{publicKey:Uint8Array.from(c),signature:Uint8Array.from(d)}})}async function Tt(t){let{utils:e}=await import("@stricahq/typhonjs");try{return e.getAddressFromHex(Buffer.from(t)).getBech32()}catch(n){throw w(`Invalid Cardano address: ${String(n)}`)}}async function xt(t){let{crypto:e}=await import("@stricahq/typhonjs");return e.hash28(Buffer.from(t))}import{bech32 as ct}from"@scure/base";import{mnemonicToEntropy as ut}from"@scure/bip39";import{wordlist as dt}from"@scure/bip39/wordlists/english.js";import{AssetValue as B,Chain as _,getChainConfig as lt,SwapKitError as g}from"@swapkit/helpers";import f from"bignumber.js";var J="mainnet3YT7XK6NidLPlkHxxyBB5V0WzXUOTIJS",Q="https://cardano-mainnet.blockfrost.io/api/v0",H=2147483648;async function O(t,e){let n=await fetch(`${Q}${t}`,{...e,headers:{project_id:J,...e?.headers}});if(!n.ok)throw Error(`Blockfrost API error: ${n.status} ${n.statusText}`);return n.json()}async function Z(t){try{return await O(`/addresses/${t}/utxos`)}catch{return[]}}async function pt(){return(await O("/blocks/latest")).slot}async function mt(){let t=await O("/epochs/latest/parameters"),e={PlutusScriptV1:t.cost_models.PlutusV1?Object.values(t.cost_models.PlutusV1):[],PlutusScriptV2:t.cost_models.PlutusV2?Object.values(t.cost_models.PlutusV2):[],PlutusScriptV3:t.cost_models.PlutusV3?Object.values(t.cost_models.PlutusV3):[]};return{collateralPercent:new f(t.collateral_percent),languageView:e,maxValueSize:Number.parseInt(t.max_val_size,10),minFeeA:new f(t.min_fee_a),minFeeB:new f(t.min_fee_b),minFeeRefScriptCostPerByte:new f(15),priceMem:new f(t.price_mem),priceSteps:new f(t.price_step),stakeKeyDeposit:new f(2000000),utxoCostPerByte:new f(t.coins_per_utxo_size)}}async function X(t){let e=await fetch(`${Q}/tx/submit`,{body:Buffer.from(t,"hex"),headers:{"Content-Type":"application/cbor",project_id:J},method:"POST"});if(!e.ok){let n=await e.text();throw Error(`Transaction submission failed: ${n}`)}return e.json()}function ft(t,e){return t.map((n)=>{let s=n.amount.find((r)=>r.unit==="lovelace"),a=s?new f(s.quantity):new f(0),i=n.amount.filter((r)=>r.unit!=="lovelace").map((r)=>({amount:new f(r.quantity),assetName:r.unit.slice(56),policyId:r.unit.slice(0,56)}));return{address:e,amount:a,index:n.output_index,tokens:i,txId:n.tx_hash}})}function yt({TransactionConstructor:t,auxiliaryData:e,bufferedParams:n,currentSlot:s,inputs:a,recipientAddress:i}){let r=a.reduce((o,u)=>o.plus(u.amount),new f(0));if(!r.isPositive())throw new g({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString()}});let c=new t({protocolParams:n});for(let o of a)c.addInput(o);if(c.addOutput({address:i,amount:r,tokens:[]}),c.setTTL(s+3600),e)c.setAuxiliaryData(e);c.setFee(c.calculateFee());let d=c.getFee(),l=r.minus(d),p={address:i,amount:l,tokens:[]},b=c.calculateMinUtxoAmountBabbage(p);if(!l.isPositive()||l.lt(b))throw new g({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString(),fee:d.toString(),minimumOutput:b.toString()}});return new t({protocolParams:n}).paymentTransaction({auxiliaryData:e,changeAddress:i,inputs:a,outputs:[p],ttl:s+3600})}async function gt(t){try{let e=await Z(t),n=0n,s=new Map;for(let r of e){if(!r.amount||!Array.isArray(r.amount))continue;for(let c of r.amount){let{unit:d,quantity:l}=c;if(d==="lovelace")n+=BigInt(l);else{let p=s.get(d)||0n;s.set(d,p+BigInt(l))}}}let a=[],{baseDecimal:i}=lt(_.Cardano);if(n>0n)a.push(B.from({chain:_.Cardano,fromBaseDecimal:i,value:n.toString()}));for(let[r,c]of s)a.push(B.from({asset:`${_.Cardano}.${r}`,value:c.toString()}));if(a.length===0)return[B.from({chain:_.Cardano})];return a}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`Cardano balance fetch error: ${n}`),[B.from({chain:_.Cardano})]}}function ht(t){if(!t||typeof t!=="string")return!1;try{let e=ct.decode(t,120);return e.prefix==="addr"||e.prefix==="addr_test"}catch{return!1}}async function wt(t,e=0,n=0){let{Bip32PrivateKey:s}=await import("@stricahq/bip32ed25519"),{types:a,address:i,crypto:r}=await import("@stricahq/typhonjs"),c=ut(t,dt),l=(await s.fromEntropy(Buffer.from(Array.from(c)))).derive(H+1852).derive(H+1815).derive(H+e),p=l.derive(0).derive(n),b=p.toBip32PublicKey().toPublicKey().toBytes(),k=r.hash28(b),u=l.derive(2).derive(0).toBip32PublicKey().toPublicKey().toBytes(),m=r.hash28(u),P={hash:k,type:a.HashType.ADDRESS},T={hash:m,type:a.HashType.ADDRESS},v=new i.BaseAddress(a.NetworkId.MAINNET,P,T).getBech32(),K=p.toPrivateKey();return{getAddress:()=>v,publicKey:b,publicKeyHash:k,signTransaction:async(S)=>{try{let{bodyHash:A}=await G(S),I=K.sign(Buffer.from(A,"hex"));return await Y(S,[{publicKey:b,signature:I}])}catch(A){if(A instanceof g)throw A;throw new g("toolbox_cardano_sign_transaction_failed",{message:String(A)})}}}}function Vt(t){let e,n,s;async function a(){if(!s)s=await mt();return s}async function i(){if(e!==void 0)return e;if(t&&"phrase"in t&&t.phrase){let{derivationPath:o}=t;if(o&&(o.length!==5||o[3]!==0||o[4]===void 0))throw new g("toolbox_derivation_slot_unsupported",{chain:_.Cardano,derivationPath:o});let u=o?.[2]??0,m=o?.[4]??t.index??0;return e=await wt(t.phrase,u,m),e}if(t&&"signer"in t&&t.signer)return e=t.signer,e;return}async function r(){if(n)return n;let o=await i();if(!o)return"";if("getAddress"in o)return n=await o.getAddress(),n;return""}async function c(o){let u=o||await r();if(!u)throw new g("core_wallet_connection_not_found");return gt(u)}async function d(o){if(o)try{let{tx:T}=await l(o),x=T.getFee();return B.from({chain:_.Cardano,fromBaseDecimal:6,value:x.toString()})}catch{}let u=await a(),m=400,P=u.minFeeB.plus(u.minFeeA.times(m));return B.from({chain:_.Cardano,fromBaseDecimal:6,value:P.toString()})}async function l({sender:o="",recipient:u,assetValue:m,memo:P,pureLovelaceOnly:T=!1,sweep:x=!1}){let{Transaction:v,utils:K}=await import("@stricahq/typhonjs"),S=o||await r();if(!S)throw new g("core_wallet_connection_not_found");let[A,I,D]=await Promise.all([Z(S),pt(),a()]);if(x&&!m.isGasAsset)throw new g({errorKey:"toolbox_not_supported",info:{asset:m.toString(),chain:_.Cardano,feature:"token_sweep"}});let U=x&&m.isGasAsset,tt=T||U,et=A.filter((y)=>tt?y.amount.some((h)=>h.unit==="lovelace")&&y.amount.every((h)=>h.unit==="lovelace"):y.amount.some((h)=>h.unit==="lovelace")).sort((y,h)=>{let z=y.amount.some((F)=>F.unit!=="lovelace"),ot=h.amount.some((F)=>F.unit!=="lovelace");if(z===ot)return 0;return z?1:-1}),M=K.getAddressFromString(S),R=K.getAddressFromString(u),L=ft(et,M),E;if(P){let y=new Map;y.set("msg",[P]),E={metadata:[{data:y,label:674}]}}let j={...D,minFeeB:D.minFeeB.plus(D.minFeeA.times(4))};if(U){let y=yt({auxiliaryData:E,bufferedParams:j,currentSlot:I,inputs:L,recipientAddress:R,TransactionConstructor:v}),{payload:h}=y.buildTransaction();return{tx:y,unsignedTx:h}}let nt=new f(m.getBaseValue("string")),rt=[{address:R,amount:nt,tokens:[]}],N=new v({protocolParams:j}).paymentTransaction({auxiliaryData:E,changeAddress:M,inputs:L,outputs:rt,ttl:I+3600}),{payload:at}=N.buildTransaction();return{tx:N,unsignedTx:at}}async function p(o){let u=await i();if(!u||!("signTransaction"in u))throw new g("core_wallet_connection_not_found");return u.signTransaction(o)}async function b({recipient:o,assetValue:u,memo:m,sweep:P}){let T=await i();if(!T||!("signTransaction"in T))throw new g("core_wallet_connection_not_found");let{unsignedTx:x}=await l({assetValue:u,memo:m,recipient:o,sender:await r(),sweep:P}),v=await p(x);return await X(v)}async function k(o){let u=await p(o);return await X(u)}return{createTransaction:l,estimateTransactionFee:d,getAddress:r,getBalance:c,signAndBroadcastTransaction:k,signTransaction:p,transfer:b,validateAddress:ht}}export{Y as addCardanoVkeyWitnesses,G as decodeCardanoTransaction,Pt as decodeCardanoWitnessSet,Tt as getCardanoAddressFromBytes,xt as getCardanoPublicKeyHash,Vt as getCardanoToolbox,ht as validateCardanoAddress};
|
package/dist/src/cosmos/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-exyqap7m.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},At={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return At;case g.Noble:return wt;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),A=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,A),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:w,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,w=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,w,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,w){let S=w??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),S=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,w=c||h?await _(await pt(a)):void 0,S=h&&w?await Mt({client:w,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,A=U(r.symbol),C=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(b.amount,A)})}let T={amount:[{amount:C.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),w=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?w:R(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),w=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as wn,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:A=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[A],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let b=(await Sn(i)(m)).filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).flatMap(({denom:A,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;try{return[In(T,C)]}catch{return[]}});if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=An.decode(n);return An.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,w=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(w,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),w=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:w,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),A=F(i,r),C=await L(l,y,{aminoTypes:A,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:A,signingClient:C}=await p(),T=(await A.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function w(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:A}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=A?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),A=(await y.getAccounts())?.[0]?.address;if(!A)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(A,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:w,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:we(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,At as DEFAULT_KUJI_FEE_MAINNET,wt as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
|
|
1
|
+
import"../../chunk-pz8xe0qj.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},At={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return At;case g.Noble:return wt;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),A=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,A),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:w,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,w=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,w,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,w){let S=w??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),S=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,w=c||h?await _(await pt(a)):void 0,S=h&&w?await Mt({client:w,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,A=U(r.symbol),C=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(b.amount,A)})}let T={amount:[{amount:C.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),w=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?w:R(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),w=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as wn,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:A=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[A],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let b=(await Sn(i)(m)).filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).flatMap(({denom:A,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;try{return[In(T,C)]}catch{return[]}});if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=An.decode(n);return An.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,w=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(w,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),w=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:w,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),A=F(i,r),C=await L(l,y,{aminoTypes:A,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:A,signingClient:C}=await p(),T=(await A.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function w(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:A}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=A?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),A=(await y.getAccounts())?.[0]?.address;if(!A)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(A,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:w,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:we(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,At as DEFAULT_KUJI_FEE_MAINNET,wt as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
|