@swapkit/toolboxes 6.5.1 → 6.6.0

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 6.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#481](https://github.com/swapkit/sdk/pull/481) [`b09262a`](https://github.com/swapkit/sdk/commit/b09262a0113cbd09f3c2b08711008dfbd55a0e76) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Zcash transfers to ZIP-320 TEX addresses (`tex1…`), the format THORChain publishes its ZEC vault in, are now built instead of being rejected as invalid. TEX addresses are reported as their own `tex` address type, THORChain and Maya swaps accept them as the ZEC destination, and `toTransparentZcashAddress` converts one to the `t1` address it pays on chain.
8
+ - [#485](https://github.com/swapkit/sdk/pull/485) [`c380f81`](https://github.com/swapkit/sdk/commit/c380f812ad4e844a5a0782e020699b6d9ff5a10a) Thanks [@0xepicode](https://github.com/0xepicode)! - The UTXO toolbox's Blockchair host is now configurable via `SKConfig.set({ blockchairApiUrl })`. When set, every Blockchair read and broadcast routes through that host (the `/{chain-slug}` path is still appended), letting a consumer proxy the calls and keep the API key server-side instead of shipping it to the browser. Unset, it defaults to `https://api.blockchair.com` as before.
9
+ - [#477](https://github.com/swapkit/sdk/pull/477) [`efc495d`](https://github.com/swapkit/sdk/commit/efc495df7dfb7851876e5d8ca7567ce64070b494) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Selling from HyperCore now works through NEAR Intents as well as Flashnet, and each swap sends the funds to the account that provider credits.
10
+ - [#472](https://github.com/swapkit/sdk/pull/472) [`f960277`](https://github.com/swapkit/sdk/commit/f960277adc6f9f20807f732858324eef971cb397) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Solana token transfers now use the token program that owns the mint. Before, every transfer was built for the original SPL Token program, so transfers of Token-2022 tokens such as PYUSD failed with "incorrect program id". A mint that does not exist, or that neither program owns, now throws `toolbox_solana_unsupported_token_program` from `createTransaction`, `transfer` and `estimateTransactionFee`. `getBalanceFromRPC` also lists Token-2022 balances, and `checkPayerBalance` sizes a new Token-2022 token account like the payer's own.
11
+ - [#466](https://github.com/swapkit/sdk/pull/466) [`2957c2f`](https://github.com/swapkit/sdk/commit/2957c2fe6605b10b08e280acc0aefd43fb095d64) Thanks [@ice-chillios](https://github.com/ice-chillios)! - THORChain and Maya tokens whose denom contains more than one "/", such as staked RUJI (`x/staking-x/ruji`), now keep their full name. Their balances show under the right asset, and sending or depositing them uses the full denom instead of a cut-off one that the chain rejects. THORChain and Maya asset identifiers with an empty part, such as `THOR.ETH//ETH`, are now rejected with `helpers_invalid_asset_identifier` instead of being cut short.
12
+ - [#483](https://github.com/swapkit/sdk/pull/483) [`b717e30`](https://github.com/swapkit/sdk/commit/b717e309061c894fb7b6b9d27acffa1e58399efa) Thanks [@0xepicode](https://github.com/0xepicode)! - Transparent Zcash swaps now broadcast the extracted network transaction instead of the PCZT envelope. The toolbox signer discriminated the transaction it received with `instanceof ZcashPSBT` / `instanceof PCZT`, but the swap plugin builds that transaction through a dynamic import of `@swapkit/utxo-signer`, which a bundler can resolve to a different module instance than the toolbox's static import. The `instanceof` check then missed, the signer fell through to its generic branch, and the still-wrapped PSBT was broadcast as its PCZT envelope — which the network rejects. The signer now discriminates by shape — a PCZT and a ZcashPSBT both expose `extract`, a raw transaction does not — which is independent of class identity.
13
+ - [#484](https://github.com/swapkit/sdk/pull/484) [`c03235b`](https://github.com/swapkit/sdk/commit/c03235b7a06fc3c71c67c0407a2c8c5159b4cb17) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.4.2)
14
+
3
15
  ## 6.5.1
4
16
 
5
17
  ### Patch Changes
@@ -1 +1 @@
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};
1
+ import"../../chunk-pz8xe0qj.js";import{base64 as X,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function z(i){return X.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(X.decode(i)))}function ve(i){return X.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 X.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,e=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,t=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(e);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),t)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,t)}}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((e)=>({amount:e.amount,denom:e.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(e,t,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===e);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let A=vt({memo:c,messages:t,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=t.map((F)=>Pt(F,o.aminoTypes)),O=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(e,O),w=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),T=ln.decode(C.signature.signature);return{authInfoBytes:w,bodyBytes:A,signatures:[T]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(e,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:A,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:A,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 e={...ut,...n??{}},t=r.map((s)=>lt(s,e));return dt({memo:o,messages:t})}async function j(i,o,r={}){let n=typeof r==="string"?{}:r,e=_n(i),t=Nn(o,n);async function s(c,a){let p=await Dn(e,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await e.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(e,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,A=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((O)=>({amount:O.amount,denom:O.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await t.signWithRegistry(c,S,h,A,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(e,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,A){let S=A??await s(c);return t.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let A=await s(c),S=await t.signWithRegistry(c,a,p,h,A),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(e,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,e,t,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,e,t,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:e,sequence:t,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||t===void 0,A=c||h?await _(await pt(a)):void 0,S=h&&A?await Mt({client:A,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&e?{amount:[{amount:e.toString(),denom:l}],gas:y.gas}:y,O=U(r.symbol),C=r;if(c){if(!A)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await A.getAllBalances(i),denom:O,feeAmount:mn(b.amount,O)})}let w={amount:[{amount:C.getBaseValue("string"),denom:O}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:w}],sequence:t??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,e)=>e.denom.toLowerCase()===r?n+BigInt(e.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let e=r.toLowerCase(),t=o.find(({denom:a})=>a.toLowerCase()===e),s=BigInt(t?.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:e,decimals:t}=r,s=n?{chain:n}:{asset:e};return fn.from({...s,fromBaseDecimal:t,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import x from"protobufjs/minimal.js";var d=x.Reader,v=x.Writer,f=x.util,u=x.roots.default||(x.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}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,e){if(!e)e=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))e.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))e.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))e.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))e.uint32(32).bool(n.synth);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.Asset;while(n.pos<t){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 e=new u.common.Asset;if(n.chain!=null)e.chain=String(n.chain);if(n.symbol!=null)e.symbol=String(n.symbol);if(n.ticker!=null)e.ticker=String(n.ticker);if(n.synth!=null)e.synth=Boolean(n.synth);return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.defaults)t.chain="",t.symbol="",t.ticker="",t.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))t.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))t.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))t.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))t.synth=n.synth;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}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,e){if(!e)e=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,e.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))e.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))e.uint32(24).int64(n.decimals);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.Coin;while(n.pos<t){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 e=u.common.Asset.verify(n.asset);if(e)return"asset."+e}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 e=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");e.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)e.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(e.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")e.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")e.decimals=n.decimals;else if(typeof n.decimals==="object")e.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.defaults)if(t.asset=null,t.amount="",f.Long){let s=new f.Long(0,0,!1);t.decimals=e.longs===String?s.toString():e.longs===Number?s.toNumber():s}else t.decimals=e.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))t.asset=u.common.Asset.toObject(n.asset,e);if(n.amount!=null&&n.hasOwnProperty("amount"))t.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")t.decimals=e.longs===String?String(n.decimals):n.decimals;else t.decimals=e.longs===String?f.Long.prototype.toString.call(n.decimals):e.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,e){if(!e)e=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))e.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))e.uint32(18).string(n.ed25519);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.PubKeySet;while(n.pos<t){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 e=new u.common.PubKeySet;if(n.secp256k1!=null)e.secp256k1=String(n.secp256k1);if(n.ed25519!=null)e.ed25519=String(n.ed25519);return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.defaults)t.secp256k1="",t.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))t.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))t.ed25519=n.ed25519;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}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,e){if(!e)e=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))e.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))e.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))e.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))e.uint32(34).string(n.toAddress);if(n.coins?.length)for(let t=0;t<n.coins.length;++t)u.common.Coin.encode(n.coins[t],e.uint32(42).fork()).ldelim();if(n.gas?.length)for(let t=0;t<n.gas.length;++t)u.common.Coin.encode(n.gas[t],e.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))e.uint32(58).string(n.memo);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.Tx;while(n.pos<t){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 e=0;e<n.coins.length;++e){let t=u.common.Coin.verify(n.coins[e]);if(t)return"coins."+t}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let e=0;e<n.gas.length;++e){let t=u.common.Coin.verify(n.gas[e]);if(t)return"gas."+t}}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 e=new u.common.Tx;if(n.id!=null)e.id=String(n.id);if(n.chain!=null)e.chain=String(n.chain);if(n.fromAddress!=null)e.fromAddress=String(n.fromAddress);if(n.toAddress!=null)e.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");e.coins=[];for(let t=0;t<n.coins.length;++t){if(typeof n.coins[t]!=="object")throw TypeError(".common.Tx.coins: object expected");e.coins[t]=u.common.Coin.fromObject(n.coins[t])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");e.gas=[];for(let t=0;t<n.gas.length;++t){if(typeof n.gas[t]!=="object")throw TypeError(".common.Tx.gas: object expected");e.gas[t]=u.common.Coin.fromObject(n.gas[t])}}if(n.memo!=null)e.memo=String(n.memo);return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.arrays||e.defaults)t.coins=[],t.gas=[];if(e.defaults)t.id="",t.chain="",t.fromAddress="",t.toAddress="",t.memo="";if(n.id!=null&&n.hasOwnProperty("id"))t.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))t.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))t.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))t.toAddress=n.toAddress;if(n.coins?.length){t.coins=[];for(let s=0;s<n.coins.length;++s)t.coins[s]=u.common.Coin.toObject(n.coins[s],e)}if(n.gas?.length){t.gas=[];for(let s=0;s<n.gas.length;++s)t.gas[s]=u.common.Coin.toObject(n.gas[s],e)}if(n.memo!=null&&n.hasOwnProperty("memo"))t.memo=n.memo;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,e){if(!e)e=v.create();if(n.coins?.length)for(let t=0;t<n.coins.length;++t)u.common.Coin.encode(n.coins[t],e.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))e.uint32(18).string(n.poolDeduct);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.Fee;while(n.pos<t){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 e=0;e<n.coins.length;++e){let t=u.common.Coin.verify(n.coins[e]);if(t)return"coins."+t}}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 e=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");e.coins=[];for(let t=0;t<n.coins.length;++t){if(typeof n.coins[t]!=="object")throw TypeError(".common.Fee.coins: object expected");e.coins[t]=u.common.Coin.fromObject(n.coins[t])}}if(n.poolDeduct!=null)e.poolDeduct=String(n.poolDeduct);return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.arrays||e.defaults)t.coins=[];if(e.defaults)t.poolDeduct="";if(n.coins?.length){t.coins=[];for(let s=0;s<n.coins.length;++s)t.coins[s]=u.common.Coin.toObject(n.coins[s],e)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))t.poolDeduct=n.poolDeduct;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,e){if(!e)e=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))e.uint32(10).string(n.value);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.common.ProtoUint;while(n.pos<t){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 e=new u.common.ProtoUint;if(n.value!=null)e.value=String(n.value);return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.defaults)t.value="";if(n.value!=null&&n.hasOwnProperty("value"))t.value=n.value;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}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,e){if(!e)e=v.create();if(n.coins?.length)for(let t=0;t<n.coins.length;++t)u.common.Coin.encode(n.coins[t],e.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))e.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))e.uint32(26).bytes(n.signer);return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.types.MsgDeposit;while(n.pos<t){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 e=0;e<n.coins.length;++e){let t=u.common.Coin.verify(n.coins[e]);if(t)return"coins."+t}}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 e=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");e.coins=[];for(let t=0;t<n.coins.length;++t){if(typeof n.coins[t]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");e.coins[t]=u.common.Coin.fromObject(n.coins[t])}}if(n.memo!=null)e.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,e.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)e.signer=n.signer}return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.arrays||e.defaults)t.coins=[];if(e.defaults){if(t.memo="",e.bytes===String)t.signer="";else if(t.signer=[],e.bytes!==Array)t.signer=f.newBuffer(t.signer)}if(n.coins?.length){t.coins=[];for(let s=0;s<n.coins.length;++s)t.coins[s]=u.common.Coin.toObject(n.coins[s],e)}if(n.memo!=null&&n.hasOwnProperty("memo"))t.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))t.signer=e.bytes===String?f.base64.encode(n.signer,0,n.signer.length):e.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),e=0;e<n.length;++e)if(r[n[e]]!=null)this[n[e]]=r[n[e]]}}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,e){if(!e)e=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))e.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))e.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let t=0;t<n.amount.length;++t)u.cosmos.base.v1beta1.Coin.encode(n.amount[t],e.uint32(26).fork()).ldelim();return e},o.encodeDelimited=function(n,e){return this.encode(n,e).ldelim()},o.decode=function(n,e){if(!(n instanceof d))n=d.create(n);let t=e===void 0?n.len:n.pos+e,s=new u.types.MsgSend;while(n.pos<t){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 e=0;e<n.amount.length;++e){let t=u.cosmos.base.v1beta1.Coin.verify(n.amount[e]);if(t)return"amount."+t}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let e=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,e.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)e.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,e.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)e.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");e.amount=[];for(let t=0;t<n.amount.length;++t){if(typeof n.amount[t]!=="object")throw TypeError(".types.MsgSend.amount: object expected");e.amount[t]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[t])}}return e},o.toObject=function(n,e){if(!e)e={};let t={};if(e.arrays||e.defaults)t.amount=[];if(e.defaults){if(e.bytes===String)t.fromAddress="";else if(t.fromAddress=[],e.bytes!==Array)t.fromAddress=f.newBuffer(t.fromAddress);if(e.bytes===String)t.toAddress="";else if(t.toAddress=[],e.bytes!==Array)t.toAddress=f.newBuffer(t.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))t.fromAddress=e.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):e.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))t.toAddress=e.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):e.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){t.amount=[];for(let s=0;s<n.amount.length;++s)t.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],e)}return t},o.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(e){if(e){for(let t=Object.keys(e),s=0;s<t.length;++s)if(e[t[s]]!=null)this[t[s]]=e[t[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(t){return new n(t)},n.encode=function(t,s){if(!s)s=v.create();if(t.denom!=null&&Object.hasOwnProperty.call(t,"denom"))s.uint32(10).string(t.denom);if(t.amount!=null&&Object.hasOwnProperty.call(t,"amount"))s.uint32(18).string(t.amount);return s},n.encodeDelimited=function(t,s){return this.encode(t,s).ldelim()},n.decode=function(t,s){if(!(t instanceof d))t=d.create(t);let c=s===void 0?t.len:t.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(t.pos<c){let p=t.uint32();switch(p>>>3){case 1:a.denom=t.string();break;case 2:a.amount=t.string();break;default:t.skipType(p&7);break}}return a},n.decodeDelimited=function(t){if(!(t instanceof d))t=new d(t);return this.decode(t,t.uint32())},n.verify=function(t){if(typeof t!=="object"||t===null)return"object expected";if(t.denom!=null&&t.hasOwnProperty("denom")){if(!f.isString(t.denom))return"denom: string expected"}if(t.amount!=null&&t.hasOwnProperty("amount")){if(!f.isString(t.amount))return"amount: string expected"}return null},n.fromObject=function(t){if(t instanceof u.cosmos.base.v1beta1.Coin)return t;let s=new u.cosmos.base.v1beta1.Coin;if(t.denom!=null)s.denom=String(t.denom);if(t.amount!=null)s.amount=String(t.amount);return s},n.toObject=function(t,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(t.denom!=null&&t.hasOwnProperty("denom"))c.denom=t.denom;if(t.amount!=null&&t.hasOwnProperty("amount"))c.amount=t.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(e){if(e){for(let t=Object.keys(e),s=0;s<t.length;++s)if(e[t[s]]!=null)this[t[s]]=e[t[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(t){return new n(t)},n.encode=function(t,s){if(!s)s=v.create();if(t.denom!=null&&Object.hasOwnProperty.call(t,"denom"))s.uint32(10).string(t.denom);if(t.amount!=null&&Object.hasOwnProperty.call(t,"amount"))s.uint32(18).string(t.amount);return s},n.encodeDelimited=function(t,s){return this.encode(t,s).ldelim()},n.decode=function(t,s){if(!(t instanceof d))t=d.create(t);let c=s===void 0?t.len:t.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(t.pos<c){let p=t.uint32();switch(p>>>3){case 1:a.denom=t.string();break;case 2:a.amount=t.string();break;default:t.skipType(p&7);break}}return a},n.decodeDelimited=function(t){if(!(t instanceof d))t=new d(t);return this.decode(t,t.uint32())},n.verify=function(t){if(typeof t!=="object"||t===null)return"object expected";if(t.denom!=null&&t.hasOwnProperty("denom")){if(!f.isString(t.denom))return"denom: string expected"}if(t.amount!=null&&t.hasOwnProperty("amount")){if(!f.isString(t.amount))return"amount: string expected"}return null},n.fromObject=function(t){if(t instanceof u.cosmos.base.v1beta1.DecCoin)return t;let s=new u.cosmos.base.v1beta1.DecCoin;if(t.denom!=null)s.denom=String(t.denom);if(t.amount!=null)s.amount=String(t.amount);return s},n.toObject=function(t,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(t.denom!=null&&t.hasOwnProperty("denom"))c.denom=t.denom;if(t.amount!=null&&t.hasOwnProperty("amount"))c.amount=t.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(e){if(e){for(let t=Object.keys(e),s=0;s<t.length;++s)if(e[t[s]]!=null)this[t[s]]=e[t[s]]}}return n.prototype.int="",n.create=function(t){return new n(t)},n.encode=function(t,s){if(!s)s=v.create();if(t.int!=null&&Object.hasOwnProperty.call(t,"int"))s.uint32(10).string(t.int);return s},n.encodeDelimited=function(t,s){return this.encode(t,s).ldelim()},n.decode=function(t,s){if(!(t instanceof d))t=d.create(t);let c=s===void 0?t.len:t.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(t.pos<c){let p=t.uint32();switch(p>>>3){case 1:a.int=t.string();break;default:t.skipType(p&7);break}}return a},n.decodeDelimited=function(t){if(!(t instanceof d))t=new d(t);return this.decode(t,t.uint32())},n.verify=function(t){if(typeof t!=="object"||t===null)return"object expected";if(t.int!=null&&t.hasOwnProperty("int")){if(!f.isString(t.int))return"int: string expected"}return null},n.fromObject=function(t){if(t instanceof u.cosmos.base.v1beta1.IntProto)return t;let s=new u.cosmos.base.v1beta1.IntProto;if(t.int!=null)s.int=String(t.int);return s},n.toObject=function(t,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(t.int!=null&&t.hasOwnProperty("int"))c.int=t.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,x.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(e){if(e){for(let t=Object.keys(e),s=0;s<t.length;++s)if(e[t[s]]!=null)this[t[s]]=e[t[s]]}}return n.prototype.dec="",n.create=function(t){return new n(t)},n.encode=function(t,s){if(!s)s=v.create();if(t.dec!=null&&Object.hasOwnProperty.call(t,"dec"))s.uint32(10).string(t.dec);return s},n.encodeDelimited=function(t,s){return this.encode(t,s).ldelim()},n.decode=function(t,s){if(!(t instanceof d))t=d.create(t);let c=s===void 0?t.len:t.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(t.pos<c){let p=t.uint32();switch(p>>>3){case 1:a.dec=t.string();break;default:t.skipType(p&7);break}}return a},n.decodeDelimited=function(t){if(!(t instanceof d))t=new d(t);return this.decode(t,t.uint32())},n.verify=function(t){if(typeof t!=="object"||t===null)return"object expected";if(t.dec!=null&&t.hasOwnProperty("dec")){if(!f.isString(t.dec))return"dec: string expected"}return null},n.fromObject=function(t){if(t instanceof u.cosmos.base.v1beta1.DecProto)return t;let s=new u.cosmos.base.v1beta1.DecProto;if(t.dec!=null)s.dec=String(t.dec);return s},n.toObject=function(t,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(t.dec!=null&&t.hasOwnProperty("dec"))c.dec=t.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,x.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 E(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function I(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:e,...t})=>({...t,signer:z(e)}),toAmino:({signer:e,...t})=>({...t,signer:typeof e==="string"?Q(e,o):e})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:e,to_address:t,...s})=>({...s,fromAddress:z(e),toAddress:z(t)}),toAmino:({fromAddress:e,toAddress:t,...s})=>({...s,from_address:typeof e==="string"?Q(e,o):e,to_address:typeof t==="string"?Q(t,o):t})}};return Object.assign(n,{fromAmino(e){let t=Object.entries(n).find(([,a])=>a.aminoType===e.type);if(!t)throw TypeError(`No converter for amino type ${e.type}`);let[s,c]=t;return{typeUrl:s,value:c.fromAmino(e.value)}},toAmino(e){let t=n[e.typeUrl];if(!t)throw TypeError(`No converter for type URL ${e.typeUrl}`);return{type:t.aminoType,value:t.toAmino(e.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 R=(i,o)=>{let r=I(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:e,asSignable:t,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:e}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:t,assetValue:p,memo:n,recipient:r,sender:e,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:t,assetValue:p,memo:n,sender:e,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),t=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:t,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:e=!0,asAminoMessage:t=!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),A=Ln({assetValue:r,recipient:o,sender:i}),S=e?R(t?A:K(A),a):A;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:e=!1,sequence:t,accountNumber:s}){let c=o.chain,a=s!==void 0&&t!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),A=n?R(e?h:K(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[A],sequence:t??Number(a?.sequence)}}function K(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.symbol.indexOf("/"),[e,t]=r.isSynthetic?[r.symbol.slice(0,n),r.symbol.slice(n+1)]:[r.chain,r.symbol],s=t.split("-")[0]??t;return{...o,asset:{chain:e.toUpperCase(),symbol:t.toUpperCase(),synth:r.isSynthetic,ticker:s.toUpperCase()}}})}}}function on({chain:i,memo:o,msgs:r}){let n=E(),e=I(i),s=r.map((c)=>{let a=En(e,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 k,CosmosChainPrefixes as Xn,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 Xt}from"@swapkit/helpers";import{SwapKitApi as zn}from"@swapkit/helpers/api";import{PubKey as zt}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 zn.getGasRate()).find((e)=>e.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 e=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:e.signature,signed:{accountNumber:e.signed.accountNumber,authInfoBytes:e.signed.authInfoBytes,bodyBytes:e.signed.bodyBytes,chainId:e.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,e=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(e)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[k.Cosmos]:1000,[k.Kujira]:1000,[k.Noble]:1000,[k.THORChain]:5000000,[k.Maya]:5000000,[k.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:e}){let t=await i(e);if(!t?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=t.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?zt.decode(t.pubkey.value).key:t.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=Xn[i],n="index"in o?o.index||0:0,e=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:Xt(Yt[i],{index:n})),t;async function s(){if(t)return t;return t=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:e,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),t}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 j(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function A(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 j(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:O=Tn.Fast,sweep:C}){let w=await s(),T=await a();if(!(w&&T))throw new N("toolbox_cosmos_signer_not_defined");let F=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[O],H,i),cn=await j(F,w),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(T),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(T,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(e),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let y=[k.THORChain,k.Maya].includes(i),b=(w)=>y&&!w.toUpperCase().startsWith("X/")&&w.split("-").length>2,C=(await Sn(i)(m)).filter(({denom:w})=>w&&!w.includes("IBC/")&&!b(w)).flatMap(({denom:w,amount:T})=>{let F=y&&(w.includes("/")||w.includes("˜"))?`${i}.${w}`:w;try{return[In(F,T)]}catch{return[]}});if(C.length===0)return[On.from({chain:i})];return C},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:A,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await zn.getGasRate()).find((e)=>e.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),e=await Qn(r,o);return{average:wn.fromBigInt(BigInt(e),n),fast:wn.fromBigInt(BigInt($n(e,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(e,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{[k.Cosmos]:0.007,[k.Kujira]:0.02,[k.Noble]:0.01,[k.THORChain]:0.02,[k.Maya]:0.02,[k.Harbor]:0.02}[i]||0}function oe(i){let o=Xn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:e,words:t}=An.decode(n);return An.encode(e,t)===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),t=Et.fromMasterSeed(n).derive(i);if(!t.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(t.privateKey,!0),Uint8Array.from(t.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 L,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 L("toolbox_cosmos_signer_not_defined");let e=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:e.signature,signed:e.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,e=0){let t=await ue({hdPath:`${o}/${e}`,mnemonic:n,prefix:i});return he(t)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:e}){let{msgs:t,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof e==="string"?JSON.parse(e):e,A=(await n.getAccounts())?.[0]?.address||"",S=I(i,o),m=E(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of t){let w=R(C,i);y.push(w)}let{signatures:[b]}=await l.sign(A,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:t.map(K)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new L("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,e,t,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),A=it(t,s),S=e.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:A,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,e="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),t=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>t.getSignerFromPhrase({derivationPath:e,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 L("toolbox_cosmos_no_signer");let b=E(),O=I(i,r),C=await j(l,y,{aminoTypes:O,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:O,signingClient:C}=await p(),w=(await O.getAccounts())?.[0]?.address;if(!w)throw new L("toolbox_cosmos_signer_not_defined");let T=await C.signAndBroadcast(w,b,l,y);if(T.code!==0)throw new L("core_swap_transaction_error",{code:T.code,message:T.rawLog});return T.transactionHash}async function A(){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:O}){let{signer:C,signingClient:w}=await p(),T=(await C.getAccounts())?.[0]?.address;if(!T)throw new L("toolbox_cosmos_no_signer");let F="signAmino"in C,sn=O?await bn({assetValue:l,sender:T}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:T});if(F){let J=R(H,i),{signatures:kn,authInfoBytes:an}=await w.sign(T,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(K)}),signatures:kn});return(await w.broadcastTx(un)).transactionHash}let G=K(H),cn=R(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),O=(await y.getAccounts())?.[0]?.address;if(!O)throw new L("toolbox_cosmos_signer_not_defined");return b.sign(O,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...t,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:R,createDefaultAminoTypes:()=>I(i,r),createDefaultRegistry:E,createMultisig:it,createTransaction:Jn,deposit:S,getFees:A,importSignature:Ce,parseAminoMessageForDirectSigning:K,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(e),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,z as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,R as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,I as createDefaultAminoTypes,E as createDefaultRegistry,Bn as createOfflineStargateClient,j 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,K as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
@@ -1 +1 @@
1
- import"../../chunk-qsbf0z90.js";import{m as Te,r as we}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function Sn({builder:e,grouping:n="na",orders:t}){return{builder:e,grouping:n,orders:t,type:"order"}}function Tn({cancels:e}){return{cancels:e,type:"cancel"}}function wn({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Un({oid:e,order:n}){return{oid:e,order:n,type:"modify"}}function _n({modifies:e}){return{modifies:e,type:"batchModify"}}function Dn({asset:e,isCross:n,leverage:t}){return{asset:e,isCross:n,leverage:t,type:"updateLeverage"}}function On({asset:e,isBuy:n,ntli:t}){return{asset:e,isBuy:n,ntli:t,type:"updateIsolatedMargin"}}function kn({asset:e,leverage:n}){return{asset:e,leverage:n,type:"topUpIsolatedOnlyMargin"}}function Pn({time:e}){return{time:e,type:"scheduleCancel"}}function vn({amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:n,nonce:t,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function oe({amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:n,destinationDex:t,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rn({agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:n,hyperliquidChain:t,nonce:r,signatureChainId:i,type:"approveAgent"}}function In({builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:n,maxFeeRate:t,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qn({hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:n,nonce:t,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as We,SwapKitNumber as Ve}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Ne,Signature as Me}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Fe={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},Le={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},ae="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},je=new TextEncoder;function b(...e){let n=e.reduce((i,o)=>i+o.length,0),t=new Uint8Array(n),r=0;for(let i of e)t.set(i,r),r+=i.length;return t}function Ee(e,n,t){if(t<n)return new Uint8Array([e+t]);if(t<=255)return new Uint8Array([e+n,t]);if(t<=65535)return new Uint8Array([e+n+1,t>>8,t&255]);return new Uint8Array([e+n+2,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function v(e,n){let t=new Uint8Array(n),r=e;for(let i=n-1;i>=0;i-=1)t[i]=Number(r&0xffn),r>>=8n;return t}function se(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function pe(e){let n=je.encode(e);if(n.length<32)return b(new Uint8Array([160+n.length]),n);return b(Ee(217,0,n.length),n)}function Je(e){let n=e.map((r)=>Y(r)),t=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,...n)}function ze(e){let n=Object.entries(e).filter(([,r])=>typeof r<"u"),t=n.length<16?new Uint8Array([128+n.length]):n.length<=65535?new Uint8Array([222,n.length>>8,n.length&255]):new Uint8Array([223,n.length>>>24&255,n.length>>>16&255,n.length>>>8&255,n.length&255]);return b(t,...n.flatMap(([r,i])=>[pe(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return pe(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return se(BigInt(e))}if(typeof e==="bigint")return se(e);if(e instanceof Uint8Array){let n=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,e)}if(Array.isArray(e))return Je(e);if(typeof e==="object")return ze(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function Ke(e){let n=e.startsWith("0x")?e.slice(2):e;if(n.length%2!==0||/[^a-fA-F0-9]/u.test(n))throw new V("helpers_invalid_params",{hexValue:e});let t=new Uint8Array(n.length/2);for(let r=0;r<n.length;r+=2)t[r/2]=Number.parseInt(n.slice(r,r+2),16);return t}function ce(e){return{domain:Fe,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...Le.Agent]}}}function de(e){let n=G[e.type],t=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||ae},primaryType:n,types:{[n]:t}}}function ye(e){let n=Me.from(e);return{r:n.r,s:n.s,v:n.v}}function ue(e,n,{expiresAfter:t,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(n),8),s=r?b(new Uint8Array([1]),Ke(r.toLowerCase())):new Uint8Array([0]),p=typeof t==="number"?b(new Uint8Array([0]),v(BigInt(t),8)):new Uint8Array;return Ne(b(i,o,s,p))}function le(e){let n=e.hyperliquidChain||ae;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:n};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:n};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:n};case"tokenDelegate":return{...e,hyperliquidChain:n,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:n};default:return e}}var ge=Number.parseInt(D,16),Qe=new Set(["chainId","name","verifyingContract","version"]),fe=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new We("toolbox_hypercore_payload_mismatch",{problems:[e]})};function me(e){try{return new URL(e)}catch{return}}function Ce({action:e,allowedEndpoints:n,expectedAmount:t,expectedDestination:r,expectedFromSubAccount:i,expectedSourceDex:o,expectedToken:s,submitTo:p,typedData:u}){let{domain:f,message:T,primaryType:m,types:H}=u,a=G.sendAsset;if(m!==a)c(`primaryType is ${JSON.stringify(m)}, expected "${a}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let y=X.map(({name:d})=>d),C=new Set([...y,"signatureChainId","type"]),x=Object.keys(e).filter((d)=>!C.has(d));if(x.length)c(`action carries unexpected keys: ${x.join(", ")}`);for(let{name:d}of X)if(T[d]!==e[d])c(`${d}: signed ${JSON.stringify(T[d])} != submitted ${JSON.stringify(e[d])}`);let A=Object.keys(T),l=A.filter((d)=>!y.includes(d)),S=y.filter((d)=>!A.includes(d));if(l.length||S.length){let d=[l.length?`declares undeclared keys [${l.join(",")}]`:"",S.length?`is missing keys [${S.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${d}`)}let _=X.map(({name:d,type:W})=>`${d}:${W}`).join(","),w=(H[a]??[]).map(({name:d,type:W})=>`${d}:${W}`).join(",");if(w!==_)c(`types.${a} is [${w}], expected [${_}]`);let R=Object.keys(H).filter((d)=>d!==a&&d!=="EIP712Domain");if(R.length)c(`types carries unexpected entries: ${R.join(", ")}`);if(Number(f.chainId)!==ge)c(`domain.chainId is ${f.chainId}, expected ${ge} (Arbitrum)`);if(f.name!==q.name)c(`domain.name is ${JSON.stringify(f.name)}, expected "${q.name}"`);if(f.version!==q.version)c(`domain.version is ${JSON.stringify(f.version)}, expected "${q.version}"`);if(f.verifyingContract!==I)c(`domain.verifyingContract is ${f.verifyingContract}, expected the zero address`);let P=Object.keys(f).filter((d)=>!Qe.has(d));if(P.length)c(`domain carries unexpected keys: ${P.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(e.destinationDex!=="")c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ""`);if(s!==B)c(`route sell token is ${JSON.stringify(s)}, expected "${B}"`);if(e.token!==s)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${s}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==o)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(o)}`);let L=e.fromSubAccount;if(typeof L!=="string"||typeof i!=="string"||L.toLowerCase()!==i.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(i)}`);if(i&&!fe.test(i))c(`expectedFromSubAccount ${JSON.stringify(i)} is not a well-formed 0x address`);if(!t)c("expectedAmount is missing — cannot verify action.amount");let j=!1;try{j=new Ve(String(e.amount)).eqValue(t)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${t}`)}if(!j)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${t}`);let z=typeof e.destination==="string"?e.destination:"";if(!fe.test(z))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(z.toLowerCase()!==r.toLowerCase())c(`action.destination ${z} != expected destination ${r}`);let re=me(p),K=re?.origin,ie=n.flatMap((d)=>me(d)?.origin??[]);if(re?.protocol!=="https:")c(`submitTo ${JSON.stringify(p)} must be an https URL`);if(!K||!ie.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${ie.join(", ")}]`)}import{AssetValue as M,Chain as Ge,derivationPathToString as Ye,getChainConfig as Ue,getRPCUrl as Xe,NetworkDerivationPath as Ze,RequestClient as N,SwapKitError as g,SwapKitNumber as O,updateDerivationPath as en}from"@swapkit/helpers";import{SwapKitApi as nn}from"@swapkit/helpers/api";import{HDNodeWallet as tn}from"ethers";import{match as rn,P as Z}from"ts-pattern";var U=Ge.Hype,{baseDecimal:ee,rpcUrls:Ae}=Ue(U),on=Ae[0]?`${Ae[0]}/exchange`:void 0,sn={HYPE:ee,USDC:6,USDT:6},_e="Mainnet",an=/^\d+(?:\.\d+)?$/,pn=/^[^:]+:0x[0-9a-fA-F]+$/,cn={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dn={spotSend:"HyperliquidTransaction:SpotSend"};function h(e,n){if(!$e(e))throw new g(n,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var De={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...n}){let t=await E();return N.post(`${t}/info`,{json:n,...e})}function ne({dex:e,user:n}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:h(n,"helpers_invalid_params")})}function Oe({user:e}){return k({type:"spotClearinghouseState",user:h(e,"helpers_invalid_params")})}function yn({destination:e,sender:n}){let t=h(n,"helpers_invalid_params"),r=h(e,"helpers_invalid_params");return k({requestOptions:De,source:t,type:"preTransferCheck",user:r})}function un({dex:e,user:n}){return k({...e?{dex:e}:{},type:"openOrders",user:h(n,"helpers_invalid_params")})}function ln({dex:e,user:n}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:h(n,"helpers_invalid_params")})}function gn({oidOrCloid:e,user:n}){return k({oid:e,type:"orderStatus",user:h(n,"helpers_invalid_params")})}function fn({aggregateByTime:e,user:n}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:h(n,"helpers_invalid_params")})}function mn({aggregateByTime:e,endTime:n,startTime:t,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof n==="number"?{endTime:n}:{},startTime:t,type:"userFillsByTime",user:h(r,"helpers_invalid_params")})}function he({coin:e,token:n,value:t,spotMeta:r}){if(!t||Number(t)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${n||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||n!==void 0&&u.index===Number(n)),s=o?.weiDecimals??sn[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:t})}function Cn(e){let n=new Map;for(let t of e){let r=t.toString({includeSynthProtocol:!0}),i=n.get(r);n.set(r,i?i.add(t):t)}if(![...n.values()].some((t)=>t.isGasAsset||t.ticker==="HYPE")){let t=M.from({chain:U,value:0});n.set(t.toString({includeSynthProtocol:!0}),t)}return[...n.values()]}async function E(){try{return await Xe(U)}catch{let[e]=Ue(U).rpcUrls;if(!e)throw new g("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function An(e){let n=dn[e.type],{type:t,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:n,types:{[n]:cn[t]}}}async function hn({action:e,expiresAfter:n,nonce:t,vaultAddress:r}){let i=t||Date.now(),o=r?h(r,"helpers_invalid_params"):void 0,s=await J(),p=ue(e,i,{expiresAfter:n,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:n,nonce:i,typedData:ce(p),vaultAddress:o}}async function ke({action:e,endpoint:n,nonce:t,signatureChainId:r}){let i=t||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=le({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:n??await J(),nonce:i,typedData:de(s)}}async function te({token:e,user:n}){let t=await Oe({user:n}),i=(t.spotState?.balances||t.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function Pe({assetValue:e,sender:n,token:t}){let r=(await te({token:t,user:n}))?.getValue("string");if(!r||Number(r)<=0)throw new g("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Hn(e){if(e.address&&pn.test(e.address))return e.address;let t=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(t)return`${t.name}:${t.tokenId}`;throw new g("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function ve({destination:e,sender:n}){let t;try{t=await yn({destination:e,sender:n})}catch(o){throw new g("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof t?.isSanctioned!=="boolean"||typeof t.userExists!=="boolean")throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});let{fee:r}=t,i=typeof r==="string"&&an.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:t});if(t.isSanctioned)throw new g("toolbox_hypercore_destination_sanctioned",{destination:e,sender:n});return i}function Re(e){return e.toUpperCase().startsWith("USDC:")}async function Ie({activationFee:e,token:n,user:t}){if(e<=0)return;let[r,i]=await Promise.all([ne({user:t}),te({token:B,user:t})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new g("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:n})}async function qe({activationFee:e,amount:n,sourceDex:t,token:r,user:i}){let o=Re(r),s=o?new O(n).add(e):new O(n);if(t!==void 0&&t!==""&&t!=="spot")throw new g("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:t});if(!o&&t==="")throw new g("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:t,token:r});let p="0";if(o&&t!=="spot"){if(p=(await ne({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(t==="")throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await te({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await Ie({activationFee:e,token:r,user:i});return"spot"}throw new g("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xn({amount:e,destination:n,sender:t,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new g("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await ve({destination:n,sender:t});if(!i){let u=await qe({activationFee:s,amount:e,sourceDex:r,token:o,user:t});return{amount:e,sourceDex:u}}if(!Re(o))return await Ie({activationFee:s,token:o,user:t}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new g("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bn({assetValue:e,recipient:n,sender:t,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=h(n,"core_transaction_invalid_recipient_address"),u=h(t,"core_transaction_invalid_sender_address"),f=e.address;if(!f)throw new g("helpers_invalid_params",{asset:e.toString(),from:u});let T=i?await Pe({assetValue:e,sender:u,token:f}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:T,destination:p,hyperliquidChain:_e,signatureChainId:r||D,time:H,token:f,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:An(a)}}async function He({assetValue:e,destinationDex:n,endpoint:t,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:f}){let T=h(i,"core_transaction_invalid_recipient_address"),m=h(o,"core_transaction_invalid_sender_address"),H=r?h(r,"helpers_invalid_params"):"",a=H||m,y=await Hn(e),C=u?await Pe({assetValue:e,sender:a,token:y}):e.getValue("string"),{amount:x,sourceDex:A}=await xn({amount:C,destination:T,sender:a,sourceDex:p,sweep:u,token:y}),l=oe({amount:x,destination:T,destinationDex:n??"spot",fromSubAccount:H,hyperliquidChain:_e,nonce:f||Date.now(),signatureChainId:s||D,sourceDex:A,token:y});return ke({action:l,endpoint:t})}async function Be(e){let n=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(n?.status!=="ok")throw new g("core_transaction_failed",{definitive:n?.status==="err",response:n});return n}async function xe({amount:e,destination:n,nonce:t,token:r,user:i}){let o=h(i,"helpers_invalid_params"),s=await E(),p=t-5000,u=n?.toLowerCase(),f=r?.toUpperCase(),T=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===t))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(f!==void 0){if(!m?.token)return!1;let y=m.token.toUpperCase();if(y!==f&&!f.startsWith(`${y}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...De}),a=Array.isArray(H)?H.find(T):void 0;if(a?.hash)return a.hash}catch{}}return""}async function be({kind:e,lookup:n,signed:t}){try{await Be(t)}catch(i){if(i instanceof g&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await xe(n);if(s)return s;throw new g("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:n.nonce,transportError:String(i)})}let r=await xe(n);if(!r)throw new g("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:n.nonce});return r}function Se({action:e,nonce:n,user:t}){return{amount:e.amount,destination:e.destination,nonce:n,token:e.token,user:t}}function $e(e){return e.startsWith("0x")&&we(e)}function Xn(e){let n=e&&"index"in e?e.index||0:0,t=Ye(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:en(Ze[U],{index:n})),r,i=!1;function o(){if(i)return r;return r=rn(e).with({phrase:Z.string},({phrase:a})=>tn.fromPhrase(a,void 0,t)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let C=Te(a.typedData),x=await y.signTypedData(C.domain,C.types,C.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ye(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let y=h(a,"helpers_invalid_params"),C=await E(),[x,A,l]=await Promise.all([N.post(`${C}/info`,{json:{type:"spotClearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"clearinghouseState",user:y}}),N.post(`${C}/info`,{json:{type:"spotMeta"}})]),S=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>he({coin:w,spotMeta:l,token:R,value:P})).filter((w)=>!!w),_=he({coin:"USDC",spotMeta:l,value:A.withdrawable||A.marginSummary?.accountValue||A.marginSummary?.totalRawUsd});return Cn(_?[...S,_]:S)}async function f(a,y=!0){let C=h(a,"helpers_invalid_params");try{let x=await nn.getChainBalance({address:C,chain:U,scamFilter:y});if(x.length){let A=x.map(({identifier:S,value:_,decimal:w})=>new M({decimal:w||ee,identifier:S,value:_}));return A.some((S)=>S.isGasAsset)?A:[M.from({chain:U}),...A]}}catch{}return u(C)}async function T({sweep:a,...y}){let C=o();if(!C)throw new g("toolbox_hypercore_no_signer");let x=y.sender||await C.getAddress(),A=await He({...y,feeRate:0,sender:x,sweep:a}),l=await p(A);return be({kind:"transfer",lookup:Se({action:A.action,nonce:A.nonce,user:A.action.fromSubAccount||x}),signed:l})}async function m(a){let y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let{action:C,typedData:x,...A}=a,l=structuredClone(C),S=structuredClone(x),_=await y.getAddress(),w=await J(),R=[...new Set([w,on??w])];Ce({...A,action:l,allowedEndpoints:R,typedData:S});let P=l.fromSubAccount?h(l.fromSubAccount,"helpers_invalid_params"):_,L=await ve({destination:l.destination,sender:P});await qe({activationFee:L,amount:l.amount,sourceDex:l.sourceDex,token:l.token,user:P});let j=await p({action:l,endpoint:w,nonce:l.nonce,typedData:S});return be({kind:"payin",lookup:Se({action:l,nonce:l.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:hn,createSendAssetTransaction:He,createTransaction:bn,createUserSignedActionRequest:ke,estimateTransactionFee:H,getAddress:s,getBalance:f,getBalanceFromChain:u,getState:{clearinghouse:ne,frontendOpenOrders:ln,openOrders:un,orderStatus:gn,spotClearinghouse:Oe,userFills:fn,userFillsByTime:mn},signAndBroadcastSendAsset:m,signTransaction:p,transfer:T,validateAddress:$e}}export{B as HYPERCORE_USDC_TOKEN_ID,Rn as buildApproveAgentAction,In as buildApproveBuilderFeeAction,_n as buildBatchModifyAction,Tn as buildCancelAction,wn as buildCancelByCloidAction,Un as buildModifyAction,Sn as buildOrderAction,Pn as buildScheduleCancelAction,oe as buildSendAssetAction,qn as buildTokenDelegateAction,kn as buildTopUpIsolatedOnlyMarginAction,On as buildUpdateIsolatedMarginAction,Dn as buildUpdateLeverageAction,vn as buildUsdClassTransferAction,hn as createL1ActionRequest,He as createSendAssetTransaction,bn as createTransaction,ke as createUserSignedActionRequest,Xn as getHyperCoreToolbox,$e as validateHyperCoreAddress};
1
+ import"../../chunk-qsbf0z90.js";import{m as we,r as Ue}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";function St({builder:e,grouping:t="na",orders:n}){return{builder:e,grouping:t,orders:n,type:"order"}}function Tt({cancels:e}){return{cancels:e,type:"cancel"}}function wt({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function Ut({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function _t({modifies:e}){return{modifies:e,type:"batchModify"}}function Dt({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Ot({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function kt({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function vt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function se({amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u}){return{amount:e,destination:t,destinationDex:n,fromSubAccount:r,hyperliquidChain:i,nonce:o,signatureChainId:s,sourceDex:p,token:u,type:"sendAsset"}}function Rt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function It({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function qt({hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,validator:i,wei:o}){return{hyperliquidChain:e,isUndelegate:t,nonce:n,signatureChainId:r,type:"tokenDelegate",validator:i,wei:o}}import{SwapKitError as Ve,SwapKitNumber as Qe}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as B}from"@swapkit/helpers/api";import{SwapKitError as V}from"@swapkit/helpers";import{keccak256 as Me,Signature as Fe}from"ethers";var I="0x0000000000000000000000000000000000000000",D="0xa4b1",q={name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},Le={chainId:1337,name:"Exchange",verifyingContract:I,version:"1"},je={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},pe="Mainnet",Q={approveAgent:[{name:"hyperliquidChain",type:"string"},{name:"agentAddress",type:"address"},{name:"agentName",type:"string"},{name:"nonce",type:"uint64"}],approveBuilderFee:[{name:"hyperliquidChain",type:"string"},{name:"maxFeeRate",type:"string"},{name:"builder",type:"address"},{name:"nonce",type:"uint64"}],sendAsset:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"sourceDex",type:"string"},{name:"destinationDex",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"fromSubAccount",type:"string"},{name:"nonce",type:"uint64"}],tokenDelegate:[{name:"hyperliquidChain",type:"string"},{name:"validator",type:"address"},{name:"wei",type:"uint64"},{name:"isUndelegate",type:"bool"},{name:"nonce",type:"uint64"}],usdClassTransfer:[{name:"hyperliquidChain",type:"string"},{name:"amount",type:"string"},{name:"toPerp",type:"bool"},{name:"nonce",type:"uint64"}]},G={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},Ee=new TextEncoder;function b(...e){let t=e.reduce((i,o)=>i+o.length,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function Je(e,t,n){if(n<t)return new Uint8Array([e+n]);if(n<=255)return new Uint8Array([e+t,n]);if(n<=65535)return new Uint8Array([e+t+1,n>>8,n&255]);return new Uint8Array([e+t+2,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}function v(e,t){let n=new Uint8Array(t),r=e;for(let i=t-1;i>=0;i-=1)n[i]=Number(r&0xffn),r>>=8n;return n}function ae(e){if(e>=0n){if(e<=0x7fn)return new Uint8Array([Number(e)]);if(e<=0xffn)return new Uint8Array([204,Number(e)]);if(e<=0xffffn)return b(new Uint8Array([205]),v(e,2));if(e<=0xffffffffn)return b(new Uint8Array([206]),v(e,4));return b(new Uint8Array([207]),v(e,8))}if(e>=-32n)return new Uint8Array([256+Number(e)]);if(e>=-128n)return new Uint8Array([208,256+Number(e)]);if(e>=-32768n)return b(new Uint8Array([209]),v(BigInt.asUintN(16,e),2));if(e>=-2147483648n)return b(new Uint8Array([210]),v(BigInt.asUintN(32,e),4));return b(new Uint8Array([211]),v(BigInt.asUintN(64,e),8))}function ce(e){let t=Ee.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Je(217,0,t.length),t)}function ze(e){let t=e.map((r)=>Y(r)),n=e.length<16?new Uint8Array([144+e.length]):e.length<=65535?new Uint8Array([220,e.length>>8,e.length&255]):new Uint8Array([221,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(n,...t)}function Ke(e){let t=Object.entries(e).filter(([,r])=>typeof r<"u"),n=t.length<16?new Uint8Array([128+t.length]):t.length<=65535?new Uint8Array([222,t.length>>8,t.length&255]):new Uint8Array([223,t.length>>>24&255,t.length>>>16&255,t.length>>>8&255,t.length&255]);return b(n,...t.flatMap(([r,i])=>[ce(r),Y(i)]))}function Y(e){if(e===null)return new Uint8Array([192]);if(typeof e==="boolean")return new Uint8Array([e?195:194]);if(typeof e==="string")return ce(e);if(typeof e==="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new V("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ae(BigInt(e))}if(typeof e==="bigint")return ae(e);if(e instanceof Uint8Array){let t=e.length<=255?new Uint8Array([196,e.length]):e.length<=65535?new Uint8Array([197,e.length>>8,e.length&255]):new Uint8Array([198,e.length>>>24&255,e.length>>>16&255,e.length>>>8&255,e.length&255]);return b(t,e)}if(Array.isArray(e))return ze(e);if(typeof e==="object")return Ke(e);throw new V("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(e)}`})}function We(e){let t=e.startsWith("0x")?e.slice(2):e;if(t.length%2!==0||/[^a-fA-F0-9]/u.test(t))throw new V("helpers_invalid_params",{hexValue:e});let n=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)n[r/2]=Number.parseInt(t.slice(r,r+2),16);return n}function de(e){return{domain:Le,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...je.Agent]}}}function ye(e){let t=G[e.type],n=Q[e.type],{signatureChainId:r,type:i,...o}=e,s=Number.parseInt(r||D,16);return{domain:{...q,chainId:s},message:{...o,hyperliquidChain:o.hyperliquidChain||pe},primaryType:t,types:{[t]:n}}}function ue(e){let t=Fe.from(e);return{r:t.r,s:t.s,v:t.v}}function le(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),We(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Me(b(i,o,s,p))}function ge(e){let t=e.hyperliquidChain||pe;switch(e.type){case"approveAgent":return{...e,agentAddress:e.agentAddress.toLowerCase(),hyperliquidChain:t};case"approveBuilderFee":return{...e,builder:e.builder.toLowerCase(),hyperliquidChain:t};case"sendAsset":return{...e,destination:e.destination.toLowerCase(),fromSubAccount:e.fromSubAccount.toLowerCase(),hyperliquidChain:t};case"tokenDelegate":return{...e,hyperliquidChain:t,validator:e.validator.toLowerCase()};case"usdClassTransfer":return{...e,hyperliquidChain:t};default:return e}}var fe=Number.parseInt(D,16),Ge=new Set(["chainId","name","verifyingContract","version"]),me=/^0x[0-9a-fA-F]{40}$/,X=Q.sendAsset;var c=(e)=>{throw new Ve("toolbox_hypercore_payload_mismatch",{problems:[e]})};function Ce(e){try{return new URL(e)}catch{return}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedDestinationDex:i,expectedFromSubAccount:o,expectedSourceDex:s,expectedToken:p,submitTo:u,typedData:S}){let{domain:h,message:m,primaryType:H,types:a}=S,d=G.sendAsset;if(H!==d)c(`primaryType is ${JSON.stringify(H)}, expected "${d}"`);if(e.type!=="sendAsset")c(`action.type is ${JSON.stringify(e.type)}, expected "sendAsset"`);let f=X.map(({name:y})=>y),x=new Set([...f,"signatureChainId","type"]),C=Object.keys(e).filter((y)=>!x.has(y));if(C.length)c(`action carries unexpected keys: ${C.join(", ")}`);for(let{name:y}of X)if(m[y]!==e[y])c(`${y}: signed ${JSON.stringify(m[y])} != submitted ${JSON.stringify(e[y])}`);let g=Object.keys(m),T=g.filter((y)=>!f.includes(y)),_=f.filter((y)=>!g.includes(y));if(T.length||_.length){let y=[T.length?`declares undeclared keys [${T.join(",")}]`:"",_.length?`is missing keys [${_.join(",")}]`:""].filter(Boolean).join(" / ");c(`message ${y}`)}let w=X.map(({name:y,type:W})=>`${y}:${W}`).join(","),R=(a[d]??[]).map(({name:y,type:W})=>`${y}:${W}`).join(",");if(R!==w)c(`types.${d} is [${R}], expected [${w}]`);let P=Object.keys(a).filter((y)=>y!==d&&y!=="EIP712Domain");if(P.length)c(`types carries unexpected entries: ${P.join(", ")}`);if(Number(h.chainId)!==fe)c(`domain.chainId is ${h.chainId}, expected ${fe} (Arbitrum)`);if(h.name!==q.name)c(`domain.name is ${JSON.stringify(h.name)}, expected "${q.name}"`);if(h.version!==q.version)c(`domain.version is ${JSON.stringify(h.version)}, expected "${q.version}"`);if(h.verifyingContract!==I)c(`domain.verifyingContract is ${h.verifyingContract}, expected the zero address`);let L=Object.keys(h).filter((y)=>!Ge.has(y));if(L.length)c(`domain carries unexpected keys: ${L.join(", ")}`);if(typeof e.signatureChainId!=="string"||e.signatureChainId.toLowerCase()!==D)c(`action.signatureChainId is ${JSON.stringify(e.signatureChainId)}, expected "${D}"`);if(e.hyperliquidChain!=="Mainnet")c(`action.hyperliquidChain is ${JSON.stringify(e.hyperliquidChain)}, expected "Mainnet"`);if(typeof e.nonce!=="number"||!Number.isSafeInteger(e.nonce)||e.nonce<=0)c(`action.nonce is ${JSON.stringify(e.nonce)}, expected a positive safe integer`);if(i!==""&&i!=="spot")c(`expectedDestinationDex ${JSON.stringify(i)} is not "" or "spot"`);if(e.destinationDex!==i)c(`action.destinationDex is ${JSON.stringify(e.destinationDex)}, expected ${JSON.stringify(i)}`);if(p!==B)c(`route sell token is ${JSON.stringify(p)}, expected "${B}"`);if(e.token!==p)c(`action.token is ${JSON.stringify(e.token)}, expected route sell token "${p}"`);if(e.sourceDex!==""&&e.sourceDex!=="spot")c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected "" or "spot"`);if(typeof e.sourceDex!=="string"||e.sourceDex!==s)c(`action.sourceDex is ${JSON.stringify(e.sourceDex)}, expected route sourceDex ${JSON.stringify(s)}`);let j=e.fromSubAccount;if(typeof j!=="string"||typeof o!=="string"||j.toLowerCase()!==o.toLowerCase())c(`action.fromSubAccount is ${JSON.stringify(e.fromSubAccount)}, expected ${JSON.stringify(o)}`);if(o&&!me.test(o))c(`expectedFromSubAccount ${JSON.stringify(o)} is not a well-formed 0x address`);if(!n)c("expectedAmount is missing — cannot verify action.amount");let re=!1;try{re=new Qe(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!re)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);let z=typeof e.destination==="string"?e.destination:"";if(!me.test(z))c(`action.destination ${JSON.stringify(e.destination)} is not a well-formed 0x address`);if(!r)c("expectedDestination is missing — cannot verify action.destination");if(z.toLowerCase()!==r.toLowerCase())c(`action.destination ${z} != expected destination ${r}`);let ie=Ce(u),K=ie?.origin,oe=t.flatMap((y)=>Ce(y)?.origin??[]);if(ie?.protocol!=="https:")c(`submitTo ${JSON.stringify(u)} must be an https URL`);if(!K||!oe.includes(K))c(`submitTo origin ${K} is not one of the allowed exchange origins [${oe.join(", ")}]`)}import{AssetValue as M,Chain as Ye,derivationPathToString as Xe,getChainConfig as _e,getRPCUrl as Ze,NetworkDerivationPath as et,RequestClient as N,SwapKitError as l,SwapKitNumber as O,updateDerivationPath as tt}from"@swapkit/helpers";import{SwapKitApi as nt}from"@swapkit/helpers/api";import{HDNodeWallet as rt}from"ethers";import{match as it,P as Z}from"ts-pattern";var U=Ye.Hype,{baseDecimal:ee,rpcUrls:he}=_e(U),ot=he[0]?`${he[0]}/exchange`:void 0,st={HYPE:ee,USDC:6,USDT:6},De="Mainnet",at=/^\d+(?:\.\d+)?$/,pt=/^[^:]+:0x[0-9a-fA-F]+$/,ct={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},dt={spotSend:"HyperliquidTransaction:SpotSend"};function A(e,t){if(!Ne(e))throw new l(t,{address:e});return e.toLowerCase()}function F(e){if(e===void 0)return;try{return new O(e)}catch{return}}var Oe={retry:{maxRetries:0},timeoutMs:5000};async function k({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return k({...e?{dex:e}:{},type:"clearinghouseState",user:A(t,"helpers_invalid_params")})}function ke({user:e}){return k({type:"spotClearinghouseState",user:A(e,"helpers_invalid_params")})}function yt({destination:e,sender:t}){let n=A(t,"helpers_invalid_params"),r=A(e,"helpers_invalid_params");return k({requestOptions:Oe,source:n,type:"preTransferCheck",user:r})}function ut({dex:e,user:t}){return k({...e?{dex:e}:{},type:"openOrders",user:A(t,"helpers_invalid_params")})}function lt({dex:e,user:t}){return k({...e?{dex:e}:{},type:"frontendOpenOrders",user:A(t,"helpers_invalid_params")})}function gt({oidOrCloid:e,user:t}){return k({oid:e,type:"orderStatus",user:A(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,user:t}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:A(t,"helpers_invalid_params")})}function mt({aggregateByTime:e,endTime:t,startTime:n,user:r}){return k({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:A(r,"helpers_invalid_params")})}function He({coin:e,token:t,value:n,spotMeta:r}){if(!n||Number(n)<=0)return null;let i=e?.toUpperCase()||`TOKEN-${t||"UNKNOWN"}`,o=r?.tokens?.find((u)=>u.name===e||t!==void 0&&u.index===Number(t)),s=o?.weiDecimals??st[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function Ct(e){let t=new Map;for(let n of e){let r=n.toString({includeSynthProtocol:!0}),i=t.get(r);t.set(r,i?i.add(n):n)}if(![...t.values()].some((n)=>n.isGasAsset||n.ticker==="HYPE")){let n=M.from({chain:U,value:0});t.set(n.toString({includeSynthProtocol:!0}),n)}return[...t.values()]}async function E(){try{return await Ze(U)}catch{let[e]=_e(U).rpcUrls;if(!e)throw new l("helpers_chain_no_public_or_set_rpc_url",{chain:U});return e}}async function J(){return`${await E()}/exchange`}function At(e){let t=dt[e.type],{type:n,...r}=e;return{domain:{chainId:Number.parseInt(e.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:I,version:"1"},message:r,primaryType:t,types:{[t]:ct[n]}}}async function ht({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?A(r,"helpers_invalid_params"):void 0,s=await J(),p=le(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:de(p),vaultAddress:o}}async function Pe({action:e,endpoint:t,nonce:n,signatureChainId:r}){let i=n||e.nonce||Date.now(),o=r||e.signatureChainId||D,s=ge({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:ye(s)}}async function ne({token:e,user:t}){let n=await ke({user:t}),i=(n.spotState?.balances||n.balances||[]).find(({coin:p})=>p&&e.startsWith(`${p}:`)),o=F(i?.total||0),s=F(i?.hold||0);return o&&s?o.sub(s):void 0}async function ve({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.getValue("string");if(!r||Number(r)<=0)throw new l("toolbox_sweep_amount_too_low",{asset:e.toString(),balance:r||"0"});return r}async function Ht(e){if(e.address&&pt.test(e.address))return e.address;let n=(await k({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.tokenId}`;throw new l("helpers_invalid_params",{asset:e.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function Re({destination:e,sender:t}){let n;try{n=await yt({destination:e,sender:t})}catch(o){throw new l("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&at.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new l("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new l("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Ie(e){return e.toUpperCase().startsWith("USDC:")}async function qe({activationFee:e,token:t,user:n}){if(e<=0)return;let[r,i]=await Promise.all([te({user:n}),ne({token:B,user:n})]),o=F(r.withdrawable||"0")??new O(0),s=i??new O(0);if(new O(e).lte(o)||new O(e).lte(s))return;throw new l("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function $e({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Ie(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new l("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new l("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:n,token:r});let p="0";if(o&&n!=="spot"){if(p=(await te({user:i})).withdrawable||"0",s.lte(F(p)??0))return"";if(n==="")throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:"0",token:r})}let u=await ne({token:r,user:i})??new O(0);if(u.gte(s)){if(!o)await qe({activationFee:e,token:r,user:i});return"spot"}throw new l("toolbox_hypercore_insufficient_balance",{amountRequired:s.getValue("string"),perpsWithdrawable:p,spotAvailable:u.getValue("string"),token:r})}async function xt({amount:e,destination:t,sender:n,sourceDex:r,sweep:i,token:o}){if(i&&r!==void 0&&r!=="spot")throw new l("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:r});let s=await Re({destination:t,sender:n});if(!i){let u=await $e({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Ie(o))return await qe({activationFee:s,token:o,user:n}),{amount:e,sourceDex:"spot"};if(s<=0)return{amount:e,sourceDex:"spot"};let p=new O(e).sub(s);if(p.lte(0))throw new l("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function bt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=A(t,"core_transaction_invalid_recipient_address"),u=A(n,"core_transaction_invalid_sender_address"),S=e.address;if(!S)throw new l("helpers_invalid_params",{asset:e.toString(),from:u});let h=i?await ve({assetValue:e,sender:u,token:S}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:h,destination:p,hyperliquidChain:De,signatureChainId:r||D,time:H,token:S,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:At(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:S}){let h=A(i,"core_transaction_invalid_recipient_address"),m=A(o,"core_transaction_invalid_sender_address"),H=r?A(r,"helpers_invalid_params"):"",a=H||m,d=await Ht(e),f=u?await ve({assetValue:e,sender:a,token:d}):e.getValue("string"),{amount:x,sourceDex:C}=await xt({amount:f,destination:h,sender:a,sourceDex:p,sweep:u,token:d}),g=se({amount:x,destination:h,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:De,nonce:S||Date.now(),signatureChainId:s||D,sourceDex:C,token:d});return Pe({action:g,endpoint:n})}async function Be(e){let t=await N.post(e.endpoint,{json:{action:e.action,...typeof e.expiresAfter==="number"?{expiresAfter:e.expiresAfter}:{},nonce:e.nonce,signature:e.signature,vaultAddress:e.vaultAddress??null},retry:{maxRetries:0}});if(t?.status!=="ok")throw new l("core_transaction_failed",{definitive:t?.status==="err",response:t});return t}async function be({amount:e,destination:t,nonce:n,token:r,user:i}){let o=A(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),S=r?.toUpperCase(),h=({delta:m,time:H})=>{if(!(H&&H>=p&&m?.type==="send"&&m.nonce===n))return!1;if(u&&m?.destination?.toLowerCase()!==u)return!1;let a=F(m?.amount);if(e!==void 0&&!a?.eqValue(e))return!1;if(S!==void 0){if(!m?.token)return!1;let d=m.token.toUpperCase();if(d!==S&&!S.startsWith(`${d}:`))return!1}return!0};for(let m=0;m<8;m++){if(m>0)await new Promise((H)=>setTimeout(H,1500));try{let H=await N.post(`${s}/info`,{json:{startTime:p,type:"userNonFundingLedgerUpdates",user:o},...Oe}),a=Array.isArray(H)?H.find(h):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Se({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof l&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);if(s)return s;throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"unknown",guidance:"Delivery of this broadcast is unknown and the nonce is single-use — do not retry or re-sign; check the account ledger for the transfer first.",nonce:t.nonce,transportError:String(i)})}let r=await be(t);if(!r)throw new l("toolbox_hypercore_transfer_hash_not_found",{broadcast:"accepted",guidance:`Do not retry or re-sign — the exchange accepted this nonce, so re-submitting risks a duplicate ${e}. Check the account ledger for the transfer first.`,nonce:t.nonce});return r}function Te({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function Ne(e){return e.startsWith("0x")&&Ue(e)}function Xt(e){let t=e&&"index"in e?e.index||0:0,n=Xe(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:tt(et[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=it(e).with({phrase:Z.string},({phrase:a})=>rt.fromPhrase(a,void 0,n)).with({signer:Z.not(Z.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,r}async function s(){let a=o();return a?await a.getAddress():""}async function p(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let f=we(a.typedData),x=await d.signTypedData(f.domain,f.types,f.message);return{action:a.action,endpoint:a.endpoint,nonce:a.nonce,signature:ue(x),..."expiresAfter"in a?{expiresAfter:a.expiresAfter}:{},..."vaultAddress"in a?{vaultAddress:a.vaultAddress}:{}}}async function u(a){let d=A(a,"helpers_invalid_params"),f=await E(),[x,C,g]=await Promise.all([N.post(`${f}/info`,{json:{type:"spotClearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"clearinghouseState",user:d}}),N.post(`${f}/info`,{json:{type:"spotMeta"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:P})=>He({coin:w,spotMeta:g,token:R,value:P})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:g,value:C.withdrawable||C.marginSummary?.accountValue||C.marginSummary?.totalRawUsd});return Ct(_?[...T,_]:T)}async function S(a,d=!0){let f=A(a,"helpers_invalid_params");try{let x=await nt.getChainBalance({address:f,chain:U,scamFilter:d});if(x.length){let C=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return C.some((T)=>T.isGasAsset)?C:[M.from({chain:U}),...C]}}catch{}return u(f)}async function h({sweep:a,...d}){let f=o();if(!f)throw new l("toolbox_hypercore_no_signer");let x=d.sender||await f.getAddress(),C=await xe({...d,feeRate:0,sender:x,sweep:a}),g=await p(C);return Se({kind:"transfer",lookup:Te({action:C.action,nonce:C.nonce,user:C.action.fromSubAccount||x}),signed:g})}async function m(a){let d=o();if(!d)throw new l("toolbox_hypercore_no_signer");let{action:f,typedData:x,...C}=a,g=structuredClone(f),T=structuredClone(x),_=await d.getAddress(),w=await J(),R=[...new Set([w,ot??w])];Ae({...C,action:g,allowedEndpoints:R,typedData:T});let P=g.fromSubAccount?A(g.fromSubAccount,"helpers_invalid_params"):_,L=await Re({destination:g.destination,sender:P});await $e({activationFee:L,amount:g.amount,sourceDex:g.sourceDex,token:g.token,user:P});let j=await p({action:g,endpoint:w,nonce:g.nonce,typedData:T});return Se({kind:"payin",lookup:Te({action:g,nonce:g.nonce,user:P}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:ht,createSendAssetTransaction:xe,createTransaction:bt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:S,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:lt,openOrders:ut,orderStatus:gt,spotClearinghouse:ke,userFills:ft,userFillsByTime:mt},signAndBroadcastSendAsset:m,signTransaction:p,transfer:h,validateAddress:Ne}}export{B as HYPERCORE_USDC_TOKEN_ID,Rt as buildApproveAgentAction,It as buildApproveBuilderFeeAction,_t as buildBatchModifyAction,Tt as buildCancelAction,wt as buildCancelByCloidAction,Ut as buildModifyAction,St as buildOrderAction,Pt as buildScheduleCancelAction,se as buildSendAssetAction,qt as buildTokenDelegateAction,kt as buildTopUpIsolatedOnlyMarginAction,Ot as buildUpdateIsolatedMarginAction,Dt as buildUpdateLeverageAction,vt as buildUsdClassTransferAction,ht as createL1ActionRequest,xe as createSendAssetTransaction,bt as createTransaction,Pe as createUserSignedActionRequest,Xt as getHyperCoreToolbox,Ne as validateHyperCoreAddress};
@@ -1 +1 @@
1
- import{ja as D}from"../../chunk-qk8kg62t.js";import{ka as d}from"../../chunk-pz8xe0qj.js";import{PublicKey as P}from"@solana/web3.js";import{AssetValue as A,Chain as p,DerivationPath as F,derivationPathToString as G,getChainConfig as O,getRPCUrl as N,NetworkDerivationPath as L,SwapKitError as T,updateDerivationPath as E}from"@swapkit/helpers";import{match as U,P as B}from"ts-pattern";async function j(n){let e=A.from({address:n,chain:p.Solana});if(e.symbol!=="UNKNOWN")return{decimals:e.decimal||0,id:n,logoURI:e.getIconUrl(),name:e.symbol,symbol:e.ticker};let t=`https://lite-api.jup.ag/tokens/v2/search?query=${encodeURIComponent(n)}`;try{let o=await fetch(t);if(!o.ok)return null;let r=await o.json();if(!Array.isArray(r)||r.length===0)return null;return r.find((a)=>a.id===n)||null}catch{return null}}async function V(n){let e=await w(),{PublicKey:t}=await import("@solana/web3.js"),{TOKEN_PROGRAM_ID:o}=await import("@solana/spl-token"),r=new t(n),{baseDecimal:i}=O(p.Solana),a=await e.getBalance(r),c=[A.from({chain:p.Solana,fromBaseDecimal:i,value:a||0})],s=await e.getParsedTokenAccountsByOwner(r,{programId:o});for(let{account:m}of s.value){let l=m.data.parsed.info,f=l.mint,y=l.tokenAmount.amount;if(Number(y)===0)continue;let u=await j(f),g=u?.symbol||"UNKNOWN",h=u?.decimals||l.tokenAmount.decimals;c.push(A.from({asset:`${p.Solana}.${g}-${f}`,fromBaseDecimal:h,value:y}))}return c}function M(n){try{let e=new P(n);return P.isOnCurve(e.toBytes())}catch{return!1}}function en(n){let e=n&&"index"in n?n.index||0:0,t=G(n&&"derivationPath"in n&&n.derivationPath?n.derivationPath:E(L[p.Solana],{index:e})),o;async function r(){if(o)return o;return o=await U(n).with({phrase:B.string},({phrase:a})=>I({derivationPath:t,phrase:a})).with({signer:B.any},({signer:a})=>a).otherwise(()=>{return}),o}async function i(){let a=await r();return a?.publicKey?R(a.publicKey):""}return{broadcastTransaction:_(w),createKeysForPath:I,createTransaction:K(w),createTransactionFromInstructions:Z,estimateTransactionFee:q(w),getAddress:i,getAddressFromPubKey:R,getBalance:D(p.Solana),getBalanceFromRPC:V,getConnection:w,getPubkeyFromAddress:(a)=>new P(a),signAndBroadcastTransaction:async(a)=>{let c=await x(w,r)(a);return _(w)(c)},signTransaction:x(w,r),transfer:J(w,r),validateAddress:M}}function q(n){return async({recipient:e,assetValue:t,memo:o,isProgramDerivedAddress:r,sender:i})=>{let a=await n(),c=await K(n)({assetValue:t,isProgramDerivedAddress:r,memo:o,recipient:e,sender:i}),s=await C(a,c),{baseDecimal:m}=O(p.Solana);return A.from({chain:p.Solana,fromBaseDecimal:m,value:s})}}async function C(n,e){let t=await n.getFeeForMessage(e.compileMessage());if(t.value===null)throw new T("toolbox_fee_estimation_failed","Could not estimate Solana fee.");return t.value}async function w(){let{Connection:n}=await import("@solana/web3.js"),e=await N(p.Solana);return new n(e,{commitment:"confirmed",fetchMiddleware:(t,o,r)=>{let i={};for(let[a,c]of Object.entries(o?.headers??{})){let s=a.toLowerCase();if(s!=="pragma"&&s!=="solana-client")i[a]=c}r(t,{...o,headers:i})}})}function W(n){return async({assetValue:e,recipient:t,sender:o,isProgramDerivedAddress:r,sweep:i})=>{let a=new P(o);if(e.isGasAsset){let{Transaction:c,SystemProgram:s}=await import("@solana/web3.js");return new c().add(s.transfer({fromPubkey:a,lamports:i?0:e.getBaseValue("number"),toPubkey:new P(t)}))}if(e.address){let c=await n();return H({amount:i?0:e.getBaseValue("number"),connection:c,decimals:e.decimal,from:a,isProgramDerivedAddress:r,recipient:t,sweep:i,tokenAddress:e.address})}return}}async function H({tokenAddress:n,recipient:e,from:t,connection:o,amount:r,decimals:i,isProgramDerivedAddress:a,sweep:c}){let{getAssociatedTokenAddress:s,getAccount:m,createAssociatedTokenAccountIdempotentInstruction:l,createTransferCheckedInstruction:f}=await import("@solana/spl-token"),{Transaction:y}=await import("@solana/web3.js"),u=new y,g=new P(n),h=await s(g,t),S=new P(e),b=await s(g,S,a),k=!1;try{await m(o,b),k=!0}catch{}if(!k)u.add(l(t,b,S,g));let v=c?BigInt((await o.getTokenAccountBalance(h)).value.amount):r;if(c&&v<=0n)throw new T({errorKey:"toolbox_sweep_amount_too_low",info:{asset:n,balance:v.toString()}});return u.add(f(h,g,b,t,v,i)),u}async function z(n,e,t){let{ACCOUNT_SIZE:o,ASSOCIATED_TOKEN_PROGRAM_ID:r}=await import("@solana/spl-token");if(!e.instructions.some(({programId:f})=>f.equals(r)))return;let[a,c,s,m]=await Promise.all([n.getBalance(t),C(n,e),n.getMinimumBalanceForRentExemption(o),n.getMinimumBalanceForRentExemption(0)]),l=c+s+m;if(a<l)throw new T({errorKey:"toolbox_solana_insufficient_balance",info:{balance:a,fee:c,rentReserve:m,required:l,tokenAccountRent:s}})}function K(n){return async({checkPayerBalance:e=!1,recipient:t,assetValue:o,memo:r,isProgramDerivedAddress:i,sender:a,recentBlockhash:c,sweep:s})=>{let{createMemoInstruction:m}=await import("@solana/spl-memo"),l=new P(a);if(!(i||M(t)))throw new T("core_transaction_invalid_recipient_address");let f,y=()=>f??=n(),u=await W(y)({assetValue:o,isProgramDerivedAddress:i,recipient:t,sender:a,sweep:s});if(!u)throw new T("core_transaction_invalid_sender_address");if(r)u.add(m(r));if(u.recentBlockhash=c??(await(await y()).getLatestBlockhash()).blockhash,u.feePayer=l,e&&!o.isGasAsset)await z(await y(),u,l);if(s&&o.isGasAsset){let g=await y(),[h,S,b]=await Promise.all([g.getBalance(l),C(g,u),g.getMinimumBalanceForRentExemption(0)]),k=h-S-b;if(k<=0)throw new T({errorKey:"toolbox_sweep_amount_too_low",info:{balance:h,fee:S,rentReserve:b}});let{SystemProgram:v}=await import("@solana/web3.js");u.instructions[0]=v.transfer({fromPubkey:l,lamports:k,toPubkey:new P(t)})}return u}}async function Z({instructions:n}){let{Transaction:e}=await import("@solana/web3.js"),t=new e().add(...n);if(!t)throw new T("core_transaction_invalid_sender_address");return t}function J(n,e){return async({recipient:t,assetValue:o,checkPayerBalance:r,memo:i,isProgramDerivedAddress:a,sweep:c})=>{let s=await e();if(!s)throw new T("core_transaction_invalid_sender_address");let m=s.publicKey?.toString()??(await s.connect()).publicKey.toString(),l=await K(n)({assetValue:o,checkPayerBalance:r,isProgramDerivedAddress:a,memo:i,recipient:t,sender:m,sweep:c});if("signTransaction"in s){let f=await s.signTransaction(l);return _(n)(f)}return l.sign(s),_(n)(l)}}function _(n){return async(e)=>(await n()).sendRawTransaction(e.serialize())}function x(n,e){return async(t)=>{let o=await e();if(!o)throw new T("toolbox_solana_no_signer");let{VersionedTransaction:r}=await import("@solana/web3.js");if(!(t instanceof r)){let a=await(await n()).getLatestBlockhash();t.recentBlockhash=a.blockhash,t.feePayer=o.publicKey||void 0}if("connect"in o)return await o.signTransaction(t);return t.sign([o]),t}}async function I({phrase:n,derivationPath:e=F.SOL}){let{HDKey:t}=await import("micro-key-producer/slip10.js"),{mnemonicToSeedSync:o}=await import("@scure/bip39"),{Keypair:r}=await import("@solana/web3.js"),i=o(n),a=t.fromMasterSeed(i);return r.fromSeed(a.derive(e,!0).privateKey)}function R(n){return n.toString()}export{I as createKeysForPath,j as fetchTokenMetaData,en as getSolanaToolbox,M as validateSolanaAddress};
1
+ import{ja as N}from"../../chunk-qk8kg62t.js";import{ka as l}from"../../chunk-pz8xe0qj.js";import{PublicKey as h}from"@solana/web3.js";import{AssetValue as C,Chain as P,DerivationPath as L,derivationPathToString as U,getChainConfig as G,getRPCUrl as q,NetworkDerivationPath as V,SwapKitError as p,updateDerivationPath as j}from"@swapkit/helpers";import{match as W,P as O}from"ts-pattern";async function z(n){let e=C.from({address:n,chain:P.Solana});if(e.symbol!=="UNKNOWN")return{decimals:e.decimal||0,id:n,logoURI:e.getIconUrl(),name:e.symbol,symbol:e.ticker};let t=`https://lite-api.jup.ag/tokens/v2/search?query=${encodeURIComponent(n)}`;try{let a=await fetch(t);if(!a.ok)return null;let r=await a.json();if(!Array.isArray(r)||r.length===0)return null;return r.find((o)=>o.id===n)||null}catch{return null}}async function H(n){let e=await T(),{PublicKey:t}=await import("@solana/web3.js"),{TOKEN_2022_PROGRAM_ID:a,TOKEN_PROGRAM_ID:r}=await import("@solana/spl-token"),i=new t(n),{baseDecimal:o}=G(P.Solana),c=await e.getBalance(i),s=[C.from({chain:P.Solana,fromBaseDecimal:o,value:c||0})],m=await Promise.all([r,a].map((u)=>e.getParsedTokenAccountsByOwner(i,{programId:u})));for(let{account:u}of m.flatMap(({value:d})=>d)){let d=u.data.parsed.info,w=d.mint,b=d.tokenAmount.amount;if(Number(b)===0)continue;let S=await z(w),f=S?.symbol||"UNKNOWN",g=S?.decimals||d.tokenAmount.decimals;s.push(C.from({asset:`${P.Solana}.${f}-${w}`,fromBaseDecimal:g,value:b}))}return s}function E(n){try{let e=new h(n);return h.isOnCurve(e.toBytes())}catch{return!1}}function cn(n){let e=n&&"index"in n?n.index||0:0,t=U(n&&"derivationPath"in n&&n.derivationPath?n.derivationPath:j(V[P.Solana],{index:e})),a;async function r(){if(a)return a;return a=await W(n).with({phrase:O.string},({phrase:o})=>D({derivationPath:t,phrase:o})).with({signer:O.any},({signer:o})=>o).otherwise(()=>{return}),a}async function i(){let o=await r();return o?.publicKey?M(o.publicKey):""}return{broadcastTransaction:I(T),createKeysForPath:D,createTransaction:B(T),createTransactionFromInstructions:en,estimateTransactionFee:Z(T),getAddress:i,getAddressFromPubKey:M,getBalance:N(P.Solana),getBalanceFromRPC:H,getConnection:T,getPubkeyFromAddress:(o)=>new h(o),signAndBroadcastTransaction:async(o)=>{let c=await x(T,r)(o);return I(T)(c)},signTransaction:x(T,r),transfer:tn(T,r),validateAddress:E}}function Z(n){return async({recipient:e,assetValue:t,memo:a,isProgramDerivedAddress:r,sender:i})=>{let o=await n(),c=await B(n)({assetValue:t,isProgramDerivedAddress:r,memo:a,recipient:e,sender:i}),s=await R(o,c),{baseDecimal:m}=G(P.Solana);return C.from({chain:P.Solana,fromBaseDecimal:m,value:s})}}async function R(n,e){let t=await n.getFeeForMessage(e.compileMessage());if(t.value===null)throw new p("toolbox_fee_estimation_failed","Could not estimate Solana fee.");return t.value}async function T(){let{Connection:n}=await import("@solana/web3.js"),e=await q(P.Solana);return new n(e,{commitment:"confirmed",fetchMiddleware:(t,a,r)=>{let i={};for(let[o,c]of Object.entries(a?.headers??{})){let s=o.toLowerCase();if(s!=="pragma"&&s!=="solana-client")i[o]=c}r(t,{...a,headers:i})}})}function J(n){return async({assetValue:e,recipient:t,sender:a,isProgramDerivedAddress:r,sweep:i})=>{let o=new h(a);if(e.isGasAsset){let{Transaction:c,SystemProgram:s}=await import("@solana/web3.js");return{tokenAccount:void 0,transaction:new c().add(s.transfer({fromPubkey:o,lamports:i?0:e.getBaseValue("number"),toPubkey:new h(t)}))}}if(e.address){let c=await n();return Q({amount:i?0:e.getBaseValue("number"),connection:c,decimals:e.decimal,from:o,isProgramDerivedAddress:r,recipient:t,sweep:i,tokenAddress:e.address})}return}}async function Q({tokenAddress:n,recipient:e,from:t,connection:a,amount:r,decimals:i,isProgramDerivedAddress:o,sweep:c}){let{getAssociatedTokenAddress:s,getAccount:m,createAssociatedTokenAccountIdempotentInstruction:u,createTransferCheckedInstruction:d,createTransferCheckedWithTransferHookInstruction:w,TOKEN_2022_PROGRAM_ID:b}=await import("@solana/spl-token"),{Transaction:S}=await import("@solana/web3.js"),f=new S,g=new h(n),y=await X(a,g),_=await s(g,t,!1,y),A=new h(e),k=await s(g,A,o,y),v=!1;try{await m(a,k,void 0,y),v=!0}catch{}if(!v)f.add(u(t,k,A,g,y));let K=c?BigInt((await a.getTokenAccountBalance(_)).value.amount):r;if(c&&K<=0n)throw new p({errorKey:"toolbox_sweep_amount_too_low",info:{asset:n,balance:K.toString()}});let F=y.equals(b)?await w(a,_,g,k,t,BigInt(K),i,[],"confirmed",y):d(_,g,k,t,K,i);return f.add(F),{tokenAccount:{programId:y,source:_},transaction:f}}async function X(n,e){let{TOKEN_2022_PROGRAM_ID:t,TOKEN_PROGRAM_ID:a}=await import("@solana/spl-token"),r=(await n.getAccountInfo(e))?.owner,i=[a,t].find((o)=>r?.equals(o));if(!i)throw new p({errorKey:"toolbox_solana_unsupported_token_program",info:{mint:e.toString(),owner:r?.toString()}});return i}async function Y(n,{programId:e,source:t}){let{ACCOUNT_SIZE:a,TOKEN_2022_PROGRAM_ID:r}=await import("@solana/spl-token");if(!e.equals(r))return a;let i=await n.getAccountInfo(t);return Math.max(i?.data.length??0,a)}async function nn({connection:n,payer:e,tokenAccount:t,transaction:a}){let{ASSOCIATED_TOKEN_PROGRAM_ID:r}=await import("@solana/spl-token");if(!a.instructions.some(({programId:w})=>w.equals(r)))return;let o=await Y(n,t),[c,s,m,u]=await Promise.all([n.getBalance(e),R(n,a),n.getMinimumBalanceForRentExemption(o),n.getMinimumBalanceForRentExemption(0)]),d=s+m+u;if(c<d)throw new p({errorKey:"toolbox_solana_insufficient_balance",info:{balance:c,fee:s,rentReserve:u,required:d,tokenAccountRent:m}})}function B(n){return async({checkPayerBalance:e=!1,recipient:t,assetValue:a,memo:r,isProgramDerivedAddress:i,sender:o,recentBlockhash:c,sweep:s})=>{let{createMemoInstruction:m}=await import("@solana/spl-memo"),u=new h(o);if(!(i||E(t)))throw new p("core_transaction_invalid_recipient_address");let d,w=()=>d??=n(),b=await J(w)({assetValue:a,isProgramDerivedAddress:i,recipient:t,sender:o,sweep:s});if(!b)throw new p("core_transaction_invalid_sender_address");let{tokenAccount:S,transaction:f}=b;if(r)f.add(m(r));if(f.recentBlockhash=c??(await(await w()).getLatestBlockhash()).blockhash,f.feePayer=u,e&&S)await nn({connection:await w(),payer:u,tokenAccount:S,transaction:f});if(s&&a.isGasAsset){let g=await w(),[y,_,A]=await Promise.all([g.getBalance(u),R(g,f),g.getMinimumBalanceForRentExemption(0)]),k=y-_-A;if(k<=0)throw new p({errorKey:"toolbox_sweep_amount_too_low",info:{balance:y,fee:_,rentReserve:A}});let{SystemProgram:v}=await import("@solana/web3.js");f.instructions[0]=v.transfer({fromPubkey:u,lamports:k,toPubkey:new h(t)})}return f}}async function en({instructions:n}){let{Transaction:e}=await import("@solana/web3.js"),t=new e().add(...n);if(!t)throw new p("core_transaction_invalid_sender_address");return t}function tn(n,e){return async({recipient:t,assetValue:a,checkPayerBalance:r,memo:i,isProgramDerivedAddress:o,sweep:c})=>{let s=await e();if(!s)throw new p("core_transaction_invalid_sender_address");let m=s.publicKey?.toString()??(await s.connect()).publicKey.toString(),u=await B(n)({assetValue:a,checkPayerBalance:r,isProgramDerivedAddress:o,memo:i,recipient:t,sender:m,sweep:c});if("signTransaction"in s){let d=await s.signTransaction(u);return I(n)(d)}return u.sign(s),I(n)(u)}}function I(n){return async(e)=>(await n()).sendRawTransaction(e.serialize())}function x(n,e){return async(t)=>{let a=await e();if(!a)throw new p("toolbox_solana_no_signer");let{VersionedTransaction:r}=await import("@solana/web3.js");if(!(t instanceof r)){let o=await(await n()).getLatestBlockhash();t.recentBlockhash=o.blockhash,t.feePayer=a.publicKey||void 0}if("connect"in a)return await a.signTransaction(t);return t.sign([a]),t}}async function D({phrase:n,derivationPath:e=L.SOL}){let{HDKey:t}=await import("micro-key-producer/slip10.js"),{mnemonicToSeedSync:a}=await import("@scure/bip39"),{Keypair:r}=await import("@solana/web3.js"),i=a(n),o=t.fromMasterSeed(i);return r.fromSeed(o.derive(e,!0).privateKey)}function M(n){return n.toString()}export{D as createKeysForPath,z as fetchTokenMetaData,cn as getSolanaToolbox,E as validateSolanaAddress};
@@ -1,2 +1,2 @@
1
- import{ia as Ct,ja as tr}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as Kr}from"@swapkit/helpers";function z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function re({accountIndex:e,chain:t,derivationPath:r}){if(e!==void 0)z("accountIndex",e);let[n,o,s]=r??Kr[t];return[n,o,e??s]}function Oe({accountIndex:e,change:t=!1,chain:r,derivationPath:n,index:o}){return z("index",o),[...re({accountIndex:e,chain:r,derivationPath:n}),Number(t),o]}function pe(e){return e[2]??0}function Fr({deriveAddress:e,getBalance:t,getUtxos:r}){async function n(i){let{accountIndex:p,count:c,startIndex:u=0,change:a=!1}=i;if(z("count",c),c<1)throw RangeError("count must be at least 1");z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:a,index:u+h});if(m)l.push(m)}return l}async function o(i){let{gapLimit:p=20,change:c=!1}=i??{},u=[],a=0,l=0;while(a<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),a=0;else a++;l++}return u}async function s(i=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:i}),o({change:!0,gapLimit:i})]),u=[...p,...c],a=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=a.reduce((h,m)=>h+m.balance,0);return{addresses:a,total:l}}async function d(i=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:i}),o({change:!0,gapLimit:i})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await r(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:n,getAggregatedBalance:s,getAggregatedUtxos:d,scanForAddresses:o}}import{Chain as C,getRPCUrl as Dr,RequestClient as Re,SKConfig as Ir,SwapKitError as R,warnOnce as Hr}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Rr({chain:e,txHash:t}){let r=`${he(e)}/push/transaction`,n=JSON.stringify({data:t});try{let o=await Re.post(r,{body:n,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let s=await Dr(e);if(s){let d=JSON.stringify({id:Ct(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),i=await Re.post(s,{body:d,headers:{"Content-Type":"application/json"}});if(i.error)throw new R("toolbox_utxo_broadcast_failed",{error:i.error?.message});if(i.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return i.result}throw o}}function he(e){return`https://api.blockchair.com/${Er(e)}`}function Ot(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Er(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function Mr(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),r=t/1000;return Math.max(r,Ot(e))}catch{return Ot(e)}}async function Se(e,t){let r=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!r||r.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return r.data}async function Nr({chain:e,apiKey:t}){let r=await Se(`${he(e)}/stats`,t);if(typeof r.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return r.best_block_height}async function Xt({address:e,chain:t,apiKey:r}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Se(`${he(t)}/dashboards/address/${e}?transaction_details=true`,r))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Zr({address:e,chain:t,apiKey:r}){return(await Xt({address:e,apiKey:r,chain:t}))?.address.balance||0}async function Bt({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Se(`${he(e)}/raw/transaction/${r}`,t))?.[r]?.raw_transaction||""}catch(n){let o=n instanceof Error?n.message:String(n);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var zr=4294967294;async function Wr({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Se(`${he(e)}/dashboards/transaction/${r}`,t))?.[r];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:r});let{transaction:s,inputs:d,outputs:i}=o,p=d.map((u)=>u.spending_sequence),c=s.is_rbf===!0||p.some((u)=>u<zr);return{blockId:s.block_id,confirmed:s.block_id!==-1,fee:s.fee,inputs:d,isRBF:c,outputs:i,sequences:p,size:s.size,txid:s.hash,weight:s.weight}}async function $r({chain:e,address:t,apiKey:r,offset:n=0,limit:o=30}){return(await Se(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${o}&offset=${n}`,r)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:a,index:l,value:h,spending_signature_hex:m})=>({hash:a,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Lr(e){return e.reduce((t,r)=>t+r.value,0)}function St(e,t){let r=[...e].sort((n,o)=>o.value-n.value);if(t){let n=[],o=0;for(let s of r)if(n.push(s),o+=s.value,o>=t)break;return n}return r}async function kt({chain:e,address:t,apiKey:r,targetValue:n,accumulativeValue:o=0,offset:s=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let i=await $r({address:t,apiKey:r,chain:e,limit:d,offset:s,targetValue:n}),c=i.length<d,u=i.filter(({is_spent:y})=>!y),a=Lr(u),l=o+a,h=n&&l>=n;if(c||h)return St(u,n);let m=await kt({accumulativeValue:l,address:t,apiKey:r,chain:e,limit:d,offset:s+d,targetValue:n}),f=[...u,...m];return St(f,n)}catch(i){let p=i instanceof Error?i.message:String(i);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Vr({address:e,chain:t,apiKey:r,fetchTxHex:n=!0,targetValue:o}){let s=await kt({address:e,apiKey:r,chain:t,targetValue:o}),d=n?await Promise.all(s.map(({hash:i})=>Bt({apiKey:r,chain:t,txHash:i}))):[];return s.map(({hash:i,index:p,script_hex:c,value:u},a)=>({address:e,hash:i,index:p,txHex:n?d[a]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=Ir.get("apiKeys").blockchair||"";return Hr({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(r)=>Rr({chain:e,txHash:r}),getAddressData:(r)=>Xt({address:r,apiKey:t,chain:e}),getBalance:(r)=>Zr({address:r,apiKey:t,chain:e}),getBlockHeight:()=>Nr({apiKey:t,chain:e}),getRawTx:(r)=>Bt({apiKey:t,chain:e,txHash:r}),getSuggestedTxFee:()=>Mr(e),getTransactionDetails:(r)=>Wr({apiKey:t,chain:e,txHash:r}),getUtxos:(r)=>Vr({...r,apiKey:t,chain:e})}}function Yo(e){return e}function Go(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as en}from"@noble/hashes/sha2.js";import{createBase58check as tn}from"@scure/base";import{SwapKitError as Ft}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as qr,encodeCashAddr as Yr}from"@swapkit/utxo-signer";var Gr={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},jr={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function Jr(e,t,r){return Yr({hash:r,prefix:e,type:Gr[t]})}function Qr(e){let t=qr(e),r=jr[t.type];if(!r)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:r}}var st={decode:Qr,encode:Jr};var Dt=tn(en);var It;((r)=>{r.Mainnet="mainnet";r.Testnet="testnet"})(It||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},rn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function os(e){return Ne(e)!==void 0}function ss(e){return it(e).network}function G(e){let t=it(e);if(t.format==="legacy")return e;return sn(t)}function Me(e){let t=it(e);return an(t)}function Ne(e){if(typeof e!=="string")return;let t=nn(e)??on(e);return t&&{...t,scriptType:rn[t.type]}}function it(e){let t=Ne(e);if(!t)throw new Ft("toolbox_utxo_invalid_address",{address:e});return t}function nn(e){try{let t=Dt.decode(e);if(t.length!==21)throw new Ft("toolbox_utxo_invalid_address",{address:e});let r=t[0],n=Array.prototype.slice.call(t,1);switch(r){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:n,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:n,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:n,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:n,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function on(e){if(e.indexOf(":")!==-1)try{return Kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let r of t)try{return Kt(`${r}:${e}`)}catch{}}return}function Kt(e){try{let{hash:t,prefix:r,type:n}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:r==="bitcoincash"?"mainnet":"testnet",type:n==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function sn(e){let t=ne.legacy[e.network][e.type],r=Buffer.alloc(1+e.hash.length);return r[0]=t,r.set(e.hash,1),Dt.encode(r)}function an(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",r=e.type==="p2pkh"?"P2PKH":"P2SH",n=new Uint8Array(e.hash);return st.encode(t,r,n)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Bn,UTXO_SCRIPT_TYPES as Vt,UTXOScriptType as Ye}from"@swapkit/helpers";import{Script as kn}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as dn,getTransparentZcashAddressType as un,getZcashAddressType as pn}from"@swapkit/utxo-signer";import{match as ln}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as cn}from"ts-pattern";function U(e){return cn(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function W(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ce(e){if(typeof e!=="string")return null;let t=Ne(W(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var hn=["sprout","sapling","unified"];function fn(e){let t=un(e,U(at.Zcash));if(t)return t;let r=pn(e);return r&&hn.includes(r)?r:null}function j({address:e,chain:t}){return ln(t).with(at.BitcoinCash,()=>Ce(e)).with(at.Zcash,()=>fn(e)).otherwise(()=>dn(e,U(t)))}import{Chain as oe,derivationPathToString as Ht,getPurposeFromPath as Tn,getUTXOScriptTypeForPath as Rt,getUTXOScriptTypeForPurpose as Nt,resolveDerivationPath as mn,SwapKitError as Xe,UTXO_SCRIPT_TYPE_LIST as Et,UTXO_SCRIPT_TYPES as me,UTXOChains as yn,UTXOScriptType as O,updateDerivationPath as gn,warnOnce as xn}from"@swapkit/helpers";import{CashAddrPrefix as bn,CashAddrType as wn,encodeCashAddr as Pn,OutScript as Zt,p2pkh as Un,p2sh as _n,p2tr as vn,p2wpkh as Mt}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),An=Object.freeze({[oe.Bitcoin]:Et,[oe.BitcoinCash]:Ze,[oe.Dash]:Ze,[oe.Dogecoin]:Ze,[oe.Litecoin]:Et,[oe.Zcash]:Ze});function We(e){return An[e]}function ct(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function $e(e,t){if(ye(e,t))return t;throw new Xe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var zt=yn.filter((e)=>!ct(e));function On({purpose:e,scriptType:t}){let r=Nt(e);return r===void 0||r===t}function dt({chain:e,purpose:t,scriptType:r}){xn({condition:!On({purpose:t,scriptType:r}),id:`utxo_off_standard_encoding_${e}_${t}_${r}`,warning:`${e}: encoding m/${t}' keys as ${r}, not the ${Nt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Le({chain:e,derivationPath:t,index:r=0,scriptType:n}){if(t){if(!n){let i=Rt(t);throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Ht(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${i?` (${i})`:""}, or state another deliberately.`})}return $e(e,n),dt({chain:e,purpose:Tn(t),scriptType:n}),{derivationPath:t,scriptType:n}}let o=mn({chain:e,index:r}),s=n?gn(o,{purpose:me[n].purpose}):o,d=n??Rt(s);if(!d)throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Ht(s),error:`${e}: the default derivation path has no standard script type`});return $e(e,d),{derivationPath:s,scriptType:d}}function Sn(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Xe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var Cn={[O.P2PKH]:(e,t)=>{let{address:r,script:n}=ze(Un(e,t),O.P2PKH);return{address:r,script:n}},[O.P2SH_P2WPKH]:(e,t)=>{let r=Mt(e,t),{address:n,script:o}=ze(_n(r,t),O.P2SH_P2WPKH);return{address:n,redeemScript:r.script,script:o}},[O.P2WPKH]:(e,t)=>{let{address:r,script:n}=ze(Mt(e,t),O.P2WPKH);return{address:r,script:n}},[O.P2TR]:(e,t)=>{let r=Sn(e),{address:n,script:o}=ze(vn(r,void 0,t),O.P2TR);return{address:n,script:o,tapInternalKey:r}}};function Ve(e,t,r){return Cn[e](t,r)}function ut(e,t){if(e!==oe.BitcoinCash)return t.address;let r=Zt.decode(t.script);if(r.type!=="pkh")throw new Xe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${r.type} as CashAddr`});return Pn({hash:r.hash,prefix:bn.MAINNET,type:wn.P2PKH}).replace(/^bitcoincash:/,"")}var Xn=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),Wt=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function $t(e){return e in Wt}function Lt(e){return $t(e)?Wt[e]:void 0}function Be(e){return Xn[e]}function pt(e){try{let{type:t}=Zt.decode(e);return $t(t)?Be(t):void 0}catch{return}}import{UTXOScriptType as ie}from"@swapkit/helpers";var _s=1000,ht=10,Kn=2,Fn=10;function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return kn.encode(["RETURN",t])}function qt(e){return Object.fromEntries(Bn.map((t)=>[t,Vt[t][e]]))}var Yt=qt("inputSize"),lt=qt("outputSize"),ft=(e)=>Vt[e].witness,Ge=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Be(r);if(!n||!ye(t,n))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return n},Dn=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Lt(r);if(!n)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return n},ge=({chain:e,inputs:t,outputs:r,feeRate:n})=>{let o=t[0]?ke(t[0],e):Ye.P2PKH,s=n?t.filter((u)=>u.value>=Yt["type"in u&&u.type?u.type:Ye.P2PKH]*Math.ceil(n)):t,d=0,i=0;for(let u of s)if(d+=se(u,e),!ft(ke(u,e)))i++;let p=r?.reduce((u,a)=>u+je(a,e),0)||lt[o],c=i<s.length;return ht+d+p+Tt(c,i)},ke=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ge(e.address,t);return Ye.P2PKH},se=(e,t)=>Yt[ke(e,t)],Tt=(e,t)=>e?Math.ceil((Kn+t)/4):0,je=(e,t,r)=>{if(e?.script)return Fn+e.script.length+(e.script.length>=74?2:1);if(r)return lt[r];if("address"in e&&e.address)return Dn(e.address,t);return lt[Ye.P2PKH]};function Ke(e){switch(e){case ae.Bitcoin:case ae.BitcoinCash:return 550;case ae.Dash:case ae.Litecoin:return 5500;case ae.Dogecoin:return 1e5;case ae.Zcash:return 546;default:throw new mt("toolbox_utxo_not_supported",{chain:e})}}function M({inputs:e,outputs:t,feeRate:r=1,chain:n=ae.Bitcoin,changeAddress:o="",sweep:s=!1}){let d=Ke(n),i=e.filter((f)=>{let y=se(f,n)*r;return s?f.value>Math.max(y,d):y<=f.value});if(s){let f=Math.ceil(r*ge({chain:n,inputs:i,outputs:t})),y=i.reduce((X,q)=>X+q.value,0),b=y-f;if(b<=d)throw new mt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new mt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:i,outputs:t.map((X,q)=>q===S?{...X,value:b}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,n),0),c=t.reduce((f,y)=>f+y.value,0),u=0,a=0,l=!1,h=0,m=[];for(let f of i){if(u+=se(f,n),ft(ke(f,n)))l=!0;else a++;h+=f.value,m.push(f);let y=(p+u+Tt(l,a))*r,b=y+c;if(h<b)continue;let S=h-b,X=r*je({address:o,value:0},n);if(S>X){let q=X+y,Ue=h-(c+Math.ceil(q));if(Ue>Math.max(se({value:0},n)*r,Ke(n)))return{fee:Math.ceil(q),inputs:m,outputs:t.concat({address:o,value:Ue})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(r*ge({chain:n,inputs:e,outputs:t}))}}import{secp256k1 as In}from"@noble/curves/secp256k1.js";import{base64 as Hn,utf8 as Gt}from"@scure/base";import{SwapKitError as Rn,UTXOScriptType as yt}from"@swapkit/helpers";import{CompactSize as En,utils as Mn}from"@swapkit/utxo-signer";var Nn=Gt.decode(`\x18Bitcoin Signed Message:
2
- `),jt={[yt.P2PKH]:31,[yt.P2SH_P2WPKH]:35,[yt.P2WPKH]:39};function Zn(e){return jt[e]!==void 0}function zn(e){let t=Gt.decode(e);return Mn.sha256x2(Nn,En.encode(BigInt(t.length)),t)}function Jt({message:e,privateKey:t,scriptType:r}){let n=jt[r];if(n===void 0)throw new Rn("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${r} address`,scriptType:r});let o=In.sign(zn(e),t,{format:"recovered",prehash:!1}),[s=0]=o,d=new Uint8Array(65);return d[0]=n+s,d.set(o.subarray(1),1),Hn.encode(d)}import{Chain as Pe,SwapKitError as zo}from"@swapkit/helpers";import{hex as hr}from"@scure/base";import{Chain as uo,derivationPathToString as po,FeeOption as lo,resolveDerivationPath as ho,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as fo,CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,NETWORKS as To,p2pkh as yr,Transaction as gr}from"@swapkit/utxo-signer";import{secp256k1 as Wn}from"@noble/curves/secp256k1.js";import{hex as J}from"@scure/base";import{HDKey as rr}from"@scure/bip32";import{mnemonicToSeedSync as bt}from"@scure/bip39";import{AssetValue as gt,applyFeeMultiplier as Qt,Chain as be,derivationPathToString as Fe,FeeOption as N,NetworkDerivationPath as $n,SwapKitError as P,SwapKitNumber as Ln,UTXO_SCRIPT_TYPES as Vn,warnOnce as qn}from"@swapkit/helpers";import{BCHSigHash as nr,RBF_SEQUENCE as Yn,SigHash as er,Transaction as Je,utils as Gn,WIF as or}from"@swapkit/utxo-signer";var Qe=[be.Bitcoin];function sr({address:e,chain:t}){return j({address:e,chain:t})!==null}function jn({phrase:e,derivationPath:t,network:r,seed:n}){let o=n??bt(e),d=rr.fromMasterSeed(o,r.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function xt(e){return Wn.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:r,scriptType:n}){return ut(t,Ve(n,e,r))}function xe({phrase:e,derivationPath:t,chain:r,wif:n,seed:o}){let s=U(r);if(n){let c=or(s).decode(n),u=xt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Fe($n[r]),i=jn({derivationPath:d,network:s,phrase:e,seed:o}),p=xt(i);return{privateKey:i,publicKey:p}}function Jn(e,t){return or(U(t)).encode(e)}function Qn({phrase:e,derivationPath:t,chain:r,seed:n}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let s=U(r),d=n??bt(e),i=rr.fromMasterSeed(d,s.bip32),p=o.slice(0,4).join("/");return i.derive(p)}function eo(e,t){if(!e||!Vn[e].witness)return!1;return e!==ie.P2SH_P2WPKH||!!t}function ir({chain:e,script:t,publicKey:r,network:n}){let o=pt(t);if(o!==ie.P2SH_P2WPKH&&o!==ie.P2TR)return{};if(!ye(e,o))return{};let s=Ve(o,r,n);if(Gn.compareBytes(s.script,t)!==0)return{};return o===ie.P2TR?{tapInternalKey:s.tapInternalKey}:{redeemScript:s.redeemScript}}function to(e,t,r){if(!r)return!1;let n=j({address:e,chain:t}),o=n?Be(n):void 0;if(!o||!ye(t,o))return!1;let s=ut(t,Ve(o,r,U(t)));return t===be.BitcoinCash?W(s)===W(e):s===e}function ro(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function wt({chain:e,tx:t,publicKey:r,network:n,indexes:o}){let s=o??Array.from({length:t.inputsLength},(i,p)=>p),d=[];for(let i of s){let p=t.getInput(i),c=ro(p);if(!c)continue;let{redeemScript:u,tapInternalKey:a}=ir({chain:e,network:n,publicKey:r,script:c}),l={index:i};if(u&&!p.redeemScript)l.redeemScript=u;if(a&&!p.tapInternalKey)l.tapInternalKey=a;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ce({inputs:e,outputs:t,chain:r,tx:n,sender:o,compiledMemo:s,enableRBF:d=!1}){let i=U(r),p=ct(r),c=d?Yn:void 0,u=new Set;for(let a of e){let l=`${a.hash}:${a.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof a.hash==="string"?J.decode(a.hash):a.hash,m=a.witnessUtxo?pt(a.witnessUtxo.script):void 0,f=a.publicKey&&a.witnessUtxo?ir({chain:r,network:i,publicKey:a.publicKey,script:a.witnessUtxo.script}):{};if(p&&a.witnessUtxo&&eo(m,f.redeemScript))n.addInput({...f,index:a.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(a.witnessUtxo.value),script:a.witnessUtxo.script}});else if(a.txHex)n.addInput({...f,index:a.index,nonWitnessUtxo:J.decode(a.txHex),sequence:c,txid:h,...r===be.BitcoinCash?{sighashType:nr.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let a of t){let l="address"in a&&a.address?a.address:o;if(r===be.BitcoinCash)l=G(l);if(a.script)if(s)n.addOutput({amount:0n,script:s});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else n.addOutputAddress(l,BigInt(a.value),i)}return{inputs:e,tx:n}}async function we(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Qt(t,N.Fast),[N.Fastest]:Qt(t,N.Fastest)}}async function ar({assetValue:e,recipient:t,memo:r,sender:n,sweep:o,fetchTxHex:s=!1,publicKey:d},i,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ge(n,c),a=u===ie.P2PKH||u===ie.P2SH_P2WPKH&&!to(n,c,d),l=s||!p&&a,h=e.getBaseValue("number"),m=o?void 0:i??(await we(c))[N.Fastest],f=o||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:n,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:o?0:h},...r?[{address:"",script:E(r),value:0}]:[]]}}async function cr({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,fetchTxHex:s=!1,enableRBF:d=!1,sweep:i,publicKey:p}){let c=e.chain,u=r?E(r):null,a=await ar({assetValue:e,fetchTxHex:s,memo:r,publicKey:p,recipient:t,sender:o,sweep:i},n),{inputs:l,outputs:h}=M({...a,chain:c,changeAddress:o,feeRate:n,sweep:i});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ce({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:o,tx:f});return{inputs:y,tx:b,utxos:a.inputs}}async function dr({assetValue:e,feeOptionKey:t=N.Fast,feeRate:r,memo:n,sender:o,recipient:s,sweep:d}){let i=e.chain,p,c;if(r!==void 0)p=r,c=Math.floor(r);else{let a=await we(i);p=a[N.Fastest],c=a[t]}let u=await ar({assetValue:e,memo:n,recipient:s,sender:o,sweep:d},p,{forEstimateOnly:!0});return M({...u,chain:i,changeAddress:o,feeRate:c,sweep:d})}function no(e){return async function({from:r,memo:n,feeRate:o,feeOptionKey:s=N.Fast,recipient:d=r,recipients:i=1}){let p=o??(await we(e))[s],u=(await A(e).getUtxos({address:r,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Ke(e),se(f,e)*p));if(!u.length)return gt.from({chain:e});let a=typeof i==="number"?Math.max(i,1):i.length,l=typeof i==="number"||a===0?Array.from({length:a||1},()=>({address:d,value:0})):[...i];if(n)l.push({address:r,script:E(n),value:0});let{outputs:h}=M({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return gt.from({chain:e,value:BigInt(m)})}}function oo(e){return async function(r){let{fee:n}=await dr(r);return gt.from({chain:e,value:Ln.fromBigInt(BigInt(n),8).getValue("string")})}}function so({chain:e,phrase:t,derivationPath:r,scriptType:n,seed:o}){let s=U(e),{privateKey:d,publicKey:i}=xe({chain:e,derivationPath:r,phrase:t,seed:o}),p=ur(e);return{getAddress:()=>De({chain:e,network:s,publicKey:i,scriptType:n}),privateKey:d,publicKey:i,signTransaction:(c)=>{for(let{index:u,...a}of wt({chain:e,network:s,publicKey:i,tx:c}))c.updateInput(u,a);return c.sign(d,p),c}}}function ur(e){return e===be.BitcoinCash?[nr.ALL]:[er.ALL,er.DEFAULT]}function io(e,t,r){return async function({memo:o,recipient:s,feeOptionKey:d,feeRate:i,assetValue:p,enableRBF:c=!1,sweep:u}){let a=await t?.getAddress();if(!(t&&a))throw new P("toolbox_utxo_no_signer");if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});qn({condition:c&&!Qe.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Qe.includes(e),h=i||(await we(e))[d||N.Fast],{tx:m}=await cr({assetValue:p,enableRBF:l,feeRate:h,memo:o,publicKey:r,recipient:s,sender:a,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(J.encode(f.extract()))}}function pr(e){return(t)=>sr({address:t,chain:e})}function lr(e,{scriptType:t}){let r=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:r,publicKey:o.publicKey,scriptType:t})}}function ao(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function de(e){let{chain:t}=e,r=e.phrase?e:void 0;if(!r&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let n=r?.phrase,o=r?.index??0,s=n?bt(n):void 0,{derivationPath:d,scriptType:i}=Le({chain:t,derivationPath:r?.derivationPath,index:o,scriptType:e.scriptType}),p=Fe(d),c=n?so({chain:t,derivationPath:p,phrase:n,scriptType:i,seed:s}):void 0,u=r?void 0:e.signer,a=c||u,l=n?xe({chain:t,derivationPath:p,phrase:n,seed:s}):void 0,h=l?.publicKey??ao(u);function m(){if(a)return a.getAddress();return Promise.resolve(void 0)}function f(T){if(!n)return;let g=re({accountIndex:T,chain:t,derivationPath:d});return Qn({chain:t,derivationPath:Fe(g),phrase:n,seed:s})}let y=f();function b(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=re({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Fe(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let v=T===void 0?y:f(T);if(!v)return;let x=Oe({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=v.deriveChild(Number(w)).deriveChild(g);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:K,publicKey:I.publicKey,scriptType:i}),F=J.encode(I.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Fe(x),pubkey:F}}async function q(T){if(!Qe.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Ue({txid:T,newFeeRate:g,recipient:w,memo:v}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let K=x.inputs.reduce((_,D)=>_+D.value,0),B=x.outputs.find((_)=>_.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let F=await Promise.all(x.inputs.map(async(_)=>{let D=await A(t).getRawTx(_.transaction_hash),k=Je.fromRaw(J.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(_.index);return{address:_.recipient,hash:_.transaction_hash,index:_.index,publicKey:h,txHex:D,value:_.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=v?E(v):null,ee=K-B-x.fee,_e=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(ee>Ke(t)&&_e)ue.push({address:_e,value:ee});let He=ge({chain:t,inputs:F.map((_)=>({..._,type:Ge(_.address,t)})),outputs:[{address:w,value:B},...ue]}),Y=Math.ceil(He*g);if(Y<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:x.fee});let ve=Y-x.fee,te=B-ve;if(te<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Ae=new Je({allowUnknownOutputs:!!H,version:1}),rt=[{address:w,value:te},...ue];return ce({chain:t,compiledMemo:H,inputs:F,outputs:rt,sender:_e||w,tx:Ae}),{feeDelta:ve,newFee:Y,originalFee:x.fee,tx:Ae}}async function Or({txid:T,newFeeRate:g,recipient:w,memo:v}){let{tx:x,originalFee:K,newFee:I}=await Ue({memo:v,newFeeRate:g,recipient:w,txid:T}),B=await tt(x);B.finalize();let F=await A(t).broadcastTx(J.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function vt({accountIndex:T,index:g,change:w=!1}){z("index",g);let v=T===void 0?y:f(T);if(!v)return;return v.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function At({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=ur(t),v=U(t);for(let x=0;x<g.length;x++){let K=g[x];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=vt({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${I}`});for(let{index:H,...ee}of wt({chain:t,indexes:[x],network:v,publicKey:xt(F),tx:T}))T.updateInput(H,ee);T.signIdx(F,x,w)}return T}async function Sr({utxos:T,recipient:g,assetValue:w,memo:v,feeRate:x,feeOptionKey:K,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let F=x||(await we(t))[K||N.Fast],H=v?E(v):null,ee=[{address:g,value:w.getBaseValue("number")}];if(H)ee.push({address:"",script:H,value:0});let _e=T.map(({address:_,hash:D,index:k,value:nt,txHex:kr,witnessUtxo:ot})=>({address:_,hash:D,index:k,txHex:kr,value:nt,witnessUtxo:ot?{script:ot.script,value:ot.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:Y,outputs:ve}=M({chain:t,changeAddress:He,feeRate:F,inputs:_e,outputs:ee});if(!(Y&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let te=new Je({allowUnknownOutputs:!!H,version:1}),Ae=Y.map((_)=>{let D=T.find((k)=>k.hash===_.hash&&k.index===_.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),rt=Y.map((_,D)=>{let k=Ae[D],nt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{..._,publicKey:nt??void 0}});return ce({chain:t,compiledMemo:H,inputs:rt,outputs:ve,sender:He,tx:te}),At({inputDerivations:Ae,tx:te}),te.finalize(),A(t).broadcastTx(J.encode(te.extract()))}function Cr({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let v=X({change:!1,index:w}),x=X({change:!0,index:w}),K=v?.address===T?!1:x?.address===T;if(v?.address===T||x?.address===T)return{change:K,index:w}}return}function tt(T){if(!a)throw new P("toolbox_utxo_no_signer");return a.signTransaction(T)}let Xr=t===be.Bitcoin&&l?async(T)=>Jt({message:T,privateKey:l.privateKey,scriptType:i}):void 0;async function Br(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(J.encode(g.extract()))}return{accumulative:M,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:Or,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Ue,createTransaction:(T)=>cr({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:no(t),estimateTransactionFee:oo(t),getAddress:m,getAddressFromKeys:lr(t,{scriptType:i}),getAddressType:(T)=>j({address:T,chain:t}),getBalance:tr(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>we(t),getInputsOutputsFee:dr,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Jn(xe({...T,chain:t}).privateKey,t),isRBFEnabled:q,keys:l,resolveDerivationIndex:Cr,scriptType:i,signAndBroadcastTransaction:Br,signMessage:Xr,signTransaction:tt,signTransactionWithMultipleKeys:At,transfer:io(t,a,h),transferFromMultipleAddresses:Sr,validateAddress:pr(t)}}import{getZcashAddressType as co,validateZcashAddress as Pt}from"@swapkit/utxo-signer";function Ie(e){return Ce(e)!==null}var Z=uo.BitcoinCash;function et(e){return W(Me(e))}function mo(e){let t=U(Z);function r(o){return o.sign(e.privateKey,[fo.ALL]),o}function n(){let o=yr(e.publicKey,t);if(!o.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let s=mr({hash:o.hash,prefix:fr.MAINNET,type:Tr.P2PKH});return Promise.resolve(s.replace(/^bitcoincash:/,""))}return{getAddress:n,signTransaction:r}}function xr(e={}){let t="phrase"in e?e.phrase:void 0,r="index"in e?e.index||0:0,n="derivationPath"in e?e.derivationPath:void 0,o=ho({chain:Z,derivationPath:n,index:r}),s=po(o),d=t?xe({chain:Z,derivationPath:s,phrase:t}):void 0,i=d?mo(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(i?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:a,broadcastTx:l,...h}=de(t?{chain:Z,index:r,phrase:t,...n?{derivationPath:n,scriptType:c}:{scriptType:c}}:{chain:Z,scriptType:c});function m(b,S=!0){return u(W(Me(b)))}function f(b){if(!i)throw new L("toolbox_utxo_no_signer");return i.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(hr.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:go,createTransaction:br,getAddress:p,getAddressFromKeys:xo,getBalance:m,getFeeRates:a,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:W,stripToCashAddress:et,transfer:yo({broadcastTx:l,getFeeRates:a,signer:i}),validateAddress:Ie}}async function br({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,sweep:s}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+n*7500),i=await A(Z).getUtxos({address:et(o),fetchTxHex:!0,targetValue:s?void 0:d}),p=r?E(r):null,c=[],u=G(t);if(c.push({address:u,value:s?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:a,outputs:l}=M({chain:Z,feeRate:n,inputs:i,outputs:c,sweep:s});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!p,version:1}),m=G(o),{inputs:f,tx:y}=ce({chain:Z,compiledMemo:p,inputs:a,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:a}}function yo({broadcastTx:e,getFeeRates:t,signer:r}){return async function({recipient:o,assetValue:s,feeOptionKey:d=lo.Fast,sweep:i,...p}){let c=await r?.getAddress();if(!(r&&c))throw new L("toolbox_utxo_no_signer");if(!o)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:a}=await br({...p,assetValue:s,feeRate:u,recipient:o,sender:c,sweep:i}),l=await r.signTransaction(a);return l.finalize(),e(hr.encode(l.extract()))}}async function go({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o}){let s=Me(t);if(!Ie(s))throw new L("toolbox_utxo_invalid_address",{address:s});let d=Math.ceil(e.getBaseValue("number")+n*7500),i=await A(Z).getUtxos({address:et(o),fetchTxHex:!0,targetValue:d}),p=Number(n.toFixed(0)),c=r?E(r):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:a,outputs:l}=M({chain:Z,feeRate:p,inputs:i,outputs:u});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ce({chain:Z,compiledMemo:c,inputs:a,outputs:l,sender:G(o),tx:h});return{inputs:m,tx:f,utxos:i}}function xo(e){let t=To.bitcoinCash,r=yr(e.publicKey,t);if(!r.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return mr({hash:r.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as bo,hex as wo}from"@scure/base";import{HDKey as Ur}from"@scure/bip32";import{mnemonicToSeedSync as _r}from"@scure/bip39";import{Chain as V,derivationPathToString as Po,FeeOption as Uo,SwapKitError as Q}from"@swapkit/helpers";import{Address as _o,createZcashTransaction as vo,getZcashTransactionFormat as Ao,isTransparentZcashAddress as wr,OutScript as Oo,PCZT as So,utils as vr,WIF as Co,ZcashPSBT as Xo,ZcashSigHash as Ut}from"@swapkit/utxo-signer";import{match as Bo,P as _t}from"ts-pattern";var ko=bo(vr.sha256);function Ko(e){return ko.encode(e)}function Fo({phrase:e,derivationPath:t}){let r=_r(e),o=Ur.fromMasterSeed(r).derive(t);if(!o.privateKey||!o.publicKey)throw new Q("toolbox_utxo_invalid_params");let{privateKey:s,publicKey:d}=o,i=vr.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let u=Ko(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(a)=>{if(a instanceof Xo){let l=a.toPCZT();return l.signAllInputs(s,d,Ut.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(a instanceof So)return a.signAllInputs(s,d,Ut.ALL),a.finalizeAllInputs(),Promise.resolve(a.extract());return a.signAllInputs(s,d,Ut.ALL),Promise.resolve(a)}}}function Do({inputs:e,outputs:t,tx:r,sender:n,compiledMemo:o}){let s=U(V.Zcash);for(let d of e){let i=_o(s).decode(n),p=Oo.encode(i);r.addInput({index:d.index,script:p,sequence:4294967295,txid:wo.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let i="address"in d&&d.address?d.address:n,p=d.script;if(p&&!o)continue;if(p&&o)r.addOutput({amount:0n,script:o});else r.addOutputAddress(i,BigInt(d.value),s)}return{inputs:e,tx:r}}async function Io(){try{let e=await A(V.Zcash).getBlockHeight();return Ao(e+1)}catch(e){throw new Q({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function Pr(e){let{assetValue:t,recipient:r,memo:n,feeRate:o,sender:s,fetchTxHex:d,sweep:i}=e,p=U(V.Zcash);if(!wr(s,p))throw new Q("toolbox_utxo_invalid_address",{address:s});if(!wr(r,p))throw new Q("toolbox_utxo_invalid_address",{address:r,error:"Zcash transaction creation currently supports transparent addresses only"});let c=n?E(n):null,u=await A(V.Zcash).getUtxos({address:s,fetchTxHex:d!==!1}),a=[{address:r,value:i?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=M({chain:V.Zcash,changeAddress:s,feeRate:o,inputs:u,outputs:a,sweep:i});if(!(l&&h))throw new Q("toolbox_utxo_insufficient_balance",{assetValue:t,sender:s});let m=vo({...await Io(),expiryHeight:0,lockTime:0}),{tx:f,inputs:y}=Do({compiledMemo:c,inputs:l,outputs:h,sender:s,tx:m});return{inputs:y,outputs:h,tx:f}}function Ar(e={}){let t="scriptType"in e?e.scriptType:void 0,r=Bo(e).with({signer:_t.not(_t.nullish)},({signer:c})=>c).with({phrase:_t.string},({phrase:c,derivationPath:u,index:a=0})=>{let{derivationPath:l}=Le({chain:V.Zcash,derivationPath:u,index:a,scriptType:t}),h=Po(l);return Fo({derivationPath:h,phrase:c})}).otherwise(()=>{return}),n=de({chain:V.Zcash,scriptType:t,signer:r});async function o(c){if(!r)throw new Q("toolbox_utxo_no_signer");return await r.signTransaction(c)}async function s(c){let u=await o(c);return n.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:a=Uo.Fast,sweep:l,...h}){let m=await r?.getAddress();if(!(r&&m))throw new Q("toolbox_utxo_no_signer");let f=h.feeRate||(await n.getFeeRates())[a],{tx:y}=await Pr({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await r.signTransaction(y)).toHex();return n.broadcastTx(S)}function i({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=_r(c),h=Ur.fromMasterSeed(a).derive(u);if(!h.privateKey||!h.publicKey)throw new Q("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=i({derivationPath:u,phrase:c}),l=U(V.Zcash);return Co(l).encode(a.privateKey)}return{...n,createKeysForPath:i,createTransaction:Pr,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:s,signTransaction:o,transfer:d,validateAddress:Pt}}import{hex as Ho}from"@scure/base";import{HDKey as Ro}from"@scure/bip32";import{derivationPathToString as Eo,NetworkDerivationPath as Mo,updateDerivationPath as No}from"@swapkit/helpers";function Zo({xpub:e,chain:t,count:r,startIndex:n=0,accountIndex:o,purpose:s,scriptType:d}){if(z("count",r),r<1)throw RangeError("count must be at least 1");z("startIndex",n),$e(t,d),dt({chain:t,purpose:s,scriptType:d});let i=U(t),p=Ro.fromExtendedKey(e,i.bip32),c=s===void 0?void 0:No(Mo[t],{purpose:s}),u=re({accountIndex:o,chain:t,derivationPath:c}),a=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<r;f++){let y=n+f,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Oe({accountIndex:o,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:a,address:De({chain:t,network:i,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:Ho.encode(b.publicKey),...s===void 0?{}:{path:Eo(S)}})}}return l}function Ii(e,t){switch(e){case Pe.BitcoinCash:return xr(t||{});case Pe.Zcash:return Ar(t);case Pe.Bitcoin:case Pe.Dogecoin:case Pe.Litecoin:case Pe.Dash:return de({chain:e,...t});default:throw new zo("toolbox_utxo_not_supported",{chain:e})}}export{Yt as InputSizes,_s as MIN_TX_FEE,Fn as OP_RETURN_OVERHEAD,lt as OutputSizes,Kn as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,ie as UTXOScriptType,It as UtxoNetwork,M as accumulative,ce as addInputsAndOutputs,lr as addressFromKeysGetter,z as assertDerivationIndex,ge as calculateTxSize,Zn as canSignBitcoinMessage,E as compileMemo,xr as createBCHToolbox,Yo as createCustomUtxoApi,Fr as createHDWalletHelpers,de as createUTXOToolbox,Ar as createZcashToolbox,Zo as deriveAddressesFromXpub,ss as detectAddressNetwork,Ce as getBchAddressType,Ke as getDustThreshold,ke as getInputScriptType,se as getInputSize,wt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Dn as getOutputSizeForAddress,Ge as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,re as getUTXOAccountPath,Oe as getUTXOAddressPath,pr as getUTXOAddressValidator,j as getUtxoAddressType,A as getUtxoApi,Go as getUtxoNetwork,Ii as getUtxoToolbox,Tt as getWitnessOverhead,co as getZcashAddressType,ft as isSegwitScriptType,os as isValidAddress,zt as nonSegwitChains,W as stripPrefix,et as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,sr as validateUtxoAddress,Pt as validateZcashAddress};
1
+ import{ia as St,ja as tr}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as Kr}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function re({accountIndex:e,chain:t,derivationPath:r}){if(e!==void 0)Z("accountIndex",e);let[n,o,i]=r??Kr[t];return[n,o,e??i]}function Oe({accountIndex:e,change:t=!1,chain:r,derivationPath:n,index:o}){return Z("index",o),[...re({accountIndex:e,chain:r,derivationPath:n}),Number(t),o]}function pe(e){return e[2]??0}function Fr({deriveAddress:e,getBalance:t,getUtxos:r}){async function n(s){let{accountIndex:p,count:c,startIndex:u=0,change:a=!1}=s;if(Z("count",c),c<1)throw RangeError("count must be at least 1");Z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:a,index:u+h});if(m)l.push(m)}return l}async function o(s){let{gapLimit:p=20,change:c=!1}=s??{},u=[],a=0,l=0;while(a<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),a=0;else a++;l++}return u}async function i(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c],a=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,x)=>y+x.getValue("number"),0);return{...h,balance:f}})),l=a.reduce((h,m)=>h+m.balance,0);return{addresses:a,total:l}}async function d(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await r(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:n,getAggregatedBalance:i,getAggregatedUtxos:d,scanForAddresses:o}}import{Chain as C,getRPCUrl as Dr,RequestClient as Re,SKConfig as Ct,SwapKitError as R,warnOnce as Ir}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Hr({chain:e,txHash:t}){let r=`${he(e)}/push/transaction`,n=JSON.stringify({data:t});try{let o=await Re.post(r,{body:n,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let i=await Dr(e);if(i){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),s=await Re.post(i,{body:d,headers:{"Content-Type":"application/json"}});if(s.error)throw new R("toolbox_utxo_broadcast_failed",{error:s.error?.message});if(s.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return s.result}throw o}}function he(e){return`${(Ct.get("blockchairApiUrl")||"https://api.blockchair.com").replace(/\/+$/,"")}/${Rr(e)}`}function At(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Rr(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function Mr(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),r=t/1000;return Math.max(r,At(e))}catch{return At(e)}}async function Se(e,t){let r=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!r||r.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return r.data}async function Er({chain:e,apiKey:t}){let r=await Se(`${he(e)}/stats`,t);if(typeof r.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return r.best_block_height}async function Xt({address:e,chain:t,apiKey:r}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Se(`${he(t)}/dashboards/address/${e}?transaction_details=true`,r))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Nr({address:e,chain:t,apiKey:r}){return(await Xt({address:e,apiKey:r,chain:t}))?.address.balance||0}async function Bt({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Se(`${he(e)}/raw/transaction/${r}`,t))?.[r]?.raw_transaction||""}catch(n){let o=n instanceof Error?n.message:String(n);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var Wr=4294967294;async function Zr({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Se(`${he(e)}/dashboards/transaction/${r}`,t))?.[r];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:r});let{transaction:i,inputs:d,outputs:s}=o,p=d.map((u)=>u.spending_sequence),c=i.is_rbf===!0||p.some((u)=>u<Wr);return{blockId:i.block_id,confirmed:i.block_id!==-1,fee:i.fee,inputs:d,isRBF:c,outputs:s,sequences:p,size:i.size,txid:i.hash,weight:i.weight}}async function zr({chain:e,address:t,apiKey:r,offset:n=0,limit:o=30}){return(await Se(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${o}&offset=${n}`,r)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:a,index:l,value:h,spending_signature_hex:m})=>({hash:a,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function $r(e){return e.reduce((t,r)=>t+r.value,0)}function Ot(e,t){let r=[...e].sort((n,o)=>o.value-n.value);if(t){let n=[],o=0;for(let i of r)if(n.push(i),o+=i.value,o>=t)break;return n}return r}async function kt({chain:e,address:t,apiKey:r,targetValue:n,accumulativeValue:o=0,offset:i=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let s=await zr({address:t,apiKey:r,chain:e,limit:d,offset:i,targetValue:n}),c=s.length<d,u=s.filter(({is_spent:y})=>!y),a=$r(u),l=o+a,h=n&&l>=n;if(c||h)return Ot(u,n);let m=await kt({accumulativeValue:l,address:t,apiKey:r,chain:e,limit:d,offset:i+d,targetValue:n}),f=[...u,...m];return Ot(f,n)}catch(s){let p=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Lr({address:e,chain:t,apiKey:r,fetchTxHex:n=!0,targetValue:o}){let i=await kt({address:e,apiKey:r,chain:t,targetValue:o}),d=n?await Promise.all(i.map(({hash:s})=>Bt({apiKey:r,chain:t,txHash:s}))):[];return i.map(({hash:s,index:p,script_hex:c,value:u},a)=>({address:e,hash:s,index:p,txHex:n?d[a]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=Ct.get("apiKeys").blockchair||"";return Ir({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(r)=>Hr({chain:e,txHash:r}),getAddressData:(r)=>Xt({address:r,apiKey:t,chain:e}),getBalance:(r)=>Nr({address:r,apiKey:t,chain:e}),getBlockHeight:()=>Er({apiKey:t,chain:e}),getRawTx:(r)=>Bt({apiKey:t,chain:e,txHash:r}),getSuggestedTxFee:()=>Mr(e),getTransactionDetails:(r)=>Zr({apiKey:t,chain:e,txHash:r}),getUtxos:(r)=>Lr({...r,apiKey:t,chain:e})}}function Lo(e){return e}function Vo(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Qr}from"@noble/hashes/sha2.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as Ft}from"@swapkit/helpers";import{CashAddrType as Me,decodeCashAddr as Vr,encodeCashAddr as qr}from"@swapkit/utxo-signer";var Yr={P2PKH:Me.P2PKH,P2SH:Me.P2SH},Gr={[Me.P2PKH]:"P2PKH",[Me.P2SH]:"P2SH"};function jr(e,t,r){return qr({hash:r,prefix:e,type:Yr[t]})}function Jr(e){let t=Vr(e),r=Gr[t.type];if(!r)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:r}}var st={decode:Jr,encode:jr};var Dt=en(Qr);var It;((r)=>{r.Mainnet="mainnet";r.Testnet="testnet"})(It||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},tn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function ts(e){return Ne(e)!==void 0}function rs(e){return it(e).network}function G(e){let t=it(e);if(t.format==="legacy")return e;return on(t)}function Ee(e){let t=it(e);return sn(t)}function Ne(e){if(typeof e!=="string")return;let t=rn(e)??nn(e);return t&&{...t,scriptType:tn[t.type]}}function it(e){let t=Ne(e);if(!t)throw new Ft("toolbox_utxo_invalid_address",{address:e});return t}function rn(e){try{let t=Dt.decode(e);if(t.length!==21)throw new Ft("toolbox_utxo_invalid_address",{address:e});let r=t[0],n=Array.prototype.slice.call(t,1);switch(r){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:n,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:n,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:n,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:n,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function nn(e){if(e.indexOf(":")!==-1)try{return Kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let r of t)try{return Kt(`${r}:${e}`)}catch{}}return}function Kt(e){try{let{hash:t,prefix:r,type:n}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:r==="bitcoincash"?"mainnet":"testnet",type:n==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function on(e){let t=ne.legacy[e.network][e.type],r=Buffer.alloc(1+e.hash.length);return r[0]=t,r.set(e.hash,1),Dt.encode(r)}function sn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",r=e.type==="p2pkh"?"P2PKH":"P2SH",n=new Uint8Array(e.hash);return st.encode(t,r,n)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as On,UTXO_SCRIPT_TYPES as Vt,UTXOScriptType as Ye}from"@swapkit/helpers";import{Script as Sn}from"@swapkit/utxo-signer";import{Chain as Ht}from"@swapkit/helpers";import{getAddressScriptType as cn,getZcashAddressType as dn}from"@swapkit/utxo-signer";import{match as un}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as an}from"ts-pattern";function U(e){return an(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ce(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function j({address:e,chain:t}){return un(t).with(Ht.BitcoinCash,()=>Ce(e)).with(Ht.Zcash,()=>dn(e)).otherwise(()=>cn(e,U(t)))}import{Chain as oe,derivationPathToString as Rt,getPurposeFromPath as pn,getUTXOScriptTypeForPath as Mt,getUTXOScriptTypeForPurpose as Wt,resolveDerivationPath as ln,SwapKitError as Xe,UTXO_SCRIPT_TYPE_LIST as Et,UTXO_SCRIPT_TYPES as me,UTXOChains as hn,UTXOScriptType as O,updateDerivationPath as fn,warnOnce as Tn}from"@swapkit/helpers";import{CashAddrPrefix as mn,CashAddrType as yn,encodeCashAddr as gn,OutScript as Zt,p2pkh as xn,p2sh as bn,p2tr as wn,p2wpkh as Nt}from"@swapkit/utxo-signer";var We=Object.freeze([O.P2PKH]),Pn=Object.freeze({[oe.Bitcoin]:Et,[oe.BitcoinCash]:We,[oe.Dash]:We,[oe.Dogecoin]:We,[oe.Litecoin]:Et,[oe.Zcash]:We});function ze(e){return Pn[e]}function ct(e){return ze(e).some((t)=>me[t].witness)}function ye(e,t){return ze(e).includes(t)}function $e(e,t){if(ye(e,t))return t;throw new Xe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${ze(e).join(", ")}`,scriptType:t,supported:ze(e)})}var zt=hn.filter((e)=>!ct(e));function Un({purpose:e,scriptType:t}){let r=Wt(e);return r===void 0||r===t}function dt({chain:e,purpose:t,scriptType:r}){Tn({condition:!Un({purpose:t,scriptType:r}),id:`utxo_off_standard_encoding_${e}_${t}_${r}`,warning:`${e}: encoding m/${t}' keys as ${r}, not the ${Wt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Le({chain:e,derivationPath:t,index:r=0,scriptType:n}){if(t){if(!n){let s=Mt(t);throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${s?` (${s})`:""}, or state another deliberately.`})}return $e(e,n),dt({chain:e,purpose:pn(t),scriptType:n}),{derivationPath:t,scriptType:n}}let o=ln({chain:e,index:r}),i=n?fn(o,{purpose:me[n].purpose}):o,d=n??Mt(i);if(!d)throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(i),error:`${e}: the default derivation path has no standard script type`});return $e(e,d),{derivationPath:i,scriptType:d}}function _n(e){return e.length===32?e:e.slice(1)}function Ze(e,t){if(!e.address)throw new Xe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vn={[O.P2PKH]:(e,t)=>{let{address:r,script:n}=Ze(xn(e,t),O.P2PKH);return{address:r,script:n}},[O.P2SH_P2WPKH]:(e,t)=>{let r=Nt(e,t),{address:n,script:o}=Ze(bn(r,t),O.P2SH_P2WPKH);return{address:n,redeemScript:r.script,script:o}},[O.P2WPKH]:(e,t)=>{let{address:r,script:n}=Ze(Nt(e,t),O.P2WPKH);return{address:r,script:n}},[O.P2TR]:(e,t)=>{let r=_n(e),{address:n,script:o}=Ze(wn(r,void 0,t),O.P2TR);return{address:n,script:o,tapInternalKey:r}}};function Ve(e,t,r){return vn[e](t,r)}function ut(e,t){if(e!==oe.BitcoinCash)return t.address;let r=Zt.decode(t.script);if(r.type!=="pkh")throw new Xe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${r.type} as CashAddr`});return gn({hash:r.hash,prefix:mn.MAINNET,type:yn.P2PKH}).replace(/^bitcoincash:/,"")}var An=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),at=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function $t(e){return e in at}function Lt(e){if(e==="tex")return at.pkh;return $t(e)?at[e]:void 0}function Be(e){return An[e]}function pt(e){try{let{type:t}=Zt.decode(e);return $t(t)?Be(t):void 0}catch{return}}import{UTXOScriptType as ie}from"@swapkit/helpers";var ws=1000,ht=10,Cn=2,Xn=10;function M(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Sn.encode(["RETURN",t])}function qt(e){return Object.fromEntries(On.map((t)=>[t,Vt[t][e]]))}var Yt=qt("inputSize"),lt=qt("outputSize"),ft=(e)=>Vt[e].witness,Ge=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Be(r);if(!n||!ye(t,n))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return n},Bn=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Lt(r);if(!n)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return n},ge=({chain:e,inputs:t,outputs:r,feeRate:n})=>{let o=t[0]?ke(t[0],e):Ye.P2PKH,i=n?t.filter((u)=>u.value>=Yt["type"in u&&u.type?u.type:Ye.P2PKH]*Math.ceil(n)):t,d=0,s=0;for(let u of i)if(d+=se(u,e),!ft(ke(u,e)))s++;let p=r?.reduce((u,a)=>u+je(a,e),0)||lt[o],c=s<i.length;return ht+d+p+Tt(c,s)},ke=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ge(e.address,t);return Ye.P2PKH},se=(e,t)=>Yt[ke(e,t)],Tt=(e,t)=>e?Math.ceil((Cn+t)/4):0,je=(e,t,r)=>{if(e?.script)return Xn+e.script.length+(e.script.length>=74?2:1);if(r)return lt[r];if("address"in e&&e.address)return Bn(e.address,t);return lt[Ye.P2PKH]};function Ke(e){switch(e){case ae.Bitcoin:case ae.BitcoinCash:return 550;case ae.Dash:case ae.Litecoin:return 5500;case ae.Dogecoin:return 1e5;case ae.Zcash:return 546;default:throw new mt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:r=1,chain:n=ae.Bitcoin,changeAddress:o="",sweep:i=!1}){let d=Ke(n),s=e.filter((f)=>{let y=se(f,n)*r;return i?f.value>Math.max(y,d):y<=f.value});if(i){let f=Math.ceil(r*ge({chain:n,inputs:s,outputs:t})),y=s.reduce((X,q)=>X+q.value,0),x=y-f;if(x<=d)throw new mt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new mt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:s,outputs:t.map((X,q)=>q===S?{...X,value:x}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,n),0),c=t.reduce((f,y)=>f+y.value,0),u=0,a=0,l=!1,h=0,m=[];for(let f of s){if(u+=se(f,n),ft(ke(f,n)))l=!0;else a++;h+=f.value,m.push(f);let y=(p+u+Tt(l,a))*r,x=y+c;if(h<x)continue;let S=h-x,X=r*je({address:o,value:0},n);if(S>X){let q=X+y,Ue=h-(c+Math.ceil(q));if(Ue>Math.max(se({value:0},n)*r,Ke(n)))return{fee:Math.ceil(q),inputs:m,outputs:t.concat({address:o,value:Ue})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(r*ge({chain:n,inputs:e,outputs:t}))}}import{secp256k1 as kn}from"@noble/curves/secp256k1.js";import{base64 as Kn,utf8 as Gt}from"@scure/base";import{SwapKitError as Fn,UTXOScriptType as yt}from"@swapkit/helpers";import{CompactSize as Dn,utils as In}from"@swapkit/utxo-signer";var Hn=Gt.decode(`\x18Bitcoin Signed Message:
2
+ `),jt={[yt.P2PKH]:31,[yt.P2SH_P2WPKH]:35,[yt.P2WPKH]:39};function Rn(e){return jt[e]!==void 0}function Mn(e){let t=Gt.decode(e);return In.sha256x2(Hn,Dn.encode(BigInt(t.length)),t)}function Jt({message:e,privateKey:t,scriptType:r}){let n=jt[r];if(n===void 0)throw new Fn("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${r} address`,scriptType:r});let o=kn.sign(Mn(e),t,{format:"recovered",prehash:!1}),[i=0]=o,d=new Uint8Array(65);return d[0]=n+i,d.set(o.subarray(1),1),Kn.encode(d)}import{Chain as Pe,SwapKitError as Eo}from"@swapkit/helpers";import{hex as hr}from"@scure/base";import{Chain as io,derivationPathToString as ao,FeeOption as co,resolveDerivationPath as uo,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as po,CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,NETWORKS as lo,p2pkh as yr,Transaction as gr}from"@swapkit/utxo-signer";import{secp256k1 as En}from"@noble/curves/secp256k1.js";import{hex as J}from"@scure/base";import{HDKey as rr}from"@scure/bip32";import{mnemonicToSeedSync as bt}from"@scure/bip39";import{AssetValue as gt,applyFeeMultiplier as Qt,Chain as be,derivationPathToString as Fe,FeeOption as N,NetworkDerivationPath as Nn,SwapKitError as P,SwapKitNumber as Wn,UTXO_SCRIPT_TYPES as Zn,warnOnce as zn}from"@swapkit/helpers";import{BCHSigHash as nr,RBF_SEQUENCE as $n,SigHash as er,Transaction as Je,utils as Ln,WIF as or}from"@swapkit/utxo-signer";var Qe=[be.Bitcoin];function sr({address:e,chain:t}){return j({address:e,chain:t})!==null}function Vn({phrase:e,derivationPath:t,network:r,seed:n}){let o=n??bt(e),d=rr.fromMasterSeed(o,r.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function xt(e){return En.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:r,scriptType:n}){return ut(t,Ve(n,e,r))}function xe({phrase:e,derivationPath:t,chain:r,wif:n,seed:o}){let i=U(r);if(n){let c=or(i).decode(n),u=xt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Fe(Nn[r]),s=Vn({derivationPath:d,network:i,phrase:e,seed:o}),p=xt(s);return{privateKey:s,publicKey:p}}function qn(e,t){return or(U(t)).encode(e)}function Yn({phrase:e,derivationPath:t,chain:r,seed:n}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let i=U(r),d=n??bt(e),s=rr.fromMasterSeed(d,i.bip32),p=o.slice(0,4).join("/");return s.derive(p)}function Gn(e,t){if(!e||!Zn[e].witness)return!1;return e!==ie.P2SH_P2WPKH||!!t}function ir({chain:e,script:t,publicKey:r,network:n}){let o=pt(t);if(o!==ie.P2SH_P2WPKH&&o!==ie.P2TR)return{};if(!ye(e,o))return{};let i=Ve(o,r,n);if(Ln.compareBytes(i.script,t)!==0)return{};return o===ie.P2TR?{tapInternalKey:i.tapInternalKey}:{redeemScript:i.redeemScript}}function jn(e,t,r){if(!r)return!1;let n=j({address:e,chain:t}),o=n?Be(n):void 0;if(!o||!ye(t,o))return!1;let i=ut(t,Ve(o,r,U(t)));return t===be.BitcoinCash?z(i)===z(e):i===e}function Jn(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function wt({chain:e,tx:t,publicKey:r,network:n,indexes:o}){let i=o??Array.from({length:t.inputsLength},(s,p)=>p),d=[];for(let s of i){let p=t.getInput(s),c=Jn(p);if(!c)continue;let{redeemScript:u,tapInternalKey:a}=ir({chain:e,network:n,publicKey:r,script:c}),l={index:s};if(u&&!p.redeemScript)l.redeemScript=u;if(a&&!p.tapInternalKey)l.tapInternalKey=a;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ce({inputs:e,outputs:t,chain:r,tx:n,sender:o,compiledMemo:i,enableRBF:d=!1}){let s=U(r),p=ct(r),c=d?$n:void 0,u=new Set;for(let a of e){let l=`${a.hash}:${a.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof a.hash==="string"?J.decode(a.hash):a.hash,m=a.witnessUtxo?pt(a.witnessUtxo.script):void 0,f=a.publicKey&&a.witnessUtxo?ir({chain:r,network:s,publicKey:a.publicKey,script:a.witnessUtxo.script}):{};if(p&&a.witnessUtxo&&Gn(m,f.redeemScript))n.addInput({...f,index:a.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(a.witnessUtxo.value),script:a.witnessUtxo.script}});else if(a.txHex)n.addInput({...f,index:a.index,nonWitnessUtxo:J.decode(a.txHex),sequence:c,txid:h,...r===be.BitcoinCash?{sighashType:nr.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let a of t){let l="address"in a&&a.address?a.address:o;if(r===be.BitcoinCash)l=G(l);if(a.script)if(i)n.addOutput({amount:0n,script:i});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else n.addOutputAddress(l,BigInt(a.value),s)}return{inputs:e,tx:n}}async function we(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Qt(t,N.Fast),[N.Fastest]:Qt(t,N.Fastest)}}async function ar({assetValue:e,recipient:t,memo:r,sender:n,sweep:o,fetchTxHex:i=!1,publicKey:d},s,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ge(n,c),a=u===ie.P2PKH||u===ie.P2SH_P2WPKH&&!jn(n,c,d),l=i||!p&&a,h=e.getBaseValue("number"),m=o?void 0:s??(await we(c))[N.Fastest],f=o||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:n,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:o?0:h},...r?[{address:"",script:M(r),value:0}]:[]]}}async function cr({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,fetchTxHex:i=!1,enableRBF:d=!1,sweep:s,publicKey:p}){let c=e.chain,u=r?M(r):null,a=await ar({assetValue:e,fetchTxHex:i,memo:r,publicKey:p,recipient:t,sender:o,sweep:s},n),{inputs:l,outputs:h}=E({...a,chain:c,changeAddress:o,feeRate:n,sweep:s});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:x}=ce({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:o,tx:f});return{inputs:y,tx:x,utxos:a.inputs}}async function dr({assetValue:e,feeOptionKey:t=N.Fast,feeRate:r,memo:n,sender:o,recipient:i,sweep:d}){let s=e.chain,p,c;if(r!==void 0)p=r,c=Math.floor(r);else{let a=await we(s);p=a[N.Fastest],c=a[t]}let u=await ar({assetValue:e,memo:n,recipient:i,sender:o,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:s,changeAddress:o,feeRate:c,sweep:d})}function Qn(e){return async function({from:r,memo:n,feeRate:o,feeOptionKey:i=N.Fast,recipient:d=r,recipients:s=1}){let p=o??(await we(e))[i],u=(await A(e).getUtxos({address:r,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Ke(e),se(f,e)*p));if(!u.length)return gt.from({chain:e});let a=typeof s==="number"?Math.max(s,1):s.length,l=typeof s==="number"||a===0?Array.from({length:a||1},()=>({address:d,value:0})):[...s];if(n)l.push({address:r,script:M(n),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return gt.from({chain:e,value:BigInt(m)})}}function eo(e){return async function(r){let{fee:n}=await dr(r);return gt.from({chain:e,value:Wn.fromBigInt(BigInt(n),8).getValue("string")})}}function to({chain:e,phrase:t,derivationPath:r,scriptType:n,seed:o}){let i=U(e),{privateKey:d,publicKey:s}=xe({chain:e,derivationPath:r,phrase:t,seed:o}),p=ur(e);return{getAddress:()=>De({chain:e,network:i,publicKey:s,scriptType:n}),privateKey:d,publicKey:s,signTransaction:(c)=>{for(let{index:u,...a}of wt({chain:e,network:i,publicKey:s,tx:c}))c.updateInput(u,a);return c.sign(d,p),c}}}function ur(e){return e===be.BitcoinCash?[nr.ALL]:[er.ALL,er.DEFAULT]}function ro(e,t,r){return async function({memo:o,recipient:i,feeOptionKey:d,feeRate:s,assetValue:p,enableRBF:c=!1,sweep:u}){let a=await t?.getAddress();if(!(t&&a))throw new P("toolbox_utxo_no_signer");if(!i)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});zn({condition:c&&!Qe.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Qe.includes(e),h=s||(await we(e))[d||N.Fast],{tx:m}=await cr({assetValue:p,enableRBF:l,feeRate:h,memo:o,publicKey:r,recipient:i,sender:a,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(J.encode(f.extract()))}}function pr(e){return(t)=>sr({address:t,chain:e})}function lr(e,{scriptType:t}){let r=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:r,publicKey:o.publicKey,scriptType:t})}}function no(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function de(e){let{chain:t}=e,r=e.phrase?e:void 0;if(!r&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let n=r?.phrase,o=r?.index??0,i=n?bt(n):void 0,{derivationPath:d,scriptType:s}=Le({chain:t,derivationPath:r?.derivationPath,index:o,scriptType:e.scriptType}),p=Fe(d),c=n?to({chain:t,derivationPath:p,phrase:n,scriptType:s,seed:i}):void 0,u=r?void 0:e.signer,a=c||u,l=n?xe({chain:t,derivationPath:p,phrase:n,seed:i}):void 0,h=l?.publicKey??no(u);function m(){if(a)return a.getAddress();return Promise.resolve(void 0)}function f(T){if(!n)return;let g=re({accountIndex:T,chain:t,derivationPath:d});return Yn({chain:t,derivationPath:Fe(g),phrase:n,seed:i})}let y=f();function x(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=re({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Fe(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let v=T===void 0?y:f(T);if(!v)return;let b=Oe({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=v.deriveChild(Number(w)).deriveChild(g);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:K,publicKey:I.publicKey,scriptType:s}),F=J.encode(I.publicKey);return{accountIndex:pe(b),address:B,change:w,index:g,path:Fe(b),pubkey:F}}async function q(T){if(!Qe.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Ue({txid:T,newFeeRate:g,recipient:w,memo:v}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let b=await A(t).getTransactionDetails(T);if(!b.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(b.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:T});let K=b.inputs.reduce((_,D)=>_+D.value,0),B=b.outputs.find((_)=>_.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let F=await Promise.all(b.inputs.map(async(_)=>{let D=await A(t).getRawTx(_.transaction_hash),k=Je.fromRaw(J.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(_.index);return{address:_.recipient,hash:_.transaction_hash,index:_.index,publicKey:h,txHex:D,value:_.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=v?M(v):null,ee=K-B-b.fee,_e=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(ee>Ke(t)&&_e)ue.push({address:_e,value:ee});let He=ge({chain:t,inputs:F.map((_)=>({..._,type:Ge(_.address,t)})),outputs:[{address:w,value:B},...ue]}),Y=Math.ceil(He*g);if(Y<=b.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:b.fee});let ve=Y-b.fee,te=B-ve;if(te<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Ae=new Je({allowUnknownOutputs:!!H,version:1}),rt=[{address:w,value:te},...ue];return ce({chain:t,compiledMemo:H,inputs:F,outputs:rt,sender:_e||w,tx:Ae}),{feeDelta:ve,newFee:Y,originalFee:b.fee,tx:Ae}}async function Or({txid:T,newFeeRate:g,recipient:w,memo:v}){let{tx:b,originalFee:K,newFee:I}=await Ue({memo:v,newFeeRate:g,recipient:w,txid:T}),B=await tt(b);B.finalize();let F=await A(t).broadcastTx(J.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function _t({accountIndex:T,index:g,change:w=!1}){Z("index",g);let v=T===void 0?y:f(T);if(!v)return;return v.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function vt({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=ur(t),v=U(t);for(let b=0;b<g.length;b++){let K=g[b];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=_t({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${b} at index ${I}`});for(let{index:H,...ee}of wt({chain:t,indexes:[b],network:v,publicKey:xt(F),tx:T}))T.updateInput(H,ee);T.signIdx(F,b,w)}return T}async function Sr({utxos:T,recipient:g,assetValue:w,memo:v,feeRate:b,feeOptionKey:K,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let F=b||(await we(t))[K||N.Fast],H=v?M(v):null,ee=[{address:g,value:w.getBaseValue("number")}];if(H)ee.push({address:"",script:H,value:0});let _e=T.map(({address:_,hash:D,index:k,value:nt,txHex:kr,witnessUtxo:ot})=>({address:_,hash:D,index:k,txHex:kr,value:nt,witnessUtxo:ot?{script:ot.script,value:ot.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:Y,outputs:ve}=E({chain:t,changeAddress:He,feeRate:F,inputs:_e,outputs:ee});if(!(Y&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let te=new Je({allowUnknownOutputs:!!H,version:1}),Ae=Y.map((_)=>{let D=T.find((k)=>k.hash===_.hash&&k.index===_.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),rt=Y.map((_,D)=>{let k=Ae[D],nt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{..._,publicKey:nt??void 0}});return ce({chain:t,compiledMemo:H,inputs:rt,outputs:ve,sender:He,tx:te}),vt({inputDerivations:Ae,tx:te}),te.finalize(),A(t).broadcastTx(J.encode(te.extract()))}function Cr({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let v=X({change:!1,index:w}),b=X({change:!0,index:w}),K=v?.address===T?!1:b?.address===T;if(v?.address===T||b?.address===T)return{change:K,index:w}}return}function tt(T){if(!a)throw new P("toolbox_utxo_no_signer");return a.signTransaction(T)}let Xr=t===be.Bitcoin&&l?async(T)=>Jt({message:T,privateKey:l.privateKey,scriptType:s}):void 0;async function Br(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(J.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:Or,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Ue,createTransaction:(T)=>cr({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:_t,estimateMaxSendableAmount:Qn(t),estimateTransactionFee:eo(t),getAddress:m,getAddressFromKeys:lr(t,{scriptType:s}),getAddressType:(T)=>j({address:T,chain:t}),getBalance:tr(t),getExtendedPublicKey:x,getExtendedPublicKeyInfo:S,getFeeRates:()=>we(t),getInputsOutputsFee:dr,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>qn(xe({...T,chain:t}).privateKey,t),isRBFEnabled:q,keys:l,resolveDerivationIndex:Cr,scriptType:s,signAndBroadcastTransaction:Br,signMessage:Xr,signTransaction:tt,signTransactionWithMultipleKeys:vt,transfer:ro(t,a,h),transferFromMultipleAddresses:Sr,validateAddress:pr(t)}}import{getZcashAddressType as oo,toTransparentZcashAddress as so,validateZcashAddress as Pt}from"@swapkit/utxo-signer";function Ie(e){return Ce(e)!==null}var W=io.BitcoinCash;function et(e){return z(Ee(e))}function ho(e){let t=U(W);function r(o){return o.sign(e.privateKey,[po.ALL]),o}function n(){let o=yr(e.publicKey,t);if(!o.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let i=mr({hash:o.hash,prefix:fr.MAINNET,type:Tr.P2PKH});return Promise.resolve(i.replace(/^bitcoincash:/,""))}return{getAddress:n,signTransaction:r}}function xr(e={}){let t="phrase"in e?e.phrase:void 0,r="index"in e?e.index||0:0,n="derivationPath"in e?e.derivationPath:void 0,o=uo({chain:W,derivationPath:n,index:r}),i=ao(o),d=t?xe({chain:W,derivationPath:i,phrase:t}):void 0,s=d?ho(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(s?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:a,broadcastTx:l,...h}=de(t?{chain:W,index:r,phrase:t,...n?{derivationPath:n,scriptType:c}:{scriptType:c}}:{chain:W,scriptType:c});function m(x,S=!0){return u(z(Ee(x)))}function f(x){if(!s)throw new L("toolbox_utxo_no_signer");return s.signTransaction(x)}async function y(x){let S=await f(x);return S.finalize(),await l(hr.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:To,createTransaction:br,getAddress:p,getAddressFromKeys:mo,getBalance:m,getFeeRates:a,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:et,transfer:fo({broadcastTx:l,getFeeRates:a,signer:s}),validateAddress:Ie}}async function br({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,sweep:i}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:i?void 0:d}),p=r?M(r):null,c=[],u=G(t);if(c.push({address:u,value:i?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:n,inputs:s,outputs:c,sweep:i});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!p,version:1}),m=G(o),{inputs:f,tx:y}=ce({chain:W,compiledMemo:p,inputs:a,outputs:l.map((x)=>("address"in x)&&x.address?{...x,address:G(x.address)}:x),sender:m,tx:h});return{inputs:f,tx:y,utxos:a}}function fo({broadcastTx:e,getFeeRates:t,signer:r}){return async function({recipient:o,assetValue:i,feeOptionKey:d=co.Fast,sweep:s,...p}){let c=await r?.getAddress();if(!(r&&c))throw new L("toolbox_utxo_no_signer");if(!o)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:a}=await br({...p,assetValue:i,feeRate:u,recipient:o,sender:c,sweep:s}),l=await r.signTransaction(a);return l.finalize(),e(hr.encode(l.extract()))}}async function To({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o}){let i=Ee(t);if(!Ie(i))throw new L("toolbox_utxo_invalid_address",{address:i});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:d}),p=Number(n.toFixed(0)),c=r?M(r):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:p,inputs:s,outputs:u});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ce({chain:W,compiledMemo:c,inputs:a,outputs:l,sender:G(o),tx:h});return{inputs:m,tx:f,utxos:s}}function mo(e){let t=lo.bitcoinCash,r=yr(e.publicKey,t);if(!r.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return mr({hash:r.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as yo,hex as go}from"@scure/base";import{HDKey as Ur}from"@scure/bip32";import{mnemonicToSeedSync as _r}from"@scure/bip39";import{Chain as V,derivationPathToString as xo,FeeOption as bo,SwapKitError as Q}from"@swapkit/helpers";import{Address as wo,createZcashTransaction as Po,getZcashTransactionFormat as Uo,isTransparentZcashAddress as wr,OutScript as _o,toTransparentZcashAddress as vo,utils as vr,WIF as Ao,ZcashSigHash as Oo}from"@swapkit/utxo-signer";import{match as So,P as Ut}from"ts-pattern";var Co=yo(vr.sha256);function Xo(e){return Co.encode(e)}function Bo({phrase:e,derivationPath:t}){let r=_r(e),o=Ur.fromMasterSeed(r).derive(t);if(!o.privateKey||!o.publicKey)throw new Q("toolbox_utxo_invalid_params");let{privateKey:i,publicKey:d}=o,s=vr.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+s.length);c.set(p,0),c.set(s,p.length);let u=Xo(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(a)=>{if(a.signAllInputs(i,d,Oo.ALL),"extract"in a)return a.finalizeAllInputs(),Promise.resolve(a.extract());return Promise.resolve(a)}}}function ko({inputs:e,outputs:t,tx:r,sender:n,compiledMemo:o}){let i=U(V.Zcash);for(let d of e){let s=wo(i).decode(n),p=_o.encode(s);r.addInput({index:d.index,script:p,sequence:4294967295,txid:go.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let s="address"in d&&d.address?d.address:n,p=d.script;if(p&&!o)continue;if(p&&o)r.addOutput({amount:0n,script:o});else r.addOutputAddress(s,BigInt(d.value),i)}return{inputs:e,tx:r}}async function Ko(){try{let e=await A(V.Zcash).getBlockHeight();return Uo(e+1)}catch(e){throw new Q({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function Pr(e){let{assetValue:t,recipient:r,memo:n,feeRate:o,sender:i,fetchTxHex:d,sweep:s}=e,p=U(V.Zcash);if(!wr(i,p))throw new Q("toolbox_utxo_invalid_address",{address:i});let c=vo(r);if(!wr(c,p))throw new Q("toolbox_utxo_invalid_address",{address:r,error:"Zcash transaction creation currently supports transparent addresses only"});let u=n?M(n):null,a=await A(V.Zcash).getUtxos({address:i,fetchTxHex:d!==!1}),l=[{address:c,value:s?0:Number(t.getBaseValue("string"))},...u?[{script:u,value:0}]:[]],{inputs:h,outputs:m}=E({chain:V.Zcash,changeAddress:i,feeRate:o,inputs:a,outputs:l,sweep:s});if(!(h&&m))throw new Q("toolbox_utxo_insufficient_balance",{assetValue:t,sender:i});let f=Po({...await Ko(),expiryHeight:0,lockTime:0}),{tx:y,inputs:x}=ko({compiledMemo:u,inputs:h,outputs:m,sender:i,tx:f});return{inputs:x,outputs:m,tx:y}}function Ar(e={}){let t="scriptType"in e?e.scriptType:void 0,r=So(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:a=0})=>{let{derivationPath:l}=Le({chain:V.Zcash,derivationPath:u,index:a,scriptType:t}),h=xo(l);return Bo({derivationPath:h,phrase:c})}).otherwise(()=>{return}),n=de({chain:V.Zcash,scriptType:t,signer:r});async function o(c){if(!r)throw new Q("toolbox_utxo_no_signer");return await r.signTransaction(c)}async function i(c){let u=await o(c);return n.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:a=bo.Fast,sweep:l,...h}){let m=await r?.getAddress();if(!(r&&m))throw new Q("toolbox_utxo_no_signer");let f=h.feeRate||(await n.getFeeRates())[a],{tx:y}=await Pr({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await r.signTransaction(y)).toHex();return n.broadcastTx(S)}function s({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=_r(c),h=Ur.fromMasterSeed(a).derive(u);if(!h.privateKey||!h.publicKey)throw new Q("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=s({derivationPath:u,phrase:c}),l=U(V.Zcash);return Ao(l).encode(a.privateKey)}return{...n,createKeysForPath:s,createTransaction:Pr,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:i,signTransaction:o,transfer:d,validateAddress:Pt}}import{hex as Fo}from"@scure/base";import{HDKey as Do}from"@scure/bip32";import{derivationPathToString as Io,NetworkDerivationPath as Ho,updateDerivationPath as Ro}from"@swapkit/helpers";function Mo({xpub:e,chain:t,count:r,startIndex:n=0,accountIndex:o,purpose:i,scriptType:d}){if(Z("count",r),r<1)throw RangeError("count must be at least 1");Z("startIndex",n),$e(t,d),dt({chain:t,purpose:i,scriptType:d});let s=U(t),p=Do.fromExtendedKey(e,s.bip32),c=i===void 0?void 0:Ro(Ho[t],{purpose:i}),u=re({accountIndex:o,chain:t,derivationPath:c}),a=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<r;f++){let y=n+f,x=m.deriveChild(y);if(!x.publicKey)continue;let S=Oe({accountIndex:o,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:a,address:De({chain:t,network:s,publicKey:x.publicKey,scriptType:d}),change:h,index:y,pubkey:Fo.encode(x.publicKey),...i===void 0?{}:{path:Io(S)}})}}return l}function Ki(e,t){switch(e){case Pe.BitcoinCash:return xr(t||{});case Pe.Zcash:return Ar(t);case Pe.Bitcoin:case Pe.Dogecoin:case Pe.Litecoin:case Pe.Dash:return de({chain:e,...t});default:throw new Eo("toolbox_utxo_not_supported",{chain:e})}}export{Yt as InputSizes,ws as MIN_TX_FEE,Xn as OP_RETURN_OVERHEAD,lt as OutputSizes,Cn as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,ie as UTXOScriptType,It as UtxoNetwork,E as accumulative,ce as addInputsAndOutputs,lr as addressFromKeysGetter,Z as assertDerivationIndex,he as baseUrl,ge as calculateTxSize,Rn as canSignBitcoinMessage,M as compileMemo,xr as createBCHToolbox,Lo as createCustomUtxoApi,Fr as createHDWalletHelpers,de as createUTXOToolbox,Ar as createZcashToolbox,Mo as deriveAddressesFromXpub,rs as detectAddressNetwork,Ce as getBchAddressType,Ke as getDustThreshold,ke as getInputScriptType,se as getInputSize,wt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Bn as getOutputSizeForAddress,Ge as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,re as getUTXOAccountPath,Oe as getUTXOAddressPath,pr as getUTXOAddressValidator,j as getUtxoAddressType,A as getUtxoApi,Vo as getUtxoNetwork,Ki as getUtxoToolbox,Tt as getWitnessOverhead,oo as getZcashAddressType,ft as isSegwitScriptType,ts as isValidAddress,zt as nonSegwitChains,z as stripPrefix,et as stripToCashAddress,Ee as toCashAddress,G as toLegacyAddress,so as toTransparentZcashAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,sr as validateUtxoAddress,Pt as validateZcashAddress};
@@ -188,8 +188,8 @@ export declare function parseAminoMessageForDirectSigning<T extends MsgDeposit |
188
188
  value: {
189
189
  coins: {
190
190
  asset: {
191
- chain: string | undefined;
192
- symbol: string | undefined;
191
+ chain: string;
192
+ symbol: string;
193
193
  synth: boolean;
194
194
  ticker: string;
195
195
  };
@@ -200,8 +200,8 @@ export declare function parseAminoMessageForDirectSigning<T extends MsgDeposit |
200
200
  } | {
201
201
  coins: {
202
202
  asset: {
203
- chain: string | undefined;
204
- symbol: string | undefined;
203
+ chain: string;
204
+ symbol: string;
205
205
  synth: boolean;
206
206
  ticker: string;
207
207
  };
@@ -6,10 +6,11 @@ interface AssertSendAssetPayloadParams {
6
6
  allowedEndpoints: string[];
7
7
  expectedAmount: string;
8
8
  expectedDestination: string;
9
+ expectedDestinationDex: "" | "spot";
9
10
  expectedFromSubAccount: string;
10
11
  expectedSourceDex: "" | "spot";
11
12
  expectedToken: string;
12
13
  submitTo: string;
13
14
  typedData: HyperCoreTypedData;
14
15
  }
15
- export declare function assertSendAssetPayload({ action, allowedEndpoints, expectedAmount, expectedDestination, expectedFromSubAccount, expectedSourceDex, expectedToken, submitTo, typedData, }: AssertSendAssetPayloadParams): void;
16
+ export declare function assertSendAssetPayload({ action, allowedEndpoints, expectedAmount, expectedDestination, expectedDestinationDex, expectedFromSubAccount, expectedSourceDex, expectedToken, submitTo, typedData, }: AssertSendAssetPayloadParams): void;
@@ -242,6 +242,7 @@ export interface HyperCoreSendAssetPayinParams {
242
242
  };
243
243
  expectedAmount: string;
244
244
  expectedDestination: string;
245
+ expectedDestinationDex: "" | "spot";
245
246
  expectedFromSubAccount: string;
246
247
  expectedSourceDex: "" | "spot";
247
248
  expectedToken: string;
@@ -103,7 +103,7 @@ export declare function toolboxFor(scriptType: FlowScriptType): {
103
103
  getAddressFromKeys: (keys: {
104
104
  publicKey: Uint8Array;
105
105
  }) => string;
106
- getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
106
+ getAddressType: (address: string) => "pkh" | "sh" | "tex" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
107
107
  getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
108
108
  getExtendedPublicKey: () => string | undefined;
109
109
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
@@ -4,5 +4,5 @@ export declare function getBchAddressType(address: string): "pkh" | "sh" | null;
4
4
  export declare function getUtxoAddressType({ address, chain }: {
5
5
  address: string;
6
6
  chain: UTXOChain;
7
- }): "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
7
+ }): "pkh" | "sh" | "tex" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
8
8
  export type UtxoAddressType = NonNullable<ReturnType<typeof getUtxoAddressType>>;
@@ -1,4 +1,5 @@
1
1
  import { Chain, type UTXOChain } from "@swapkit/helpers";
2
+ export declare function baseUrl(chain: Chain): string;
2
3
  export declare function getUtxoApi(chain: UTXOChain): {
3
4
  broadcastTx: (txHash: string) => Promise<string>;
4
5
  getAddressData: (address: string) => Promise<{
@@ -65,7 +65,7 @@ export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(too
65
65
  feeRate?: number;
66
66
  fetchTxHex?: boolean;
67
67
  }) => Promise<import("@swapkit/helpers").AssetValue>;
68
- getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
68
+ getAddressType: (address: string) => "pkh" | "sh" | "tex" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
69
69
  getExtendedPublicKey: () => string | undefined;
70
70
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
71
71
  accountIndex?: number;
@@ -22,4 +22,4 @@ export { assertDerivationIndex, type CreateHDWalletHelpersParams, createHDWallet
22
22
  export { type DeriveAddressesFromXpubParams, deriveAddressesFromXpub } from "../helpers/xpubDerivation";
23
23
  export { stripToCashAddress } from "./bitcoinCash";
24
24
  export * from "./params";
25
- export { getBchAddressType, getZcashAddressType, stripPrefix, validateBchAddress, validateZcashAddress, } from "./validators";
25
+ export { getBchAddressType, getZcashAddressType, stripPrefix, toTransparentZcashAddress, validateBchAddress, validateZcashAddress, } from "./validators";
@@ -175,7 +175,7 @@ export declare function createUTXOToolbox<T extends UTXOChain>(toolboxParams: (U
175
175
  getAddressFromKeys: (keys: {
176
176
  publicKey: Uint8Array;
177
177
  }) => string;
178
- getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
178
+ getAddressType: (address: string) => "pkh" | "sh" | "tex" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
179
179
  getBalance: (address: string, scamFilter?: boolean) => Promise<AssetValue[]>;
180
180
  getExtendedPublicKey: () => string | undefined;
181
181
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
@@ -1,3 +1,3 @@
1
- export { getZcashAddressType, validateZcashAddress } from "@swapkit/utxo-signer";
1
+ export { getZcashAddressType, toTransparentZcashAddress, validateZcashAddress } from "@swapkit/utxo-signer";
2
2
  export { getBchAddressType, stripPrefix } from "../helpers/addressType";
3
3
  export declare function validateBchAddress(address: string): boolean;
@@ -1,5 +1,5 @@
1
1
  import { type ChainSigner, FeeOption } from "@swapkit/helpers";
2
- import { PCZT, ZcashPSBT, type ZcashTransaction } from "@swapkit/utxo-signer";
2
+ import { type PCZT, type ZcashPSBT, type ZcashTransaction } from "@swapkit/utxo-signer";
3
3
  import { accumulative } from "../helpers";
4
4
  import type { TargetOutput, UTXOBuildTxParams, UTXOTransferParams, UTXOType } from "../types";
5
5
  import type { UTXOToolboxDerivationParams } from "./params";
@@ -68,7 +68,7 @@ export declare function createZcashToolbox(toolboxParams?: {
68
68
  getAddressFromKeys: (keys: {
69
69
  publicKey: Uint8Array;
70
70
  }) => string;
71
- getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
71
+ getAddressType: (address: string) => "pkh" | "sh" | "tex" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
72
72
  getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
73
73
  getExtendedPublicKey: () => string | undefined;
74
74
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "6.4.1", "@swapkit/utxo-signer": "3.2.0" },
2
+ "dependencies": { "@swapkit/helpers": "6.4.2", "@swapkit/utxo-signer": "3.3.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -133,5 +133,5 @@
133
133
  "type-check:go": "tsgo"
134
134
  },
135
135
  "type": "module",
136
- "version": "6.5.1"
136
+ "version": "6.6.0"
137
137
  }