@swapkit/toolboxes 6.4.0 → 6.5.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/chunk-2q4pxsyg.js +2 -0
  3. package/dist/chunk-bmj5dnhd.js +1 -0
  4. package/dist/{chunk-exyqap7m.js → chunk-pz8xe0qj.js} +1 -1
  5. package/dist/{chunk-xdkdc1f0.js → chunk-qk8kg62t.js} +1 -1
  6. package/dist/src/aleo/index.js +1 -1
  7. package/dist/src/aptos/index.js +1 -1
  8. package/dist/src/cardano/index.js +1 -1
  9. package/dist/src/cosmos/index.js +1 -1
  10. package/dist/src/evm/index.js +1 -1
  11. package/dist/src/hypercore/index.js +1 -1
  12. package/dist/src/index.js +1 -1
  13. package/dist/src/lightspark/index.js +1 -1
  14. package/dist/src/near/index.js +1 -1
  15. package/dist/src/radix/index.js +1 -1
  16. package/dist/src/ripple/index.js +1 -1
  17. package/dist/src/solana/index.js +1 -1
  18. package/dist/src/starknet/index.js +1 -1
  19. package/dist/src/stellar/index.js +1 -1
  20. package/dist/src/substrate/index.js +1 -1
  21. package/dist/src/sui/index.js +1 -1
  22. package/dist/src/ton/index.js +1 -1
  23. package/dist/src/tron/index.js +1 -1
  24. package/dist/src/utxo/index.js +2 -1
  25. package/dist/types/evm/helpers.d.ts +4 -0
  26. package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -1
  27. package/dist/types/evm/toolbox/evm.d.ts +24 -24
  28. package/dist/types/evm/toolbox/op.d.ts +2 -2
  29. package/dist/types/evm/types.d.ts +2 -2
  30. package/dist/types/hypercore/payin.d.ts +0 -1
  31. package/dist/types/sui/__tests__/grpcClientMock.d.ts +37 -0
  32. package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +1 -0
  33. package/dist/types/utxo/helpers/index.d.ts +1 -0
  34. package/dist/types/utxo/helpers/messageSigning.d.ts +7 -0
  35. package/dist/types/utxo/toolbox/bitcoinCash.d.ts +1 -0
  36. package/dist/types/utxo/toolbox/utxo.d.ts +1 -0
  37. package/dist/types/utxo/toolbox/zcash.d.ts +1 -0
  38. package/package.json +2 -4
  39. package/dist/chunk-ncc6qmj6.js +0 -1
  40. package/dist/chunk-ygq25ce3.js +0 -2
@@ -1 +1 @@
1
- import"../../chunk-exyqap7m.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},At={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return At;case g.Noble:return wt;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),A=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,A),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:w,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,w=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,w,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,w){let S=w??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),S=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,w=c||h?await _(await pt(a)):void 0,S=h&&w?await Mt({client:w,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,A=U(r.symbol),C=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(b.amount,A)})}let T={amount:[{amount:C.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),w=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?w:R(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),w=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as wn,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:A=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[A],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let b=(await Sn(i)(m)).filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).flatMap(({denom:A,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;try{return[In(T,C)]}catch{return[]}});if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=An.decode(n);return An.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,w=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(w,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),w=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:w,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),A=F(i,r),C=await L(l,y,{aminoTypes:A,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:A,signingClient:C}=await p(),T=(await A.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function w(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:A}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=A?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),A=(await y.getAccounts())?.[0]?.address;if(!A)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(A,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:w,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:we(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,At as DEFAULT_KUJI_FEE_MAINNET,wt as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
1
+ import"../../chunk-pz8xe0qj.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},At={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return At;case g.Noble:return wt;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),A=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,A),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:w,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,w=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,w,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,w){let S=w??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),S=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,w=c||h?await _(await pt(a)):void 0,S=h&&w?await Mt({client:w,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,A=U(r.symbol),C=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(b.amount,A)})}let T={amount:[{amount:C.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),w=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?w:R(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),w=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as wn,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:A=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[A],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let b=(await Sn(i)(m)).filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).flatMap(({denom:A,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;try{return[In(T,C)]}catch{return[]}});if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=An.decode(n);return An.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,w=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(w,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),w=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:w,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),A=F(i,r),C=await L(l,y,{aminoTypes:A,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:A,signingClient:C}=await p(),T=(await A.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function w(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:A}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=A?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),A=(await y.getAccounts())?.[0]?.address;if(!A)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(A,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:w,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:we(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,At as DEFAULT_KUJI_FEE_MAINNET,wt as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
@@ -1 +1 @@
1
- import{a as ha}from"../../chunk-qsbf0z90.js";import{$ as _,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,O as N,P as O,Q as P,R as Q,S as R,T as S,U as T,V as U,W as V,X as W,Y as X,Z as Y,_ as Z,aa,b as a,ba,c as b,ca,d as c,da,e as d,ea,f as e,fa,g as f,ga,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"../../chunk-ygq25ce3.js";import"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";export{J as ADIToolbox,K as ARBToolbox,L as ARCToolbox,M as AURORAToolbox,N as AVAXToolbox,O as BASEToolbox,P as BERAToolbox,Q as BSCToolbox,o as BaseEVMToolbox,R as BotanixToolbox,S as COREToolbox,T as CORNToolbox,U as CROToolbox,x as ContractAddress,I as ETHToolbox,ha as EthNetwork,V as GNOToolbox,W as HOODToolbox,X as HYPEREVMToolbox,Y as LINEAToolbox,Z as MATICToolbox,n as MAX_APPROVAL,_ as MEGAETHToolbox,aa as MONADToolbox,H as OPToolbox,ba as PLASMAToolbox,ca as SONICToolbox,da as UNIToolbox,ea as XLayerToolbox,k as buildEIP712DomainType,r as createContract,b as createCustomEvmApi,G as createOPStackToolbox,w as getChecksumAddressFromAsset,s as getCreateContract,z as getCreateContractTxObject,v as getEIP1193SendTransaction,D as getEVMTxType,A as getEstimateGasPrices,a as getEvmApi,fa as getEvmToolbox,ga as getEvmToolboxAsync,e as getFallbackProvider,h as getIsEIP1559Compatible,g as getNetworkParams,d as getProvider,c as getProviderSync,y as getTokenAddress,q as isBrowserProvider,C as isEIP1559Transaction,B as isEIP7702Transaction,t as isStateChangingCall,E as maxBigInt,l as parseEIP712FromEVMTx,F as scaleEIP1559Fees,i as signAuthorization,u as toChecksumAddress,f as toHexString,j as validateAuthorization,m as validateAuthorizations,p as validateEVMAddress};
1
+ import{a as ia}from"../../chunk-qsbf0z90.js";import{$ as _,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,O as N,P as O,Q as P,R as Q,S as R,T as S,U as T,V as U,W as V,X as W,Y as X,Z as Y,_ as Z,aa,b as a,ba,c as b,ca,d as c,da,e as d,ea,f as e,fa,g as f,ga,h as g,ha,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"../../chunk-2q4pxsyg.js";import"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";export{K as ADIToolbox,L as ARBToolbox,M as ARCToolbox,N as AURORAToolbox,O as AVAXToolbox,P as BASEToolbox,Q as BERAToolbox,R as BSCToolbox,p as BaseEVMToolbox,S as BotanixToolbox,T as COREToolbox,U as CORNToolbox,V as CROToolbox,y as ContractAddress,J as ETHToolbox,ia as EthNetwork,W as GNOToolbox,X as HOODToolbox,Y as HYPEREVMToolbox,Z as LINEAToolbox,_ as MATICToolbox,o as MAX_APPROVAL,aa as MEGAETHToolbox,ba as MONADToolbox,I as OPToolbox,ca as PLASMAToolbox,da as SONICToolbox,ea as UNIToolbox,fa as XLayerToolbox,k as buildEIP712DomainType,s as createContract,b as createCustomEvmApi,H as createOPStackToolbox,x as getChecksumAddressFromAsset,t as getCreateContract,A as getCreateContractTxObject,w as getEIP1193SendTransaction,E as getEVMTxType,B as getEstimateGasPrices,a as getEvmApi,ga as getEvmToolbox,ha as getEvmToolboxAsync,e as getFallbackProvider,h as getIsEIP1559Compatible,g as getNetworkParams,d as getProvider,c as getProviderSync,z as getTokenAddress,r as isBrowserProvider,D as isEIP1559Transaction,C as isEIP7702Transaction,u as isStateChangingCall,F as maxBigInt,l as normalizeTypedDataForSigner,m as parseEIP712FromEVMTx,G as scaleEIP1559Fees,i as signAuthorization,v as toChecksumAddress,f as toHexString,j as validateAuthorization,n as validateAuthorizations,q as validateEVMAddress};
@@ -1 +1 @@
1
- import"../../chunk-qsbf0z90.js";import{q as we}from"../../chunk-ygq25ce3.js";import"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";function bt({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 St({cancels:e}){return{cancels:e,type:"cancelByCloid"}}function wt({oid:e,order:t}){return{oid:e,order:t,type:"modify"}}function Ut({modifies:e}){return{modifies:e,type:"batchModify"}}function _t({asset:e,isCross:t,leverage:n}){return{asset:e,isCross:t,leverage:n,type:"updateLeverage"}}function Dt({asset:e,isBuy:t,ntli:n}){return{asset:e,isBuy:t,ntli:n,type:"updateIsolatedMargin"}}function Ot({asset:e,leverage:t}){return{asset:e,leverage:t,type:"topUpIsolatedOnlyMargin"}}function Pt({time:e}){return{time:e,type:"scheduleCancel"}}function kt({amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i}){return{amount:e,hyperliquidChain:t,nonce:n,signatureChainId:r,toPerp:i,type:"usdClassTransfer"}}function oe({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 vt({agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i}){return{agentAddress:e,agentName:t,hyperliquidChain:n,nonce:r,signatureChainId:i,type:"approveAgent"}}function Rt({builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i}){return{builder:e,hyperliquidChain:t,maxFeeRate:n,nonce:r,signatureChainId:i,type:"approveBuilderFee"}}function It({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 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 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 Ee(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 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 t=je.encode(e);if(t.length<32)return b(new Uint8Array([160+t.length]),t);return b(Ee(217,0,t.length),t)}function Je(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 ze(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])=>[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 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 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 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 ce(e){return{domain:Fe,message:{connectionId:e,source:"a"},primaryType:"Agent",types:{Agent:[...Le.Agent]}}}function de(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||ae},primaryType:t,types:{[t]:n}}}function ye(e){let t=Me.from(e);return{r:t.r,s:t.s,v:t.v}}function ue(e,t,{expiresAfter:n,vaultAddress:r}={}){let i=Y(e),o=v(BigInt(t),8),s=r?b(new Uint8Array([1]),Ke(r.toLowerCase())):new Uint8Array([0]),p=typeof n==="number"?b(new Uint8Array([0]),v(BigInt(n),8)):new Uint8Array;return Ne(b(i,o,s,p))}function le(e){let t=e.hyperliquidChain||ae;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 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(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types;return{...e,types:n}}function Ae({action:e,allowedEndpoints:t,expectedAmount:n,expectedDestination:r,expectedFromSubAccount:i,expectedSourceDex:o,expectedToken:s,submitTo:p,typedData:u}){let{domain:f,message:S,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(S[d]!==e[d])c(`${d}: signed ${JSON.stringify(S[d])} != submitted ${JSON.stringify(e[d])}`);let A=Object.keys(S),l=A.filter((d)=>!y.includes(d)),T=y.filter((d)=>!A.includes(d));if(l.length||T.length){let d=[l.length?`declares undeclared keys [${l.join(",")}]`:"",T.length?`is missing keys [${T.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 k=Object.keys(f).filter((d)=>!Qe.has(d));if(k.length)c(`domain carries unexpected keys: ${k.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(!n)c("expectedAmount is missing — cannot verify action.amount");let j=!1;try{j=new Ve(String(e.amount)).eqValue(n)}catch{c(`action.amount ${JSON.stringify(e.amount)} is not comparable to ${n}`)}if(!j)c(`action.amount ${JSON.stringify(e.amount)} != route sell amount ${n}`);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=t.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 et}from"@swapkit/helpers";import{SwapKitApi as tt}from"@swapkit/helpers/api";import{HDNodeWallet as nt}from"ethers";import{match as rt,P as Z}from"ts-pattern";var U=Ge.Hype,{baseDecimal:ee,rpcUrls:he}=Ue(U),it=he[0]?`${he[0]}/exchange`:void 0,ot={HYPE:ee,USDC:6,USDT:6},_e="Mainnet",st=/^\d+(?:\.\d+)?$/,at=/^[^:]+:0x[0-9a-fA-F]+$/,pt={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},ct={spotSend:"HyperliquidTransaction:SpotSend"};function h(e,t){if(!$e(e))throw new g(t,{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 P({requestOptions:e,...t}){let n=await E();return N.post(`${n}/info`,{json:t,...e})}function te({dex:e,user:t}){return P({...e?{dex:e}:{},type:"clearinghouseState",user:h(t,"helpers_invalid_params")})}function Oe({user:e}){return P({type:"spotClearinghouseState",user:h(e,"helpers_invalid_params")})}function dt({destination:e,sender:t}){let n=h(t,"helpers_invalid_params"),r=h(e,"helpers_invalid_params");return P({requestOptions:De,source:n,type:"preTransferCheck",user:r})}function yt({dex:e,user:t}){return P({...e?{dex:e}:{},type:"openOrders",user:h(t,"helpers_invalid_params")})}function ut({dex:e,user:t}){return P({...e?{dex:e}:{},type:"frontendOpenOrders",user:h(t,"helpers_invalid_params")})}function lt({oidOrCloid:e,user:t}){return P({oid:e,type:"orderStatus",user:h(t,"helpers_invalid_params")})}function gt({aggregateByTime:e,user:t}){return P({...typeof e==="boolean"?{aggregateByTime:e}:{},type:"userFills",user:h(t,"helpers_invalid_params")})}function ft({aggregateByTime:e,endTime:t,startTime:n,user:r}){return P({...typeof e==="boolean"?{aggregateByTime:e}:{},...typeof t==="number"?{endTime:t}:{},startTime:n,type:"userFillsByTime",user:h(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??ot[i]??ee,p=o?`${U}.${i}-${o.name}:${o.tokenId}`:`${U}.${i}`;return new M({decimal:s,identifier:p,value:n})}function mt(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 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 Ct(e){let t=ct[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]:pt[n]}}}async function At({action:e,expiresAfter:t,nonce:n,vaultAddress:r}){let i=n||Date.now(),o=r?h(r,"helpers_invalid_params"):void 0,s=await J(),p=ue(e,i,{expiresAfter:t,vaultAddress:o});return{action:e,endpoint:s,expiresAfter:t,nonce:i,typedData:ce(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=le({...e,nonce:i,signatureChainId:o});return{action:s,endpoint:t??await J(),nonce:i,typedData:de(s)}}async function ne({token:e,user:t}){let n=await Oe({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 ke({assetValue:e,sender:t,token:n}){let r=(await ne({token:n,user:t}))?.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 ht(e){if(e.address&&at.test(e.address))return e.address;let n=(await P({type:"spotMeta"}))?.tokens?.find(({name:r})=>r?.toUpperCase()===e.ticker.toUpperCase());if(n)return`${n.name}:${n.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:t}){let n;try{n=await dt({destination:e,sender:t})}catch(o){throw new g("toolbox_hypercore_pre_transfer_check_failed",o)}if(typeof n?.isSanctioned!=="boolean"||typeof n.userExists!=="boolean")throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:n});let{fee:r}=n,i=typeof r==="string"&&st.test(r)?Number(r):Number.NaN;if(!Number.isFinite(i))throw new g("toolbox_hypercore_pre_transfer_check_failed",{response:n});if(n.isSanctioned)throw new g("toolbox_hypercore_destination_sanctioned",{destination:e,sender:t});return i}function Re(e){return e.toUpperCase().startsWith("USDC:")}async function Ie({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 g("toolbox_hypercore_insufficient_balance",{activationFee:e,feeToken:B,perpsWithdrawable:o.getValue("string"),spotAvailable:s.getValue("string"),token:t})}async function qe({activationFee:e,amount:t,sourceDex:n,token:r,user:i}){let o=Re(r),s=o?new O(t).add(e):new O(t);if(n!==void 0&&n!==""&&n!=="spot")throw new g("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:n});if(!o&&n==="")throw new g("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 g("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 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 Ht({amount:e,destination:t,sender:n,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:t,sender:n});if(!i){let u=await qe({activationFee:s,amount:e,sourceDex:r,token:o,user:n});return{amount:e,sourceDex:u}}if(!Re(o))return await Ie({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 g("toolbox_hypercore_insufficient_balance",{activationFee:s,spotAvailable:e,token:o});return{amount:p.getValue("string"),sourceDex:"spot"}}async function xt({assetValue:e,recipient:t,sender:n,signatureChainId:r,sweep:i,time:o,endpoint:s}){let p=h(t,"core_transaction_invalid_recipient_address"),u=h(n,"core_transaction_invalid_sender_address"),f=e.address;if(!f)throw new g("helpers_invalid_params",{asset:e.toString(),from:u});let S=i?await ke({assetValue:e,sender:u,token:f}):e.getValue("string"),m=s??await J(),H=o||Date.now(),a={amount:S,destination:p,hyperliquidChain:_e,signatureChainId:r||D,time:H,token:f,type:"spotSend"};return{action:a,endpoint:m,nonce:H,typedData:Ct(a)}}async function xe({assetValue:e,destinationDex:t,endpoint:n,fromSubAccount:r,recipient:i,sender:o,signatureChainId:s,sourceDex:p,sweep:u,time:f}){let S=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 ht(e),C=u?await ke({assetValue:e,sender:a,token:y}):e.getValue("string"),{amount:x,sourceDex:A}=await Ht({amount:C,destination:S,sender:a,sourceDex:p,sweep:u,token:y}),l=oe({amount:x,destination:S,destinationDex:t??"spot",fromSubAccount:H,hyperliquidChain:_e,nonce:f||Date.now(),signatureChainId:s||D,sourceDex:A,token:y});return Pe({action:l,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 g("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=h(i,"helpers_invalid_params"),s=await E(),p=n-5000,u=t?.toLowerCase(),f=r?.toUpperCase(),S=({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(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(S):void 0;if(a?.hash)return a.hash}catch{}}return""}async function Te({kind:e,lookup:t,signed:n}){try{await Be(n)}catch(i){if(i instanceof g&&i.errorKey==="core_transaction_failed"&&i.cause?.definitive===!0)throw i;let s=await be(t);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:t.nonce,transportError:String(i)})}let r=await be(t);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:t.nonce});return r}function Se({action:e,nonce:t,user:n}){return{amount:e.amount,destination:e.destination,nonce:t,token:e.token,user:n}}function $e(e){return e.startsWith("0x")&&we(e)}function Yt(e){let t=e&&"index"in e?e.index||0:0,n=Ye(e&&"derivationPath"in e&&e.derivationPath?e.derivationPath:et(Ze[U],{index:t})),r,i=!1;function o(){if(i)return r;return r=rt(e).with({phrase:Z.string},({phrase:a})=>nt.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 y=o();if(!y)throw new g("toolbox_hypercore_no_signer");let C=Ce(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"}})]),T=(x.spotState?.balances||x.balances||[]).map(({coin:w,token:R,total:k})=>He({coin:w,spotMeta:l,token:R,value:k})).filter((w)=>!!w),_=He({coin:"USDC",spotMeta:l,value:A.withdrawable||A.marginSummary?.accountValue||A.marginSummary?.totalRawUsd});return mt(_?[...T,_]:T)}async function f(a,y=!0){let C=h(a,"helpers_invalid_params");try{let x=await tt.getChainBalance({address:C,chain:U,scamFilter:y});if(x.length){let A=x.map(({identifier:T,value:_,decimal:w})=>new M({decimal:w||ee,identifier:T,value:_}));return A.some((T)=>T.isGasAsset)?A:[M.from({chain:U}),...A]}}catch{}return u(C)}async function S({sweep:a,...y}){let C=o();if(!C)throw new g("toolbox_hypercore_no_signer");let x=y.sender||await C.getAddress(),A=await xe({...y,feeRate:0,sender:x,sweep:a}),l=await p(A);return Te({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),T=structuredClone(x),_=await y.getAddress(),w=await J(),R=[...new Set([w,it??w])];Ae({...A,action:l,allowedEndpoints:R,typedData:T});let k=l.fromSubAccount?h(l.fromSubAccount,"helpers_invalid_params"):_,L=await ve({destination:l.destination,sender:k});await qe({activationFee:L,amount:l.amount,sourceDex:l.sourceDex,token:l.token,user:k});let j=await p({action:l,endpoint:w,nonce:l.nonce,typedData:T});return Te({kind:"payin",lookup:Se({action:l,nonce:l.nonce,user:k}),signed:j})}function H(){return M.from({chain:U,value:0})}return{broadcastTransaction:Be,createL1ActionRequest:At,createSendAssetTransaction:xe,createTransaction:xt,createUserSignedActionRequest:Pe,estimateTransactionFee:H,getAddress:s,getBalance:f,getBalanceFromChain:u,getState:{clearinghouse:te,frontendOpenOrders:ut,openOrders:yt,orderStatus:lt,spotClearinghouse:Oe,userFills:gt,userFillsByTime:ft},signAndBroadcastSendAsset:m,signTransaction:p,transfer:S,validateAddress:$e}}export{B as HYPERCORE_USDC_TOKEN_ID,vt as buildApproveAgentAction,Rt as buildApproveBuilderFeeAction,Ut as buildBatchModifyAction,Tt as buildCancelAction,St as buildCancelByCloidAction,wt as buildModifyAction,bt as buildOrderAction,Pt as buildScheduleCancelAction,oe as buildSendAssetAction,It as buildTokenDelegateAction,Ot as buildTopUpIsolatedOnlyMarginAction,Dt as buildUpdateIsolatedMarginAction,_t as buildUpdateLeverageAction,kt as buildUsdClassTransferAction,At as createL1ActionRequest,xe as createSendAssetTransaction,xt as createTransaction,Pe as createUserSignedActionRequest,Yt as getHyperCoreToolbox,$e as validateHyperCoreAddress};
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};
package/dist/src/index.js CHANGED
@@ -1 +1 @@
1
- import{ja as o}from"../chunk-exyqap7m.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-ncc6qmj6.js");return await e(l,r)}).with(...C,async()=>{let{getUtxoToolbox:e}=await import("./utxo/index.js");return e(l,r)}).with(...x,async()=>{let{getCosmosToolbox:e}=await import("./cosmos/index.js");return e(l,r)}).with(t.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(t.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(t.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(t.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(t.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(t.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(t.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(t.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(t.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(t.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(t.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(t.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(t.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new V("toolbox_not_supported",{chain:l})})}export{H as getAddressValidator,F as getFeeEstimator,b as getToolbox};
1
+ import{ka as o}from"../chunk-pz8xe0qj.js";import{AssetValue as k,Chain as t,CosmosChains as x,EVMChains as c,FeeOption as v,SubstrateChains as O,SwapKitError as V,UTXOChains as C}from"@swapkit/helpers";async function H(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:s}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:i}=await import("./cosmos/index.js"),{getSubstrateAddressValidator:p}=await import("./substrate/index.js"),{validateHyperCoreAddress:m}=await import("./hypercore/index.js"),{validateSolanaAddress:h}=await import("./solana/index.js"),{validateStarknetAddress:u}=await import("./starknet/index.js"),{validateSuiAddress:d}=await import("./sui/index.js"),{validateTonAddress:f}=await import("./ton/index.js"),{getUTXOAddressValidator:g}=await import("./utxo/index.js"),{validateNearAddress:w}=await import("./near/index.js"),{validateRadixAddress:S}=await import("./radix/index.js"),{validateRippleAddress:P}=await import("./ripple/index.js"),{validateTronAddress:A}=await import("./tron/index.js"),{validateStellarAddress:R}=await import("./stellar/index.js");return function({address:n,chain:W}){return l(W).with(...c,()=>e(n)).with(...C,(T)=>g(T)(n)).with(...x,(T)=>i(T)(n)).with(...O,(T)=>p({chain:T})(n)).with(t.Aleo,()=>r(n)).with(t.Aptos,()=>s(n)).with(t.Radix,()=>S(n)).with(t.Hype,()=>m(n)).with(t.Near,()=>w(n)).with(t.Ripple,()=>P(n)).with(t.Solana,()=>h(n)).with(t.Stellar,()=>R(n)).with(t.Starknet,()=>u(n)).with(t.Sui,()=>d(n)).with(t.Ton,()=>f(n)).with(t.Tron,()=>A(n)).with(t.Cardano,()=>a(n)).otherwise(()=>!1)}}function F(l){return async function(s){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let i=await b(a),p=await i.createTransaction(s),m="feeOptionKey"in s?s.feeOptionKey:v.Fast;return i.estimateTransactionFee({...p,feeOption:m})}).with(t.Bitcoin,t.BitcoinCash,t.Dogecoin,t.Dash,t.Litecoin,t.Solana,t.Ripple,t.Tron,t.Near,t.Cardano,t.Hype,async(a)=>(await b(a)).estimateTransactionFee(s)).with(t.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(s)}).with(t.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(s)}).with(t.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(s)}).with(t.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(t.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(s)}).with(t.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(s)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(s)}).otherwise(async()=>k.from({chain:l}))}}async function b(l,r){let{match:s}=await import("ts-pattern");return s(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-bmj5dnhd.js");return await e(l,r)}).with(...C,async()=>{let{getUtxoToolbox:e}=await import("./utxo/index.js");return e(l,r)}).with(...x,async()=>{let{getCosmosToolbox:e}=await import("./cosmos/index.js");return e(l,r)}).with(t.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(t.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(t.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(t.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(t.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(t.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(t.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(t.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(t.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(t.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(t.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(t.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(t.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new V("toolbox_not_supported",{chain:l})})}export{H as getAddressValidator,F as getFeeEstimator,b as getToolbox};
@@ -1 +1 @@
1
- import{ja as Kt}from"../../chunk-exyqap7m.js";import{SwapKitError as y}from"@swapkit/helpers";import{SwapKitError as D}from"@swapkit/helpers";var T=1000n,x=100000000n*T,Tt=BigInt(Number.MAX_SAFE_INTEGER),bt=10000n,vt=16n,ot=5n*T,Et=/^\d+$/,At=/^0[23][0-9a-fA-F]{64}$/,Mt=/^[0-9a-fA-F]{64}$/,xt=new Map([["BITCOIN",x],["MILLIBITCOIN",x/1000n],["MICROBITCOIN",x/1000000n],["NANOBITCOIN",x/1000000000n],["MILLISATOSHI",1n],["SATOSHI",T]]),Ct=(t,e)=>(t+e-1n)/e;function I(t,e){if(typeof t!=="string"||!Et.test(t))throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,value:t}});return BigInt(t)}function S(t,e){if(t<0n||t>Tt)throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,msats:t.toString()}});return Number(t)}function L(t){if(!t)return;let{originalUnit:e,originalValue:d}=t,p=xt.get(e);if(p===void 0||!Number.isSafeInteger(d)||d<0)return;return BigInt(d)*p}function b(t){let e=L(t);if(e===void 0)throw new D({errorKey:"toolbox_lightspark_api_error",info:{originalUnit:t?.originalUnit,originalValue:t?.originalValue,reason:t?"unsupported currency amount":"missing currency amount"}});return e}function at(t){let e=Ct(t*vt,bt*T)*T;if(e<ot)return ot;return e}function B(t){return t==="SUCCESS"||t==="FAILED"?t:"PENDING"}function v(t){return B(t)!=="PENDING"}function C(t){return typeof t==="string"&&At.test(t)}function H(t){return typeof t==="string"&&Mt.test(t)}function U(t){return new Promise((e)=>setTimeout(e,t))}function V(t){return typeof t==="object"&&t!==null&&"code"in t&&typeof t.code==="string"?t.code:void 0}function q(t){return t instanceof Error?t.message:void 0}var K=60000,X=600000,Ht=new Set(["MAINNET","REGTEST","SIGNET","TESTNET"]);function rt({decoded:t,expectedDestinationPublicKey:e,expectedNetwork:d,nowMs:p,skewToleranceMs:f}){if(!Number.isFinite(f)||f<0||f>X)throw new y({errorKey:"toolbox_lightspark_invalid_params",info:{expirySkewToleranceMs:f,maxExpirySkewToleranceMs:X,operation:"payInvoice"}});if(!H(t.paymentHash)||t.paymentHash!==t.paymentHash.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{paymentHash:t.paymentHash,reason:"missing or malformed payment hash"}});if(!Ht.has(t.network)||t.network!==d)throw new y({errorKey:"toolbox_lightspark_network_mismatch",info:{expectedNetwork:d,invoiceNetwork:t.network,paymentHash:t.paymentHash}});if(e!==void 0){if(!C(e))throw new y({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:e,paymentHash:t.paymentHash}});if(t.destinationPublicKey?.toLowerCase()!==e.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invoice_destination_mismatch",info:{expectedDestinationPublicKey:e,invoiceDestinationPublicKey:t.destinationPublicKey,paymentHash:t.paymentHash}})}let _=Date.parse(t.expiresAt);if(Number.isNaN(_))throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{expiresAt:t.expiresAt,paymentHash:t.paymentHash,reason:"unparseable expiry"}});if(p>_+f)throw new y({errorKey:"toolbox_lightspark_invoice_expired",info:{expiresAt:t.expiresAt,expirySkewToleranceMs:f,nowMs:p,paymentHash:t.paymentHash}})}function st({amountMsats:t,invoiceAmountMsats:e,paymentHash:d}){let p=t===void 0?void 0:I(t,"payInvoice amountMsats");if(e>0n){if(p!==void 0&&p!==e)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:e.toString(),paymentHash:d,requestedAmountMsats:t}});return{payAmountMsats:e,zeroAmountInvoice:!1}}if(p===void 0)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:"0",paymentHash:d,reason:"zero-amount invoice requires an explicit amountMsats"}});if(p===0n)throw new y({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"payInvoice amountMsats",paymentHash:d,reason:"amountMsats must be positive"}});return{payAmountMsats:p,zeroAmountInvoice:!0}}import{SwapKitError as c}from"@swapkit/helpers";var ct=60,ut=10,W=3000,Rt=K;function R(t){let e=L(t.amount),d=L(t.fees);return{...e===void 0?{}:{amountMsats:e.toString()},...d===void 0?{}:{feePaidMsats:d.toString()},failureReason:t.failureReason??void 0,paymentHash:t.transactionHash??void 0,preimage:t.paymentPreimage??void 0,status:B(t.status),transactionId:t.id}}function Y(t){return t.find((e)=>e.status==="SUCCESS")??t.find((e)=>!v(e.status))}function Ot(t){if(t.status==="CLOSED")return!0;let e=t.amountPaid?.originalValue;if(e===void 0||e===null)return!1;return typeof e==="number"?e>0:!0}function Ft({paymentHash:t,prior:e,requestedAmountMsats:d}){let p=L(e.amount);if(p===d)return;throw new c({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{operation:"payInvoice",paymentHash:t,...p===void 0?{}:{priorAmountMsats:p.toString()},priorTransactionId:e.id,reason:p===void 0?"a prior payment for this zero-amount invoice is denominated in a unit this toolbox cannot read, so it cannot be shown to match":"a prior payment for this zero-amount invoice used a different amount",requestedAmountMsats:d.toString()}})}async function dt({context:t,estimate:e,info:d,maximumFeesMsats:p,payAmountMsats:f}){let _=p!==void 0?I(p,t):at(f),P;try{P=L(await e())}catch{}if(P!==void 0&&P>_)throw new c({errorKey:"toolbox_lightspark_fee_limit_exceeded",info:{...d,estimatedFeeMsats:P.toString(),maximumFeesMsats:_.toString()}});return _}function Gt(t){let{nodeId:e}=t;if(!e||!(t.client||t.clientId&&t.clientSecret))throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClient:!!t.client,hasClientId:!!t.clientId,hasClientSecret:!!t.clientSecret,hasNodeId:!!e}});let d,p,f;async function _(n){try{return await import("@lightsparkdev/lightspark-sdk")}catch(i){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:n,reason:"@lightsparkdev/lightspark-sdk could not be loaded; install the optional peer dependency or inject a client"}},i)}}async function P(){if(t.client)return t.client;let{clientId:n,clientSecret:i}=t;if(!n||!i)throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClientId:!!n,hasClientSecret:!!i,hasNodeId:!!e}});let{AccountTokenAuthProvider:o,LightsparkClient:s}=await _("createClient");return new s(new o(n,i),t.apiUrl||void 0)}function k(){return d??=P().catch((n)=>{throw d=void 0,n}),d}function z(n,i){let o=V(n);return new c({errorKey:"toolbox_lightspark_signing_key_unavailable",info:{nodeId:e,operation:i,reason:"the node signing key could not be loaded",...o===void 0?{}:{vendorErrorCode:o}}})}function Q(n){let{signingKey:i}=t;if(!i)return Promise.resolve();return f??=n.loadNodeKey(e,{key:i}).catch((o)=>{throw f=void 0,z(o,"loadNodeKey")}),f}function j(n){if(t.signingKey||t.client)return;throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{operation:n,reason:"signingKey is required to send payments"}})}async function J(n){let i;if(n.getNodeById)i=await n.getNodeById(e);else if(n.executeRawQuery){let{getLightsparkNodeQuery:o}=await _("getNode");i=await n.executeRawQuery(o(e))}else throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"the injected client implements neither getNodeById nor executeRawQuery"}});if(!i)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"node not found"}});return p=i,i}async function Z(n){return p??await J(n)}async function tt({client:n,attempts:i,intervalMs:o,initial:s}){let a=s;if(v(a.status))return a;for(let r=0;r<i;r++){await U(o);try{let u=await n.getTransaction(s.id);if(u){if(a=u,v(u.status))return u}}catch{}}return a}async function pt(n,i){try{let o=await n.outgoingPaymentsForPaymentHash(i),s=Y(o);if(s)return{attemptSeq:0,existing:s};let a=await n.invoiceForPaymentHash(i);if(a&&Ot(a))throw new c({errorKey:"toolbox_lightspark_invoice_already_settled",info:{invoiceStatus:a.status,paymentHash:i}});return{attemptSeq:o.filter((r)=>r.status==="FAILED").length,existing:void 0}}catch(o){if(o instanceof c)throw o;throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"payInvoice preflight",paymentHash:i}},o)}}async function mt(n,i){try{return Y(await n.outgoingPaymentsForPaymentHash(i,["SUCCESS","PENDING"]))}catch{return}}async function ht(n,{paymentHash:i,transactionId:o}){if(o){let a=await n.getTransaction(o)??void 0;if(a)return{found:a,hashVerified:!1}}if(!i)return{found:void 0,hashVerified:!1};let s=await n.outgoingPaymentsForPaymentHash(i);return{found:Y(s)??s[s.length-1],hashVerified:!0}}async function lt(n,i,o,s){let a=!1,r,u=!1;for(let h=0;h<o;h++){if(h>0)await U(s);try{let m=await ht(n,i);if(u=!0,m.found){if(r=m.found,a=m.hashVerified,v(m.found.status))break}}catch{u=!1}}return{hashVerified:a,last:r,lookupSucceeded:u}}function O(n,i){let{timeoutSecs:o,attempts:s,intervalMs:a}=i;if(o!==void 0&&!(Number.isInteger(o)&&o>0)||s!==void 0&&!(Number.isInteger(s)&&s>=0)||a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:n,...i}})}function et(n,i){if(n instanceof c)throw n;let o=V(n);if(o==="SigningException")throw z(n,i);return o==="PaymentError"?"FAILED":"UNKNOWN"}async function ft(){let n=await k(),i=await J(n),o=i.balances?.availableToSendBalance??i.localBalance;if(!o)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getBalance",reason:"node reports no spendable balance"}});return{spendableMsats:b(o).toString(),...i.remoteBalance?{inboundCapacityMsats:b(i.remoteBalance).toString()}:{}}}async function nt(n){if(!n||typeof n!=="string")throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{reason:"empty invoice"}});let i=await k(),o;try{o=await i.decodeInvoice(n)}catch(s){throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"decodeInvoice"}},s)}if(!o?.paymentHash)throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{operation:"decodeInvoice",reason:"decoded invoice has no payment hash"}});return{amountMsats:b(o.amount).toString(),createdAt:o.createdAt,destinationPublicKey:o.destination?.publicKey??void 0,expiresAt:o.expiresAt,memo:o.memo??void 0,network:o.bitcoinNetwork,paymentHash:o.paymentHash}}async function gt({amountMsats:n,memo:i,expirySecs:o}){let s=I(n,"createInvoice"),r=await(await k()).createInvoiceWithDetails(e,S(s,"createInvoice"),i??"",void 0,o);if(!(r?.data?.encodedPaymentRequest&&r.data.paymentHash))throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createInvoice",reason:"invoice creation returned no invoice"}});return{amountMsats:b(r.data.amount).toString(),createdAt:r.data.createdAt,encodedInvoice:r.data.encodedPaymentRequest,expiresAt:r.data.expiresAt,paymentHash:r.data.paymentHash}}async function yt({amountMsats:n,memo:i}){let o=I(n,"createTestModeInvoice"),s=S(o,"createTestModeInvoice"),a=await k(),r;try{r=await a.createTestModeInvoice(e,s,i)}catch(u){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice"}},u)}if(!r)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice",reason:"test mode invoices require regtest credentials"}});return{encodedInvoice:r}}async function _t({invoice:n,amountMsats:i,maximumFeesMsats:o,destinationPublicKey:s,timeoutSecs:a=ct,attempts:r=ut,intervalMs:u=W,expirySkewToleranceMs:h=K}){j("payInvoice"),O("payInvoice",{attempts:r,intervalMs:u,timeoutSecs:a});let m=await k(),l=await nt(n),F=await Z(m);rt({decoded:l,expectedDestinationPublicKey:s,expectedNetwork:F.bitcoinNetwork,nowMs:Date.now(),skewToleranceMs:h});let{payAmountMsats:g,zeroAmountInvoice:w}=st({amountMsats:i,invoiceAmountMsats:I(l.amountMsats,"payInvoice"),paymentHash:l.paymentHash}),E=w?S(g,"payInvoice"):void 0,{attemptSeq:A,existing:G}=await pt(m,l.paymentHash);if(G){if(w)Ft({paymentHash:l.paymentHash,prior:G,requestedAmountMsats:g});return{...R(G),paymentHash:l.paymentHash,replayedPriorPayment:!0}}let St=await dt({context:"payInvoice maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForInvoice(e,n,E),info:{paymentHash:l.paymentHash},maximumFeesMsats:o,payAmountMsats:g});await Q(m);let Lt=S(St,"payInvoice maximumFeesMsats"),Pt=`${l.paymentHash}:${A}`,M;try{M=await m.payInvoice(e,n,Lt,a,E,Pt)}catch(it){if(et(it,"payInvoice")==="FAILED")return{failureReason:q(it),paymentHash:l.paymentHash,status:"FAILED"};M=await mt(m,l.paymentHash)}if(!M)return{paymentHash:l.paymentHash,status:"PENDING"};let Nt=await tt({attempts:r,client:m,initial:M,intervalMs:u}),N={...R(Nt),paymentHash:l.paymentHash};if(w&&N.status!=="FAILED"&&N.amountMsats!==g.toString())return{...N,reconciliationRequired:{reason:N.amountMsats===void 0?"AMOUNT_UNVERIFIABLE":"AMOUNT_MISMATCH",requestedAmountMsats:g.toString()},status:"PENDING"};return N}async function kt({destinationPublicKey:n,amountMsats:i,maximumFeesMsats:o,timeoutSecs:s=ct,attempts:a=ut,intervalMs:r=W}){if(j("sendPayment"),O("sendPayment",{attempts:a,intervalMs:r,timeoutSecs:s}),!C(n))throw new c({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:n}});let u=I(i,"sendPayment");if(u===0n)throw new c({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"sendPayment",reason:"amountMsats must be positive"}});let h=S(u,"sendPayment"),m=await k(),l=await dt({context:"sendPayment maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForNode(e,n,h),info:{destinationPublicKey:n},maximumFeesMsats:o,payAmountMsats:u}),F=S(l,"sendPayment maximumFeesMsats");await Q(m);let g={amountMsats:u.toString(),destinationPublicKey:n,sentAfter:new Date(Date.now()-Rt).toISOString()},w;try{w=await m.sendPayment(e,n,s,h,F)}catch(A){if(et(A,"sendPayment")==="FAILED")return{...g,failureReason:q(A),status:"FAILED"};return{...g,status:"PENDING"}}if(!w)return{...g,status:"PENDING"};let E=await tt({attempts:a,client:m,initial:w,intervalMs:r});return{...g,...R(E)}}async function It({transactionId:n,paymentHash:i,attempts:o=1,intervalMs:s=W}){if(!n&&!i)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",reason:"transactionId or paymentHash is required"}});O("getTransactionStatus",{attempts:o,intervalMs:s});let a=i?.toLowerCase();if(a!==void 0&&!H(a))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:i,reason:"malformed payment hash"}});let r=await k(),{hashVerified:u,last:h,lookupSucceeded:m}=await lt(r,{paymentHash:a,transactionId:n},o,s);if(!h)return{paymentHash:a,status:m?"NOT_FOUND":"UNKNOWN",transactionId:n};if(a&&!u&&h.transactionHash!==a)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:a,reason:h.transactionHash?"paymentHash does not match the transaction":"transaction carries no payment hash to verify against",transactionHash:h.transactionHash??void 0,transactionId:h.id}});return{...R(h),paymentHash:a??h.transactionHash??void 0}}async function wt({numTransactions:n,afterDate:i}={}){let o=await k(),s=await Z(o);return(await o.getRecentTransactions(e,n,s.bitcoinNetwork,i)).map((r)=>{let u=L(r.amount);return{...u===void 0?{}:{amountMsats:u.toString()},createdAt:r.createdAt,destinationId:r.destinationId??void 0,id:r.id,resolvedAt:r.resolvedAt??void 0,status:r.status,transactionHash:r.transactionHash??void 0,typename:r.typename}})}return{createInvoice:gt,createTestModeInvoice:yt,decodeInvoice:nt,getBalance:ft,getTransactionStatus:It,listTransactions:wt,payInvoice:_t,sendPayment:kt}}export{X as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MAX_MS,K as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS,Gt as getLightsparkToolbox};
1
+ import{ka as Kt}from"../../chunk-pz8xe0qj.js";import{SwapKitError as y}from"@swapkit/helpers";import{SwapKitError as D}from"@swapkit/helpers";var T=1000n,x=100000000n*T,Tt=BigInt(Number.MAX_SAFE_INTEGER),bt=10000n,vt=16n,ot=5n*T,Et=/^\d+$/,At=/^0[23][0-9a-fA-F]{64}$/,Mt=/^[0-9a-fA-F]{64}$/,xt=new Map([["BITCOIN",x],["MILLIBITCOIN",x/1000n],["MICROBITCOIN",x/1000000n],["NANOBITCOIN",x/1000000000n],["MILLISATOSHI",1n],["SATOSHI",T]]),Ct=(t,e)=>(t+e-1n)/e;function I(t,e){if(typeof t!=="string"||!Et.test(t))throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,value:t}});return BigInt(t)}function S(t,e){if(t<0n||t>Tt)throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,msats:t.toString()}});return Number(t)}function L(t){if(!t)return;let{originalUnit:e,originalValue:d}=t,p=xt.get(e);if(p===void 0||!Number.isSafeInteger(d)||d<0)return;return BigInt(d)*p}function b(t){let e=L(t);if(e===void 0)throw new D({errorKey:"toolbox_lightspark_api_error",info:{originalUnit:t?.originalUnit,originalValue:t?.originalValue,reason:t?"unsupported currency amount":"missing currency amount"}});return e}function at(t){let e=Ct(t*vt,bt*T)*T;if(e<ot)return ot;return e}function B(t){return t==="SUCCESS"||t==="FAILED"?t:"PENDING"}function v(t){return B(t)!=="PENDING"}function C(t){return typeof t==="string"&&At.test(t)}function H(t){return typeof t==="string"&&Mt.test(t)}function U(t){return new Promise((e)=>setTimeout(e,t))}function V(t){return typeof t==="object"&&t!==null&&"code"in t&&typeof t.code==="string"?t.code:void 0}function q(t){return t instanceof Error?t.message:void 0}var K=60000,X=600000,Ht=new Set(["MAINNET","REGTEST","SIGNET","TESTNET"]);function rt({decoded:t,expectedDestinationPublicKey:e,expectedNetwork:d,nowMs:p,skewToleranceMs:f}){if(!Number.isFinite(f)||f<0||f>X)throw new y({errorKey:"toolbox_lightspark_invalid_params",info:{expirySkewToleranceMs:f,maxExpirySkewToleranceMs:X,operation:"payInvoice"}});if(!H(t.paymentHash)||t.paymentHash!==t.paymentHash.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{paymentHash:t.paymentHash,reason:"missing or malformed payment hash"}});if(!Ht.has(t.network)||t.network!==d)throw new y({errorKey:"toolbox_lightspark_network_mismatch",info:{expectedNetwork:d,invoiceNetwork:t.network,paymentHash:t.paymentHash}});if(e!==void 0){if(!C(e))throw new y({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:e,paymentHash:t.paymentHash}});if(t.destinationPublicKey?.toLowerCase()!==e.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invoice_destination_mismatch",info:{expectedDestinationPublicKey:e,invoiceDestinationPublicKey:t.destinationPublicKey,paymentHash:t.paymentHash}})}let _=Date.parse(t.expiresAt);if(Number.isNaN(_))throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{expiresAt:t.expiresAt,paymentHash:t.paymentHash,reason:"unparseable expiry"}});if(p>_+f)throw new y({errorKey:"toolbox_lightspark_invoice_expired",info:{expiresAt:t.expiresAt,expirySkewToleranceMs:f,nowMs:p,paymentHash:t.paymentHash}})}function st({amountMsats:t,invoiceAmountMsats:e,paymentHash:d}){let p=t===void 0?void 0:I(t,"payInvoice amountMsats");if(e>0n){if(p!==void 0&&p!==e)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:e.toString(),paymentHash:d,requestedAmountMsats:t}});return{payAmountMsats:e,zeroAmountInvoice:!1}}if(p===void 0)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:"0",paymentHash:d,reason:"zero-amount invoice requires an explicit amountMsats"}});if(p===0n)throw new y({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"payInvoice amountMsats",paymentHash:d,reason:"amountMsats must be positive"}});return{payAmountMsats:p,zeroAmountInvoice:!0}}import{SwapKitError as c}from"@swapkit/helpers";var ct=60,ut=10,W=3000,Rt=K;function R(t){let e=L(t.amount),d=L(t.fees);return{...e===void 0?{}:{amountMsats:e.toString()},...d===void 0?{}:{feePaidMsats:d.toString()},failureReason:t.failureReason??void 0,paymentHash:t.transactionHash??void 0,preimage:t.paymentPreimage??void 0,status:B(t.status),transactionId:t.id}}function Y(t){return t.find((e)=>e.status==="SUCCESS")??t.find((e)=>!v(e.status))}function Ot(t){if(t.status==="CLOSED")return!0;let e=t.amountPaid?.originalValue;if(e===void 0||e===null)return!1;return typeof e==="number"?e>0:!0}function Ft({paymentHash:t,prior:e,requestedAmountMsats:d}){let p=L(e.amount);if(p===d)return;throw new c({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{operation:"payInvoice",paymentHash:t,...p===void 0?{}:{priorAmountMsats:p.toString()},priorTransactionId:e.id,reason:p===void 0?"a prior payment for this zero-amount invoice is denominated in a unit this toolbox cannot read, so it cannot be shown to match":"a prior payment for this zero-amount invoice used a different amount",requestedAmountMsats:d.toString()}})}async function dt({context:t,estimate:e,info:d,maximumFeesMsats:p,payAmountMsats:f}){let _=p!==void 0?I(p,t):at(f),P;try{P=L(await e())}catch{}if(P!==void 0&&P>_)throw new c({errorKey:"toolbox_lightspark_fee_limit_exceeded",info:{...d,estimatedFeeMsats:P.toString(),maximumFeesMsats:_.toString()}});return _}function Gt(t){let{nodeId:e}=t;if(!e||!(t.client||t.clientId&&t.clientSecret))throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClient:!!t.client,hasClientId:!!t.clientId,hasClientSecret:!!t.clientSecret,hasNodeId:!!e}});let d,p,f;async function _(n){try{return await import("@lightsparkdev/lightspark-sdk")}catch(i){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:n,reason:"@lightsparkdev/lightspark-sdk could not be loaded; install the optional peer dependency or inject a client"}},i)}}async function P(){if(t.client)return t.client;let{clientId:n,clientSecret:i}=t;if(!n||!i)throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClientId:!!n,hasClientSecret:!!i,hasNodeId:!!e}});let{AccountTokenAuthProvider:o,LightsparkClient:s}=await _("createClient");return new s(new o(n,i),t.apiUrl||void 0)}function k(){return d??=P().catch((n)=>{throw d=void 0,n}),d}function z(n,i){let o=V(n);return new c({errorKey:"toolbox_lightspark_signing_key_unavailable",info:{nodeId:e,operation:i,reason:"the node signing key could not be loaded",...o===void 0?{}:{vendorErrorCode:o}}})}function Q(n){let{signingKey:i}=t;if(!i)return Promise.resolve();return f??=n.loadNodeKey(e,{key:i}).catch((o)=>{throw f=void 0,z(o,"loadNodeKey")}),f}function j(n){if(t.signingKey||t.client)return;throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{operation:n,reason:"signingKey is required to send payments"}})}async function J(n){let i;if(n.getNodeById)i=await n.getNodeById(e);else if(n.executeRawQuery){let{getLightsparkNodeQuery:o}=await _("getNode");i=await n.executeRawQuery(o(e))}else throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"the injected client implements neither getNodeById nor executeRawQuery"}});if(!i)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"node not found"}});return p=i,i}async function Z(n){return p??await J(n)}async function tt({client:n,attempts:i,intervalMs:o,initial:s}){let a=s;if(v(a.status))return a;for(let r=0;r<i;r++){await U(o);try{let u=await n.getTransaction(s.id);if(u){if(a=u,v(u.status))return u}}catch{}}return a}async function pt(n,i){try{let o=await n.outgoingPaymentsForPaymentHash(i),s=Y(o);if(s)return{attemptSeq:0,existing:s};let a=await n.invoiceForPaymentHash(i);if(a&&Ot(a))throw new c({errorKey:"toolbox_lightspark_invoice_already_settled",info:{invoiceStatus:a.status,paymentHash:i}});return{attemptSeq:o.filter((r)=>r.status==="FAILED").length,existing:void 0}}catch(o){if(o instanceof c)throw o;throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"payInvoice preflight",paymentHash:i}},o)}}async function mt(n,i){try{return Y(await n.outgoingPaymentsForPaymentHash(i,["SUCCESS","PENDING"]))}catch{return}}async function ht(n,{paymentHash:i,transactionId:o}){if(o){let a=await n.getTransaction(o)??void 0;if(a)return{found:a,hashVerified:!1}}if(!i)return{found:void 0,hashVerified:!1};let s=await n.outgoingPaymentsForPaymentHash(i);return{found:Y(s)??s[s.length-1],hashVerified:!0}}async function lt(n,i,o,s){let a=!1,r,u=!1;for(let h=0;h<o;h++){if(h>0)await U(s);try{let m=await ht(n,i);if(u=!0,m.found){if(r=m.found,a=m.hashVerified,v(m.found.status))break}}catch{u=!1}}return{hashVerified:a,last:r,lookupSucceeded:u}}function O(n,i){let{timeoutSecs:o,attempts:s,intervalMs:a}=i;if(o!==void 0&&!(Number.isInteger(o)&&o>0)||s!==void 0&&!(Number.isInteger(s)&&s>=0)||a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:n,...i}})}function et(n,i){if(n instanceof c)throw n;let o=V(n);if(o==="SigningException")throw z(n,i);return o==="PaymentError"?"FAILED":"UNKNOWN"}async function ft(){let n=await k(),i=await J(n),o=i.balances?.availableToSendBalance??i.localBalance;if(!o)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getBalance",reason:"node reports no spendable balance"}});return{spendableMsats:b(o).toString(),...i.remoteBalance?{inboundCapacityMsats:b(i.remoteBalance).toString()}:{}}}async function nt(n){if(!n||typeof n!=="string")throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{reason:"empty invoice"}});let i=await k(),o;try{o=await i.decodeInvoice(n)}catch(s){throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"decodeInvoice"}},s)}if(!o?.paymentHash)throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{operation:"decodeInvoice",reason:"decoded invoice has no payment hash"}});return{amountMsats:b(o.amount).toString(),createdAt:o.createdAt,destinationPublicKey:o.destination?.publicKey??void 0,expiresAt:o.expiresAt,memo:o.memo??void 0,network:o.bitcoinNetwork,paymentHash:o.paymentHash}}async function gt({amountMsats:n,memo:i,expirySecs:o}){let s=I(n,"createInvoice"),r=await(await k()).createInvoiceWithDetails(e,S(s,"createInvoice"),i??"",void 0,o);if(!(r?.data?.encodedPaymentRequest&&r.data.paymentHash))throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createInvoice",reason:"invoice creation returned no invoice"}});return{amountMsats:b(r.data.amount).toString(),createdAt:r.data.createdAt,encodedInvoice:r.data.encodedPaymentRequest,expiresAt:r.data.expiresAt,paymentHash:r.data.paymentHash}}async function yt({amountMsats:n,memo:i}){let o=I(n,"createTestModeInvoice"),s=S(o,"createTestModeInvoice"),a=await k(),r;try{r=await a.createTestModeInvoice(e,s,i)}catch(u){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice"}},u)}if(!r)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice",reason:"test mode invoices require regtest credentials"}});return{encodedInvoice:r}}async function _t({invoice:n,amountMsats:i,maximumFeesMsats:o,destinationPublicKey:s,timeoutSecs:a=ct,attempts:r=ut,intervalMs:u=W,expirySkewToleranceMs:h=K}){j("payInvoice"),O("payInvoice",{attempts:r,intervalMs:u,timeoutSecs:a});let m=await k(),l=await nt(n),F=await Z(m);rt({decoded:l,expectedDestinationPublicKey:s,expectedNetwork:F.bitcoinNetwork,nowMs:Date.now(),skewToleranceMs:h});let{payAmountMsats:g,zeroAmountInvoice:w}=st({amountMsats:i,invoiceAmountMsats:I(l.amountMsats,"payInvoice"),paymentHash:l.paymentHash}),E=w?S(g,"payInvoice"):void 0,{attemptSeq:A,existing:G}=await pt(m,l.paymentHash);if(G){if(w)Ft({paymentHash:l.paymentHash,prior:G,requestedAmountMsats:g});return{...R(G),paymentHash:l.paymentHash,replayedPriorPayment:!0}}let St=await dt({context:"payInvoice maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForInvoice(e,n,E),info:{paymentHash:l.paymentHash},maximumFeesMsats:o,payAmountMsats:g});await Q(m);let Lt=S(St,"payInvoice maximumFeesMsats"),Pt=`${l.paymentHash}:${A}`,M;try{M=await m.payInvoice(e,n,Lt,a,E,Pt)}catch(it){if(et(it,"payInvoice")==="FAILED")return{failureReason:q(it),paymentHash:l.paymentHash,status:"FAILED"};M=await mt(m,l.paymentHash)}if(!M)return{paymentHash:l.paymentHash,status:"PENDING"};let Nt=await tt({attempts:r,client:m,initial:M,intervalMs:u}),N={...R(Nt),paymentHash:l.paymentHash};if(w&&N.status!=="FAILED"&&N.amountMsats!==g.toString())return{...N,reconciliationRequired:{reason:N.amountMsats===void 0?"AMOUNT_UNVERIFIABLE":"AMOUNT_MISMATCH",requestedAmountMsats:g.toString()},status:"PENDING"};return N}async function kt({destinationPublicKey:n,amountMsats:i,maximumFeesMsats:o,timeoutSecs:s=ct,attempts:a=ut,intervalMs:r=W}){if(j("sendPayment"),O("sendPayment",{attempts:a,intervalMs:r,timeoutSecs:s}),!C(n))throw new c({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:n}});let u=I(i,"sendPayment");if(u===0n)throw new c({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"sendPayment",reason:"amountMsats must be positive"}});let h=S(u,"sendPayment"),m=await k(),l=await dt({context:"sendPayment maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForNode(e,n,h),info:{destinationPublicKey:n},maximumFeesMsats:o,payAmountMsats:u}),F=S(l,"sendPayment maximumFeesMsats");await Q(m);let g={amountMsats:u.toString(),destinationPublicKey:n,sentAfter:new Date(Date.now()-Rt).toISOString()},w;try{w=await m.sendPayment(e,n,s,h,F)}catch(A){if(et(A,"sendPayment")==="FAILED")return{...g,failureReason:q(A),status:"FAILED"};return{...g,status:"PENDING"}}if(!w)return{...g,status:"PENDING"};let E=await tt({attempts:a,client:m,initial:w,intervalMs:r});return{...g,...R(E)}}async function It({transactionId:n,paymentHash:i,attempts:o=1,intervalMs:s=W}){if(!n&&!i)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",reason:"transactionId or paymentHash is required"}});O("getTransactionStatus",{attempts:o,intervalMs:s});let a=i?.toLowerCase();if(a!==void 0&&!H(a))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:i,reason:"malformed payment hash"}});let r=await k(),{hashVerified:u,last:h,lookupSucceeded:m}=await lt(r,{paymentHash:a,transactionId:n},o,s);if(!h)return{paymentHash:a,status:m?"NOT_FOUND":"UNKNOWN",transactionId:n};if(a&&!u&&h.transactionHash!==a)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:a,reason:h.transactionHash?"paymentHash does not match the transaction":"transaction carries no payment hash to verify against",transactionHash:h.transactionHash??void 0,transactionId:h.id}});return{...R(h),paymentHash:a??h.transactionHash??void 0}}async function wt({numTransactions:n,afterDate:i}={}){let o=await k(),s=await Z(o);return(await o.getRecentTransactions(e,n,s.bitcoinNetwork,i)).map((r)=>{let u=L(r.amount);return{...u===void 0?{}:{amountMsats:u.toString()},createdAt:r.createdAt,destinationId:r.destinationId??void 0,id:r.id,resolvedAt:r.resolvedAt??void 0,status:r.status,transactionHash:r.transactionHash??void 0,typename:r.typename}})}return{createInvoice:gt,createTestModeInvoice:yt,decodeInvoice:nt,getBalance:ft,getTransactionStatus:It,listTransactions:wt,payInvoice:_t,sendPayment:kt}}export{X as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MAX_MS,K as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS,Gt as getLightsparkToolbox};