@swapkit/toolboxes 5.4.1 → 6.0.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 (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{chunk-4428244x.js → chunk-exyqap7m.js} +1 -1
  3. package/dist/chunk-ncc6qmj6.js +1 -0
  4. package/dist/{chunk-as9fracn.js → chunk-xdkdc1f0.js} +1 -1
  5. package/dist/{chunk-rn33j2bm.js → chunk-ygq25ce3.js} +2 -2
  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/near/index.js +1 -1
  14. package/dist/src/radix/index.js +1 -1
  15. package/dist/src/ripple/index.js +1 -1
  16. package/dist/src/solana/index.js +1 -1
  17. package/dist/src/starknet/index.js +1 -1
  18. package/dist/src/stellar/index.js +1 -1
  19. package/dist/src/substrate/index.js +1 -1
  20. package/dist/src/sui/index.js +1 -1
  21. package/dist/src/ton/index.js +1 -1
  22. package/dist/src/tron/index.js +1 -1
  23. package/dist/src/utxo/index.js +1 -1
  24. package/dist/types/cosmos/types.d.ts +0 -1
  25. package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -0
  26. package/dist/types/evm/toolbox/op.d.ts +8 -0
  27. package/dist/types/near/toolbox.d.ts +0 -2
  28. package/dist/types/near/types/toolbox.d.ts +0 -2
  29. package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +6 -5
  30. package/dist/types/utxo/helpers/addressType.d.ts +8 -0
  31. package/dist/types/utxo/helpers/network.d.ts +4 -0
  32. package/dist/types/utxo/helpers/scriptTypes.d.ts +40 -0
  33. package/dist/types/utxo/helpers/txSize.d.ts +7 -6
  34. package/dist/types/utxo/helpers/xpubDerivation.d.ts +4 -2
  35. package/dist/types/utxo/index.d.ts +1 -1
  36. package/dist/types/utxo/toolbox/bitcoinCash.d.ts +5 -8
  37. package/dist/types/utxo/toolbox/index.d.ts +3 -7
  38. package/dist/types/utxo/toolbox/params.d.ts +24 -19
  39. package/dist/types/utxo/toolbox/utxo.d.ts +51 -36
  40. package/dist/types/utxo/toolbox/validators.d.ts +1 -2
  41. package/dist/types/utxo/toolbox/zcash.d.ts +6 -8
  42. package/dist/types/utxo/types.d.ts +4 -1
  43. package/package.json +2 -2
  44. package/dist/chunk-dssawneq.js +0 -1
@@ -1 +1 @@
1
- import"../../chunk-4428244x.js";import{base64 as Y,bech32 as G}from"@scure/base";import{SwapKitError as at}from"@swapkit/helpers";function z(i){return Y.encode(Uint8Array.from(G.fromWords(G.decode(i).words)))}function X(i,o="thor"){return G.encode(o,G.toWords(Y.decode(i)))}function Me(i){return Y.encode(i)}function _e(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new at("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return Y.decode(i)}import{encodeMessage as It,encodeTxBody as Rt}from"@swapkit/cosmos-signer";import{AssetValue as Kt,Chain as tn,getChainConfig as Ln,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Q,getAccount as Mn,getBalances as ut,createTendermintRpc as lt,defaultEncoders as ft,encodeAuthInfo as Pn,encodeMessage as dt,encodePubkey as mt,encodeTxBody as pt,encodeTxRaw as vn,makeStdSignDoc as yt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as b,getChainConfig as M,getRPCUrl as gt,RequestClient as ht,SKConfig as Dn,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var _n="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",bt="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",At={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},St={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function _(i){switch(i){case b.Maya:return{amount:[],gas:"10000000000"};case b.THORChain:return{amount:[],gas:"500000000"};case b.Kujira:return wt;case b.Noble:return St;default:return At}}async function Z(i){let{isStagenet:o}=Dn.get("envs"),r=Dn.get("thornodeUrls"),n=i===b.Maya,e=`${n?o?r.MAYA_STAGENET:r.MAYA:o?r.THOR_STAGENET:r.THOR}/${n?"mayachain":"thorchain"}/constants`,s=M(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:c}}=await ht.get(e);if(!Number.isInteger(c)||c<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:c.toString()});return dn.fromBigInt(BigInt(c),s)}catch{let c=n?10000000000n:2000000n;return dn.fromBigInt(c,s)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return _n;case"uYUM":case"YUM":return bt;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},nn=({symbol:i,chain:o})=>{if(o===b.Maya)return(i.toUpperCase()!=="CACAO"?i:`${b.Maya}.${i}`).toUpperCase();if(o===b.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${b.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},Ct=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function Nn(i){return lt(i,{headers:Ct()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ot(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 N(i){let o=Nn(i);return{async broadcastTx(r){let n=await Q(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 Mn(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 ut(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Bn(i,o={}){let r=Tt(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((g)=>g.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=Dt({memo:c,messages:e,registry:o.registry}),C=mt({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let g=e.map((k)=>vt(k,o.aminoTypes)),A=yt({accountNumber:a.accountNumber,chainId:a.chainId,fee:xt(s),memo:c,msgs:g,sequence:a.sequence}),S=await i.signAmino(t,A),O=Pn({fee:Pt(S.signed.fee,s),signerInfos:[{mode:"amino",pubkey:C,sequence:BigInt(S.signed.sequence)}]}),D=ln.decode(S.signature.signature);return{authInfoBytes:O,bodyBytes:w,signatures:[D]}}let m=Pn({fee:kt(s),signerInfos:[{mode:"direct",pubkey:C,sequence:BigInt(a.sequence)}]}),y=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),f=ln.decode(y.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[f]}}return{signWithRegistry:n}}function Tt(i){return typeof i.signAmino==="function"}function xt(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 kt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function Pt(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 vt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ot(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 Dt(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={...ft,...n??{}},e=r.map((s)=>dt(s,t));return pt({memo:o,messages:e})}async function E(i,o,r={}){let n=typeof r==="string"?{}:r,t=Nn(i),e=Bn(o,n);async function s(c,a){let p=await Mn(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 Q(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 C=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),y=await e.signWithRegistry(c,C,h,w,m),f=vn({authInfoBytes:y.authInfoBytes,bodyBytes:y.bodyBytes,signatures:y.signatures}),g=await Q(t,f,"sync");if(g.code!==0)throw new P("core_swap_transaction_error",{code:g.code,message:g.log});return{code:g.code,rawLog:g.log,transactionHash:g.hash}},async sign(c,a,p,h,w){let C=w??await s(c);return e.signWithRegistry(c,a,p,h,C)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),C=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:C.authInfoBytes,bodyBytes:C.bodyBytes,signatures:C.signatures}),y=await Q(t,m,"sync");return{code:y.code,rawLog:y.log,transactionHash:y.hash}}}}async function Fn(i,o){let r=Bn(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 Mt=(i)=>{switch(i){case b.Maya:case b.THORChain:return"/types.MsgSend";case b.Cosmos:case b.Kujira:case b.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function _t({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 In({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 N(await gt(a)):void 0,C=h&&w?await _t({client:w,sender:i}):void 0,m=fn.from({chain:a}),y=U(m.symbol),f=_(a),g=y&&t?{amount:[{amount:t.toString(),denom:y}],gas:f.gas}:f,A=U(r.symbol),S=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});S=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(g.amount,A)})}let O={amount:[{amount:S.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(C?.accountNumber),chainId:p,fee:g,memo:n,msgs:[{typeUrl:Mt(a),value:O}],sequence:e??Number(C?.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 Nt={atom:{chain:b.Cosmos,decimals:M(b.Cosmos).baseDecimal},cacao:{chain:b.Maya,decimals:10},kuji:{chain:b.Kujira,decimals:M(b.Kujira).baseDecimal},maya:{asset:`${b.Maya}.${b.Maya}`,decimals:4},rune:{chain:b.THORChain,decimals:M(b.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:M(b.THORChain).baseDecimal},uatom:{chain:b.Cosmos,decimals:M(b.Cosmos).baseDecimal},ukuji:{chain:b.Kujira,decimals:M(b.Kujira).baseDecimal},usdc:{chain:b.Noble,decimals:M(b.Noble).baseDecimal},uusdc:{chain:b.Noble,decimals:M(b.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:M(b.THORChain).baseDecimal},[_n.toLowerCase()]:{asset:`${b.Kujira}.USK`,decimals:M(b.Kujira).baseDecimal}},Rn=(i,o)=>{let r=Nt[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 Kn}from"@swapkit/helpers";import T from"protobufjs/minimal.js";var d=T.Reader,v=T.Writer,l=T.util,u=T.roots.default||(T.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(!l.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!l.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!l.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,T.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=l.Long?l.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(!l.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!l.isInteger(n.decimals)&&!(n.decimals&&l.isInteger(n.decimals.low)&&l.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(l.Long)(t.decimals=l.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 l.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="",l.Long){let s=new l.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?l.Long.prototype.toString.call(n.decimals):t.longs===Number?new l.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,T.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(!l.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!l.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,T.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=l.emptyArray,o.prototype.gas=l.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(!l.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!l.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!l.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!l.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(!l.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,T.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=l.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(!l.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,T.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(!l.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,T.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=l.emptyArray,o.prototype.memo="",o.prototype.signer=l.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(!l.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||l.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")l.base64.decode(n.signer,t.signer=l.newBuffer(l.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=l.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?l.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,T.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=l.newBuffer([]),o.prototype.toAddress=l.newBuffer([]),o.prototype.amount=l.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"||l.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||l.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")l.base64.decode(n.fromAddress,t.fromAddress=l.newBuffer(l.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")l.base64.decode(n.toAddress,t.toAddress=l.newBuffer(l.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=l.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=l.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?l.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?l.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,T.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(!l.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!l.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,T.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(!l.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!l.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,T.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(!l.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,T.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(!l.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,T.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 Bt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Ft=(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 H(){return{...Ut,"/types.MsgDeposit":Ft,"/types.MsgSend":Bt}}function I(i,o=i===Kn.THORChain?"thor":"maya"){let r=i===Kn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:z(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?X(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:z(t),toAddress:z(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?X(t,o):t,to_address:typeof e==="string"?X(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 Ge=_(tn.THORChain).gas,Ye=_(tn.Maya).gas,jn=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===tn.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),En=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===tn.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:nn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?En({assetValue:r,memo:n,sender:i}):jn({assetValue:r,recipient:o,sender:i});function Hn(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var R=(i,o)=>{let r=I(o),n=Hn(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)}},Jn=async({rpcUrl:i,sender:o})=>{let n=await(await N(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function $n(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 Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return jt({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(n)).getAllBalances(o),s=i.isGasAsset?(await Z(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Lt({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 Jn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Ln(a),w=jn({assetValue:r,recipient:o,sender:i}),C=t?R(e?w:K(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:_(a),memo:n,msgs:[C],sequence:s??Number(p?.sequence)}}async function jt({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 Jn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Ln(c),h=En({assetValue:o,memo:r,sender:i}),w=n?R(t?h:K(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:_(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function K(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Kt.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 en({chain:i,memo:o,msgs:r}){let n=H(),t=I(i),s=r.map((c)=>{let a=Hn(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)=>It(c,n));return Rt({memo:o,messages:s})}import{Chain as V,SwapKitError as ke}from"@swapkit/helpers";import{secp256k1 as Et}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Ht}from"@scure/bip32";import{verifySignature as Jt,createWalletFromMnemonic as $t,createWalletFromPrivateKey as Wt,mnemonicToSeed as qt,signDirect as Vt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as Wn,Chain as x,CosmosChainPrefixes as Xn,DerivationPath as Gt,derivationPathToString as qn,FeeOption as Tn,getChainConfig as Yt,getRPCUrl as q,NetworkDerivationPath as zt,SwapKitError as B,SwapKitNumber as wn,updateDerivationPath as Xt}from"@swapkit/helpers";import{SwapKitApi as Qn}from"@swapkit/helpers/api";import{PubKey as Qt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Zt,P as Vn}from"ts-pattern";async function Zn(i,o){try{let n=(await Qn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function nt(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 B("toolbox_cosmos_signer_not_defined");let t=await Vt(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 Gn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Gt[r.chain]}/${r.index??0}`,t=await $t({hdPath:n,mnemonic:i,prefix:o??""});return nt(t)}async function ne({privateKey:i,prefix:o}){let r=Wt({prefix:o,privateKey:i});return nt(r)}var Yn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function te(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new B("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Qt.decode(e.pubkey.value).key:e.pubkey.value;return Jt(Cn.decode(n),Cn.decode(r),s)}}function on({chain:i,...o}){let r=Xn[i],n="index"in o?o.index||0:0,t=qn("derivationPath"in o&&o.derivationPath?o.derivationPath:Xt(zt[i],{index:n})),e;async function s(){if(e)return e;return e=await Zt(o).with({phrase:Vn.string},({phrase:m})=>Gn({derivationPath:t,phrase:m,prefix:r})).with({signer:Vn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let y=await q(i);return(await N(y)).getAccount(m)}async function a(){let m=await s(),[y]=await m?.getAccounts()||[];return y?.address}async function p(){let m=await s(),[y]=await m?.getAccounts()||[];if(!y?.pubkey)throw new B("toolbox_cosmos_signer_not_defined");return Cn.encode(y?.pubkey)}async function h(m){let y=await s(),f=await a(),g=await q(i);if(!(y&&f))throw new B("toolbox_cosmos_signer_not_defined");return(await E(g,y)).sign(f,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let y=await s(),f=await a(),g=await q(i);if(!(y&&f))throw new B("toolbox_cosmos_signer_not_defined");let S=await(await E(g,y)).signAndBroadcast(f,m.msgs,m.fee,m.memo);if(S.code!==0)throw new B("core_swap_transaction_error",{code:S.code,message:S.rawLog});return S.transactionHash}async function C({recipient:m,assetValue:y,memo:f="",feeRate:g,feeOptionKey:A=Tn.Fast,sweep:S}){let O=await s(),D=await a();if(!(O&&D))throw new B("toolbox_cosmos_signer_not_defined");let k=await q(i),rn=On.from({chain:i}),sn=nn(rn),j=ee(g||(await zn(i,Yn[i]))[A],sn,i),cn=await E(k,O),J=U(y.symbol),an=[{amount:(S?W({assetValue:y,balances:await Sn(i)(D),denom:J,feeAmount:mn(j.amount,J)}):y).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(D,m,an,j,f);return un}return{createPrivateKeyFromPhrase:re(t),createTransaction:In,fetchFeeRateFromSwapKit:Zn,getAccount:c,getAddress:a,getBalance:async(m,y)=>{let f=await Sn(i)(m),g=await Promise.all(f.filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).map(({denom:A,amount:S})=>{let O=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;return Rn(O,S)}));if(g.length===0)return[On.from({chain:i})];return g},getBalanceAsDenoms:Sn(i),getFees:()=>zn(i,Yn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:y})=>Gn({derivationPath:qn(y),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>ne({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:C,validateAddress:ie(i),verifySignature:te(c)}}async function mo(i,o){try{let n=(await Qn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function po({assetValue:{chain:i}}){return On.from({chain:i,value:oe(i)})}async function zn(i,o){let{chainId:r,baseDecimal:n}=Yt(i),t=await Zn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt(Wn(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt(Wn(t,Tn.Fastest,!0)),n)}}function ee(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:_(r).gas}}function oe(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 ie(i){let o=Xn[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(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function re(i){return async function(r){let n=await qt(r),e=Ht.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new B("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return Et.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as se}from"@noble/curves/secp256k1.js";import{base64 as F}from"@scure/base";import{buildMultisignedTx as ce,createMultisigThresholdPubkey as ae,signAmino as ue,createWalletFromMnemonic as le,encodeTxRaw as fe,multisigPubkeyToAddress as de,singlePubkeyToAddress as et}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as me,derivationPathToString as pe,FeeOption as xn,getRPCUrl as ot,NetworkDerivationPath as ye,SKConfig as ge,SwapKitError as L,updateDerivationPath as he}from"@swapkit/helpers";import{match as be,P as tt}from"ts-pattern";function Ae(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new L("toolbox_cosmos_signer_not_defined");let t=await ue(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function we({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await le({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return Ae(e)}}function Se(i){return F.encode(i)}function Ce(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||"",C=I(i,o),m=H(),y=await Fn(n,{aminoTypes:C,registry:m}),f=[];for(let S of e){let O=R(S,i);f.push(O)}let{signatures:[g]}=await y.sign(w,f,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:en({chain:i,memo:h,msgs:e.map(K)}),signature:Se(g)}}}function it(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new L("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:F.encode(i)}}function Oe({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await ot(o),{sequence:p,fee:h}=JSON.parse(n),w=rt(e,s),C=t.map((f)=>[et(it(F.decode(f.pubKey)),i),F.decode(f.signature)]),m=await N(a),{transactionHash:y}=await m.broadcastTx(ce({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(C)}));return y}}function rt(i,o,r=!0){return ae(i.map((n)=>it(F.decode(n))),o,r)}function Te(i){return F.decode(i)}function xe({privateKey:i,message:o}){let r=se.sign(F.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(F.encode(r))}function st({chain:i,...o}){let{isStagenet:r}=ge.get("envs"),n=`${r?"s":""}${me[i]}`,t="index"in o?o.index||0:0,e="derivationPath"in o&&o.derivationPath?o.derivationPath:he(ye[i],{index:t}),s=on({chain:i,...o}),c=_(i),a;function p(){return a??=be(o).with({phrase:tt.string},({phrase:f})=>s.getSignerFromPhrase({derivationPath:e,phrase:f})).with({signer:tt.any},({signer:f})=>Promise.resolve(f)).otherwise(()=>Promise.resolve(void 0)),a}async function h(){let f=await ot(i),g=await p();if(!g)throw new L("toolbox_cosmos_no_signer");let A=H(),S=I(i,n),O=await E(f,g,{aminoTypes:S,registry:A});return{signer:g,signingClient:O}}async function w({fee:f,memo:g,msgs:A}){let{signer:S,signingClient:O}=await h(),D=(await S.getAccounts())?.[0]?.address;if(!D)throw new L("toolbox_cosmos_signer_not_defined");let k=await O.signAndBroadcast(D,A,f,g);if(k.code!==0)throw new L("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function C(){let f=await Z(i);return{[xn.Average]:f,[xn.Fast]:f,[xn.Fastest]:f}}async function m({assetValue:f,memo:g="",recipient:A,sweep:S}){let{signer:O,signingClient:D}=await h(),k=(await O.getAccounts())?.[0]?.address;if(!k)throw new L("toolbox_cosmos_no_signer");let rn="signAmino"in O,sn=S?await bn({assetValue:f,sender:k}):f,j=hn({assetValue:sn,memo:g,recipient:A,sender:k});if(rn){let kn=R(j,i),{signatures:an,authInfoBytes:un}=await D.sign(k,[kn],c,g),ct=fe({authInfoBytes:un,bodyBytes:en({chain:i,memo:g,msgs:[j].map(K)}),signatures:an});return(await D.broadcastTx(ct)).transactionHash}let cn=K(j),J=R(cn,i);return w({fee:c,memo:g,msgs:[J]})}async function y(f){let{signer:g,signingClient:A}=await h(),S=(await g.getAccounts())?.[0]?.address;if(!S)throw new L("toolbox_cosmos_signer_not_defined");return A.sign(S,f.msgs,f.fee,f.memo,{accountNumber:BigInt(f.accountNumber),chainId:f.chainId,sequence:f.sequence})}return{...s,broadcastMultisigTx:Oe({chain:i,prefix:n}),buildAminoMsg:hn,buildEncodedTxBody:en,convertToSignable:R,createDefaultAminoTypes:()=>I(i,n),createDefaultRegistry:H,createMultisig:rt,createTransaction:$n,deposit:m,getFees:C,importSignature:Te,parseAminoMessageForDirectSigning:K,pubkeyToAddress:(f)=>{if(f.type==="tendermint/PubKeyMultisigThreshold")return de(f,n);return et(f,n)},secp256k1HdWalletFromMnemonic:we({derivationPath:pe(e),prefix:n}),signAndBroadcastTransaction:w,signMultisigTx:Ce(i,n),signTransaction:y,signWithPrivateKey:xe,transfer:m}}var vo=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return on({chain:i,...o});case V.Maya:case V.THORChain:return st({chain:i,...o});default:throw new ke("toolbox_cosmos_not_supported",{chain:i})}};export{At as DEFAULT_COSMOS_FEE_MAINNET,wt as DEFAULT_KUJI_FEE_MAINNET,St as DEFAULT_NOBLE_FEE_MAINNET,Ye as MAYA_GAS_VALUE,Ge as THORCHAIN_GAS_VALUE,_n as USK_KUJIRA_FACTORY_DENOM,bt as YUM_KUJIRA_FACTORY_DENOM,X as base64ToBech32,z as bech32ToBase64,hn as buildAminoMsg,jt as buildDepositTx,en as buildEncodedTxBody,Lt as buildTransferTx,R as convertToSignable,In as cosmosCreateTransaction,on as createCosmosToolbox,I as createDefaultAminoTypes,H as createDefaultRegistry,Fn as createOfflineStargateClient,E as createSigningStargateClient,N as createStargateClient,st as createThorchainToolbox,$n as createTransaction,En as depositMsgAmino,po as estimateTransactionFee,Zn as fetchFeeRateFromSwapKit,_e as fromBase64,Rn as getAssetFromDenom,ie as getCosmosAddressValidator,vo as getCosmosToolbox,_ as getDefaultChainFee,nn as getDenomWithChain,mn as getFeeAmountForDenom,mo as getFeeRateFromSwapKit,U as getMsgSendDenom,Gn as getSignerFromPhrase,ne as getSignerFromPrivateKey,W as getSweepAssetValue,Z as getThorchainNativeFee,K as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,Me as toBase64,jn as transferMsgAmino,te as verifySignature};
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"},wt={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},At={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 wt;case g.Noble:return At;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 A=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)),w=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,w),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:A,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:A,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:A,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let 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,A=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((w)=>({amount:w.amount,denom:w.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,A,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,A){let S=A??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let A=await s(c),S=await e.signWithRegistry(c,a,p,h,A),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,A=c||h?await _(await pt(a)):void 0,S=h&&A?await Mt({client:A,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,w=U(r.symbol),C=r;if(c){if(!A)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await A.getAllBalances(i),denom:w,feeAmount:mn(b.amount,w)})}let T={amount:[{amount:C.getBaseValue("string"),denom:w}],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),A=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?A:R(A),a):A;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage: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}),A=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[A],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 wn}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 An,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 A(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await 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:w=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]))[w],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 y=await Sn(i)(m),b=await Promise.all(y.filter(({denom:w})=>w&&!w.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&w.split("-").length>2)).map(({denom:w,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(w.includes("/")||w.includes("˜"))?`${i}.${w}`:w;return In(T,C)}));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:A,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:An.fromBigInt(BigInt(t),n),fast:An.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:An.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}=wn.decode(n);return wn.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 we(i){return B.encode(i)}function Ae(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,A=(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(A,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:we(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),A=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:A,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,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(),w=F(i,r),C=await L(l,y,{aminoTypes:w,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:w,signingClient:C}=await p(),T=(await w.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 A(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:w}){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=w?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(),w=(await y.getAccounts())?.[0]?.address;if(!w)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(w,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:A,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:Ae(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,wt as DEFAULT_KUJI_FEE_MAINNET,At 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 fa}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,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}from"../../chunk-rn33j2bm.js";import"../../chunk-as9fracn.js";import"../../chunk-4428244x.js";export{H as ADIToolbox,I as ARBToolbox,J as ARCToolbox,K as AURORAToolbox,L as AVAXToolbox,M as BASEToolbox,N as BERAToolbox,O as BSCToolbox,o as BaseEVMToolbox,P as BotanixToolbox,Q as COREToolbox,R as CORNToolbox,S as CROToolbox,x as ContractAddress,G as ETHToolbox,fa as EthNetwork,T as GNOToolbox,U as HOODToolbox,V as HYPEREVMToolbox,W as LINEAToolbox,X as MATICToolbox,n as MAX_APPROVAL,Y as MEGAETHToolbox,Z as MONADToolbox,F as OPToolbox,_ as PLASMAToolbox,aa as SONICToolbox,ba as UNIToolbox,ca as XLayerToolbox,k as buildEIP712DomainType,r as createContract,b as createCustomEvmApi,E as createOPStackToolbox,w as getChecksumAddressFromAsset,s as getCreateContract,z as getCreateContractTxObject,v as getEIP1193SendTransaction,D as getEVMTxType,A as getEstimateGasPrices,a as getEvmApi,da as getEvmToolbox,ea 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,l as parseEIP712FromEVMTx,i as signAuthorization,u as toChecksumAddress,f as toHexString,j as validateAuthorization,m as validateAuthorizations,p as validateEVMAddress};
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 +1 @@
1
- import"../../chunk-qsbf0z90.js";import{q as we}from"../../chunk-rn33j2bm.js";import"../../chunk-as9fracn.js";import"../../chunk-4428244x.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{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};
package/dist/src/index.js CHANGED
@@ -1 +1 @@
1
- import{ha as o}from"../chunk-4428244x.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-dssawneq.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{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 +1 @@
1
- import{ga as wt}from"../../chunk-as9fracn.js";import{ha as l}from"../../chunk-4428244x.js";import{Chain as Gt,derivationPathToString as Kt,SwapKitError as rt}from"@swapkit/helpers";function G(e){return e.length>=2&&e.length<=64&&/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(e)}async function M(e){if(e.derivationPath&&(e.derivationPath[3]||e.derivationPath[4]))throw new rt("toolbox_derivation_slot_unsupported",{chain:Gt.Near,derivationPath:e.derivationPath});let{KeyPair:s}=await import("@near-js/crypto"),c=e.derivationPath?Kt(e.derivationPath.slice(0,3)):`m/44'/397'/${e.index??0}'`,{parseSeedPhrase:g}=await import("near-seed-phrase"),{secretKey:P}=g(e.phrase,c),y=s.fromString(P);return at(y)}async function et(e){let{KeyPair:s}=await import("@near-js/crypto"),c=s.fromString(e);return at(c)}async function at(e){let{KeyPairSigner:s}=await import("@near-js/signers");class c extends s{#t;constructor(g){super(g);this.#t=g}getAddress(){let g=this.#t.getPublicKey(),P=Buffer.from(g.data).toString("hex");return Promise.resolve(P)}}return new c(e)}async function j(e,s){let g=(await e.query({account_id:s,finality:"final",request_type:"view_access_key_list"})).keys.find((K)=>K.access_key.permission==="FullAccess");if(!g)throw new rt("toolbox_near_no_public_key_found");let{PublicKey:P}=await import("@near-js/crypto"),y=P.fromString(g.public_key);return{nonce:g.access_key.nonce||0,publicKey:y}}var p={ACCESS_KEY_ADDITION:"5",ACCESS_KEY_DELETION:"5",ACCOUNT_CREATION:"30",CONTRACT_CALL:"150",CONTRACT_DEPLOYMENT:"200",SIMPLE_TRANSFER:"1",STAKE:"10",STORAGE_DEPOSIT:"150",TOKEN_TRANSFER:"150"};function ot(e){return"recipient"in e&&"amount"in e&&!("contractId"in e)}function it(e){return"contractId"in e&&"methodName"in e}function st(e){return"actions"in e}function ct(e){return"newAccountId"in e}function gt(e){return"contractCode"in e}function mt(e){return"customEstimator"in e}function ut(e){let s=0;for(let c of e)switch(c.enum){case"transfer":s+=Number(p.SIMPLE_TRANSFER);break;case"functionCall":s+=Number(p.CONTRACT_CALL);break;case"createAccount":s+=Number(p.ACCOUNT_CREATION);break;case"deployContract":s+=Number(p.CONTRACT_DEPLOYMENT);break;case"addKey":s+=Number(p.ACCESS_KEY_ADDITION);break;case"deleteKey":s+=Number(p.ACCESS_KEY_DELETION);break;case"stake":s+=Number(p.STAKE);break;default:s+=Number(p.CONTRACT_CALL)}return s.toString()}function dt(e){if(e==="ft_transfer"||e==="ft_transfer_call")return p.TOKEN_TRANSFER;if(e==="storage_deposit")return p.STORAGE_DEPOSIT;return p.CONTRACT_CALL}function Ut(e){return(BigInt(e)*BigInt(1000000000000)).toString()}function Vt(e){return(BigInt(e)/BigInt(1000000000000)).toString()}async function lt({account:e,contractId:s,viewMethods:c,changeMethods:g}){let{Contract:P}=await import("@near-js/accounts");return new P(e,s,{changeMethods:g,useLocalViewExecution:!0,viewMethods:c})}import{AssetValue as ft,Chain as x,getRPCUrl as kt,SwapKitError as u}from"@swapkit/helpers";import{match as pt,P as Pt}from"ts-pattern";var _t=1250000000000000000000n,yt=150000000000000n,Ft=150000000000000n,Dt=250000000000000n,Ot=250000000000000n,Lt=500n,U=10000n;function Xt(e){let s;async function c(){if(s)return s;return s=await pt(e).with({phrase:Pt.string},async(t)=>await M(t)).with({signer:Pt.any},({signer:t})=>t).otherwise(()=>{return}),s}async function g(){let{JsonRpcProvider:t}=await import("@near-js/providers"),n=await kt(x.Near);return new t({url:n})}async function P(t){let{Account:n}=await import("@near-js/accounts"),r=await g(),a=await c(),o=t||await y();return new n(o,r,a)}async function y(){let t=await c();if(!t)throw new u("toolbox_near_no_signer");return await t.getAddress()}async function V(t,n){return(n||await g()).callFunction(t.contractId,"storage_balance_of",{account_id:t.accountId},{finality:"final"})}async function K(t,n){try{let r=await n.callFunction(t,"storage_balance_bounds",{},{finality:"final"});return r?.min?BigInt(r.min):_t}catch{return _t}}function k(t){return(t*(U+Lt)+U-1n)/U}function J(t,n){return BigInt(t)*BigInt(n.runtime_config.storage_amount_per_byte)}function z(t,n){if(t<=0n)throw new u({errorKey:"toolbox_sweep_amount_too_low",info:n});return t}async function F(t){return await(t||await g()).experimental_protocolConfig({finality:"final"})}async function Tt(t,n,r){let o=await(r||await g()).callFunction(t,"ft_balance_of",{account_id:n},{finality:"final"});return BigInt(o||"0")}async function ht(t){if(!await c())throw new u("toolbox_near_no_signer");let{assetValue:r,recipient:a,memo:o,sweep:i}=t,m=await y(),d=await Y({assetValue:r,memo:o,recipient:a,sender:m,sweep:i});return X(d)}async function St({assetValue:t,attachedDeposit:n,memo:r,provider:a,recipient:o,sender:i,sweep:m}){let d=t.address;if(!d)throw new u("toolbox_near_missing_contract_address");let f=await V({accountId:o,contractId:d},a),_=f?0n:await K(d,a),w=f?Dt:Ft,T=BigInt(n||"1"),N=t.getBaseValue("bigint");if(m){let[S,A,b,I]=await Promise.all([Tt(d,i,a),a.viewAccount(i,{finality:"final"}),F(a),L(a)]);N=z(S,{asset:t.toString(),balance:S.toString()});let B=J(A.storage_usage,b),C=A.amount-B,R=_,nt=(w+(f?0n:yt))*k(I)+R+T;if(C<nt)throw new u("toolbox_sweep_amount_too_low",{asset:t.toString(),availableNear:C.toString(),reason:"Insufficient NEAR to cover token transfer gas and storage deposit",requiredNear:nt.toString()})}let h=[];if(!f)h.push(await E({args:{account_id:o},attachedDeposit:_.toString(),gas:yt.toString(),methodName:"storage_deposit"}));return h.push(await E({args:{amount:N.toString(),memo:r||null,receiver_id:o},attachedDeposit:T.toString(),gas:w.toString(),methodName:"ft_transfer"})),W({actions:h,receiverId:d,sender:i})}async function Nt({assetValue:t,attachedDeposit:n,memo:r,provider:a,recipient:o,sender:i,sweep:m}){let d=t.getBaseValue("bigint");if(m){let[b,I]=await Promise.all([a.viewAccount(i,{finality:"final"}),F(a)]),B=await Z({assetValue:t,memo:r,recipient:o,sweep:m},I),C=J(b.storage_usage,I),R=0n;if(r&&n){let tt=await L(a);R=Ot*k(tt)+BigInt(n)}d=z(b.amount-B.getBaseValue("bigint")-C-R,{asset:t.toString(),balance:b.amount.toString(),fee:B.getBaseValue("bigint").toString(),storageStakeReserve:C.toString()})}let[{publicKey:f,nonce:_},w,{actionCreators:T,createTransaction:N},{baseDecode:h}]=await Promise.all([j(a,i),a.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),S=[T.transfer(d)];if(r&&n)S.push(T.functionCall("memo",{memo:r},BigInt("250000000000000"),BigInt(n)));let A=h(w.header.hash);return N(i,f,o,_+1,S,A)}async function Y({recipient:t,assetValue:n,memo:r,attachedDeposit:a,sender:o,functionCall:i,sweep:m}){if(!G(t))throw new u("toolbox_near_invalid_address",{recipient:t});if(!G(o))throw new u("toolbox_near_invalid_address",{sender:o});if(i)return H({...i,sender:o});if(m&&!await c())throw new u("toolbox_near_no_signer");let d=await g(),f={assetValue:n,attachedDeposit:a,memo:r,provider:d,recipient:t,sender:o,sweep:m};return n.isGasAsset?Nt(f):St(f)}function At(t){let n=t.encode();return Buffer.from(n).toString("base64")}async function H({args:t,attachedDeposit:n,contractId:r,gas:a,methodName:o,sender:i}){let m=await E({args:t,attachedDeposit:n,gas:a,methodName:o});return W({actions:[m],receiverId:r,sender:i})}async function W({actions:t,receiverId:n,sender:r}){let a=await g(),[{publicKey:o,nonce:i},m,{createTransaction:d},{baseDecode:f}]=await Promise.all([j(a,r),a.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),_=f(m.header.hash);return d(r,o,n,i+1,t,_)}async function E(t){let{actionCreators:n}=await import("@near-js/transactions");return n.functionCall(t.methodName,Buffer.from(JSON.stringify(t.args)),BigInt(t.gas),BigInt(t.attachedDeposit))}async function q(t){let n=await c();if(!n)throw new u("toolbox_near_no_signer");await bt(t);let[r,a]=await n.signTransaction(t);return a}async function bt(t){let n=t.publicKey;if(n.toString?.().startsWith("ed25519:")||n.toString?.().startsWith("secp256k1:"))return;let{KeyType:r,PublicKey:a}=await import("@near-js/crypto"),o=n.data||n.ed25519Key?.data,i=n.secp256k1Key?.data;if(o){t.publicKey=new a({data:Uint8Array.from(o),keyType:r.ED25519});return}if(i)t.publicKey=new a({data:Uint8Array.from(i),keyType:r.SECP256K1})}function D(t){if(typeof t==="string")return t;if(Array.isArray(t))return t.map(D).find(Boolean);if(!(t&&typeof t==="object"))return;let n=t;return n.transaction?.hash||n.transaction_outcome?.id}function O(t){return t instanceof Error?t.message:String(t)}async function Q(t){let r=await(await g()).sendTransaction(t),a=D(r);if(!a)throw new u("toolbox_near_transfer_failed",{result:r});return a}async function X(t){let n=await c();if(!n)throw new u("toolbox_near_no_signer");let r;try{r=await q(t)}catch(a){let o;try{o=n.signAndSendTransaction?await n.signAndSendTransaction({actions:t.actions,receiverId:t.receiverId,signerId:t.signerId}):await n.signAndSendTransactions?.({transactions:[t]})}catch(m){throw new u({errorKey:"toolbox_near_sign_transaction_failed",info:{directSignError:O(a),signAndSendError:O(m)}},m)}let i=D(o);if(i)return i;throw a}return Q(r)}async function Z(t,n){let r=await c();if("assetValue"in t){if(t.sweep&&!r)throw new u("toolbox_near_no_signer");try{let[o,i]=await Promise.all([L(),n?Promise.resolve(n):F()]),{runtime_config:m}=i,{execution:d,send_sir:f}=m.transaction_costs.action_receipt_creation_config,{execution:_,send_sir:w}=m.transaction_costs.action_creation_config.transfer_cost,T=BigInt(w)+BigInt(_),N=BigInt(f)+BigInt(d),h=T+N,S=t.sweep?k(o):o,A=h*S;return ft.from({chain:x.Near,value:A})}catch(o){throw new u({errorKey:"toolbox_fee_estimation_failed",info:{chain:x.Near,message:O(o)}},o)}}let a=r?await P():void 0;return v(t,a)}async function L(t){let r=await(t||await g()).gasPrice(null);return BigInt(r.gas_price)}async function Ct(t,n,r){if(!await c())throw new u("toolbox_near_no_signer");let o=await P(),{formatNearAmount:i}=await import("@near-js/utils"),{PublicKey:m}=await import("@near-js/crypto"),d=i(r)||"0";return(await o.createAccount(t,m.fromString(n),BigInt(d))).transaction.hash}async function xt(t){let n=await c();try{if(!n)throw new u("toolbox_near_no_signer");let{actionCreators:r}=await import("@near-js/transactions"),{contractId:a,methodName:o,args:i,deposit:m}=t,d=await P(),f=await v({args:i||{},contractId:a,methodName:o}),_=r.functionCall(o,i||{},f.getBaseValue("bigint"),BigInt(m||"1"));return(await d.signAndSendTransaction({actions:[_],receiverId:a})).transaction_outcome.id}catch(r){throw new u("toolbox_near_transfer_failed",{error:r})}}async function Et(t){let n=await P();return lt({account:n,changeMethods:t.changeMethods,contractId:t.contractId,viewMethods:t.viewMethods})}async function vt(t){if(!await c())throw new u("toolbox_near_no_signer");if(t.actions.length===0)throw new u("toolbox_near_empty_batch");return(await(await P()).signAndSendTransaction({actions:t.actions,receiverId:t.receiverId})).transaction.hash}async function v(t,n){let r=await pt(t).when(ot,()=>p.SIMPLE_TRANSFER).when(it,(o)=>dt(o.methodName)).when(st,(o)=>ut(o.actions)).when(ct,()=>p.ACCOUNT_CREATION).when(gt,()=>p.CONTRACT_DEPLOYMENT).when(mt,(o)=>{if(!n)throw new u("toolbox_near_no_account");return o.customEstimator(n)}).otherwise(()=>{throw new u("toolbox_near_invalid_gas_params")}),a=BigInt(r)*BigInt(1000000000000);return ft.from({chain:x.Near,value:a})}function It(t,n){return console.warn("NEAR toolbox: estimateGas is deprecated, use estimateGasLimit instead"),v(t,n)}async function Bt(){let t=await g();try{return(await t.gasPrice(null)).gas_price||"100000000"}catch{return"100000000"}}async function Rt(){let t=await c();return t?(await t.getPublicKey()).toString():""}return{broadcastTransaction:Q,callFunction:xt,createAction:E,createContract:Et,createContractFunctionCall:H,createSubAccount:Ct,createTransaction:Y,estimateGas:It,estimateGasLimit:v,estimateTransactionFee:Z,executeBatchTransaction:vt,getAddress:y,getBalance:wt(x.Near),getGasPrice:Bt,getNearProvider:g,getPublicKey:Rt,getSignerFromPhrase:M,getSignerFromPrivateKey:et,serializeTransaction:At,signAndBroadcastTransaction:X,signTransaction:q,transfer:ht,validateAddress:G}}export{p as GAS_COSTS,lt as createNearContract,ut as estimateBatchGas,Vt as gasToTGas,dt as getContractMethodGas,j as getFullAccessPublicKey,M as getNearSignerFromPhrase,et as getNearSignerFromPrivateKey,Xt as getNearToolbox,ct as isAccountCreation,st as isBatchTransaction,it as isContractCall,gt as isContractDeployment,mt as isCustomEstimator,ot as isSimpleTransfer,Ut as tgasToGas,G as validateNearAddress};
1
+ import{ia as wt}from"../../chunk-xdkdc1f0.js";import{ja as l}from"../../chunk-exyqap7m.js";import{Chain as Rt,derivationPathToString as Kt,SwapKitError as rt}from"@swapkit/helpers";function R(e){return e.length>=2&&e.length<=64&&/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(e)}async function M(e){if(e.derivationPath&&(e.derivationPath[3]||e.derivationPath[4]))throw new rt("toolbox_derivation_slot_unsupported",{chain:Rt.Near,derivationPath:e.derivationPath});let{KeyPair:s}=await import("@near-js/crypto"),c=e.derivationPath?Kt(e.derivationPath.slice(0,3)):`m/44'/397'/${e.index??0}'`,{parseSeedPhrase:g}=await import("near-seed-phrase"),{secretKey:_}=g(e.phrase,c),y=s.fromString(_);return at(y)}async function et(e){let{KeyPair:s}=await import("@near-js/crypto"),c=s.fromString(e);return at(c)}async function at(e){let{KeyPairSigner:s}=await import("@near-js/signers");class c extends s{#t;constructor(g){super(g);this.#t=g}getAddress(){let g=this.#t.getPublicKey(),_=Buffer.from(g.data).toString("hex");return Promise.resolve(_)}}return new c(e)}async function j(e,s){let g=(await e.query({account_id:s,finality:"final",request_type:"view_access_key_list"})).keys.find((K)=>K.access_key.permission==="FullAccess");if(!g)throw new rt("toolbox_near_no_public_key_found");let{PublicKey:_}=await import("@near-js/crypto"),y=_.fromString(g.public_key);return{nonce:g.access_key.nonce||0,publicKey:y}}var p={ACCESS_KEY_ADDITION:"5",ACCESS_KEY_DELETION:"5",ACCOUNT_CREATION:"30",CONTRACT_CALL:"150",CONTRACT_DEPLOYMENT:"200",SIMPLE_TRANSFER:"1",STAKE:"10",STORAGE_DEPOSIT:"150",TOKEN_TRANSFER:"150"};function ot(e){return"recipient"in e&&"amount"in e&&!("contractId"in e)}function it(e){return"contractId"in e&&"methodName"in e}function st(e){return"actions"in e}function ct(e){return"newAccountId"in e}function gt(e){return"contractCode"in e}function mt(e){return"customEstimator"in e}function ut(e){let s=0;for(let c of e)switch(c.enum){case"transfer":s+=Number(p.SIMPLE_TRANSFER);break;case"functionCall":s+=Number(p.CONTRACT_CALL);break;case"createAccount":s+=Number(p.ACCOUNT_CREATION);break;case"deployContract":s+=Number(p.CONTRACT_DEPLOYMENT);break;case"addKey":s+=Number(p.ACCESS_KEY_ADDITION);break;case"deleteKey":s+=Number(p.ACCESS_KEY_DELETION);break;case"stake":s+=Number(p.STAKE);break;default:s+=Number(p.CONTRACT_CALL)}return s.toString()}function dt(e){if(e==="ft_transfer"||e==="ft_transfer_call")return p.TOKEN_TRANSFER;if(e==="storage_deposit")return p.STORAGE_DEPOSIT;return p.CONTRACT_CALL}function jt(e){return(BigInt(e)*BigInt(1000000000000)).toString()}function Ut(e){return(BigInt(e)/BigInt(1000000000000)).toString()}async function lt({account:e,contractId:s,viewMethods:c,changeMethods:g}){let{Contract:_}=await import("@near-js/accounts");return new _(e,s,{changeMethods:g,useLocalViewExecution:!0,viewMethods:c})}import{AssetValue as ft,Chain as x,getRPCUrl as kt,SwapKitError as u}from"@swapkit/helpers";import{match as pt,P as _t}from"ts-pattern";var Pt=1250000000000000000000n,yt=150000000000000n,Gt=150000000000000n,Ft=250000000000000n,Dt=250000000000000n,Ot=500n,U=10000n;function Qt(e){let s;async function c(){if(s)return s;return s=await pt(e).with({phrase:_t.string},async(t)=>await M(t)).with({signer:_t.any},({signer:t})=>t).otherwise(()=>{return}),s}async function g(){let{JsonRpcProvider:t}=await import("@near-js/providers"),n=await kt(x.Near);return new t({url:n})}async function _(t){let{Account:n}=await import("@near-js/accounts"),r=await g(),a=await c(),o=t||await y();return new n(o,r,a)}async function y(){let t=await c();if(!t)throw new u("toolbox_near_no_signer");return await t.getAddress()}async function V(t,n){return(n||await g()).callFunction(t.contractId,"storage_balance_of",{account_id:t.accountId},{finality:"final"})}async function K(t,n){try{let r=await n.callFunction(t,"storage_balance_bounds",{},{finality:"final"});return r?.min?BigInt(r.min):Pt}catch{return Pt}}function k(t){return(t*(U+Ot)+U-1n)/U}function J(t,n){return BigInt(t)*BigInt(n.runtime_config.storage_amount_per_byte)}function z(t,n){if(t<=0n)throw new u({errorKey:"toolbox_sweep_amount_too_low",info:n});return t}async function G(t){return await(t||await g()).experimental_protocolConfig({finality:"final"})}async function Tt(t,n,r){let o=await(r||await g()).callFunction(t,"ft_balance_of",{account_id:n},{finality:"final"});return BigInt(o||"0")}async function ht(t){if(!await c())throw new u("toolbox_near_no_signer");let{assetValue:r,recipient:a,memo:o,sweep:i}=t,m=await y(),d=await Y({assetValue:r,memo:o,recipient:a,sender:m,sweep:i});return X(d)}async function St({assetValue:t,attachedDeposit:n,memo:r,provider:a,recipient:o,sender:i,sweep:m}){let d=t.address;if(!d)throw new u("toolbox_near_missing_contract_address");let f=await V({accountId:o,contractId:d},a),P=f?0n:await K(d,a),w=f?Ft:Gt,T=BigInt(n||"1"),N=t.getBaseValue("bigint");if(m){let[S,A,b,I]=await Promise.all([Tt(d,i,a),a.viewAccount(i,{finality:"final"}),G(a),O(a)]);N=z(S,{asset:t.toString(),balance:S.toString()});let E=J(A.storage_usage,b),C=A.amount-E,B=P,nt=(w+(f?0n:yt))*k(I)+B+T;if(C<nt)throw new u("toolbox_sweep_amount_too_low",{asset:t.toString(),availableNear:C.toString(),reason:"Insufficient NEAR to cover token transfer gas and storage deposit",requiredNear:nt.toString()})}let h=[];if(!f)h.push(await v({args:{account_id:o},attachedDeposit:P.toString(),gas:yt.toString(),methodName:"storage_deposit"}));return h.push(await v({args:{amount:N.toString(),memo:r||null,receiver_id:o},attachedDeposit:T.toString(),gas:w.toString(),methodName:"ft_transfer"})),W({actions:h,receiverId:d,sender:i})}async function Nt({assetValue:t,attachedDeposit:n,memo:r,provider:a,recipient:o,sender:i,sweep:m}){let d=t.getBaseValue("bigint");if(m){let[b,I]=await Promise.all([a.viewAccount(i,{finality:"final"}),G(a)]),E=await Z({assetValue:t,memo:r,recipient:o,sweep:m},I),C=J(b.storage_usage,I),B=0n;if(r&&n){let tt=await O(a);B=Dt*k(tt)+BigInt(n)}d=z(b.amount-E.getBaseValue("bigint")-C-B,{asset:t.toString(),balance:b.amount.toString(),fee:E.getBaseValue("bigint").toString(),storageStakeReserve:C.toString()})}let[{publicKey:f,nonce:P},w,{actionCreators:T,createTransaction:N},{baseDecode:h}]=await Promise.all([j(a,i),a.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),S=[T.transfer(d)];if(r&&n)S.push(T.functionCall("memo",{memo:r},BigInt("250000000000000"),BigInt(n)));let A=h(w.header.hash);return N(i,f,o,P+1,S,A)}async function Y({recipient:t,assetValue:n,memo:r,attachedDeposit:a,sender:o,functionCall:i,sweep:m}){if(!R(t))throw new u("toolbox_near_invalid_address",{recipient:t});if(!R(o))throw new u("toolbox_near_invalid_address",{sender:o});if(i)return H({...i,sender:o});if(m&&!await c())throw new u("toolbox_near_no_signer");let d=await g(),f={assetValue:n,attachedDeposit:a,memo:r,provider:d,recipient:t,sender:o,sweep:m};return n.isGasAsset?Nt(f):St(f)}function At(t){let n=t.encode();return Buffer.from(n).toString("base64")}async function H({args:t,attachedDeposit:n,contractId:r,gas:a,methodName:o,sender:i}){let m=await v({args:t,attachedDeposit:n,gas:a,methodName:o});return W({actions:[m],receiverId:r,sender:i})}async function W({actions:t,receiverId:n,sender:r}){let a=await g(),[{publicKey:o,nonce:i},m,{createTransaction:d},{baseDecode:f}]=await Promise.all([j(a,r),a.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),P=f(m.header.hash);return d(r,o,n,i+1,t,P)}async function v(t){let{actionCreators:n}=await import("@near-js/transactions");return n.functionCall(t.methodName,Buffer.from(JSON.stringify(t.args)),BigInt(t.gas),BigInt(t.attachedDeposit))}async function q(t){let n=await c();if(!n)throw new u("toolbox_near_no_signer");await bt(t);let[r,a]=await n.signTransaction(t);return a}async function bt(t){let n=t.publicKey;if(n.toString?.().startsWith("ed25519:")||n.toString?.().startsWith("secp256k1:"))return;let{KeyType:r,PublicKey:a}=await import("@near-js/crypto"),o=n.data||n.ed25519Key?.data,i=n.secp256k1Key?.data;if(o){t.publicKey=new a({data:Uint8Array.from(o),keyType:r.ED25519});return}if(i)t.publicKey=new a({data:Uint8Array.from(i),keyType:r.SECP256K1})}function F(t){if(typeof t==="string")return t;if(Array.isArray(t))return t.map(F).find(Boolean);if(!(t&&typeof t==="object"))return;let n=t;return n.transaction?.hash||n.transaction_outcome?.id}function D(t){return t instanceof Error?t.message:String(t)}async function Q(t){let r=await(await g()).sendTransaction(t),a=F(r);if(!a)throw new u("toolbox_near_transfer_failed",{result:r});return a}async function X(t){let n=await c();if(!n)throw new u("toolbox_near_no_signer");let r;try{r=await q(t)}catch(a){let o;try{o=n.signAndSendTransaction?await n.signAndSendTransaction({actions:t.actions,receiverId:t.receiverId,signerId:t.signerId}):await n.signAndSendTransactions?.({transactions:[t]})}catch(m){throw new u({errorKey:"toolbox_near_sign_transaction_failed",info:{directSignError:D(a),signAndSendError:D(m)}},m)}let i=F(o);if(i)return i;throw a}return Q(r)}async function Z(t,n){let r=await c();if("assetValue"in t){if(t.sweep&&!r)throw new u("toolbox_near_no_signer");try{let[o,i]=await Promise.all([O(),n?Promise.resolve(n):G()]),{runtime_config:m}=i,{execution:d,send_sir:f}=m.transaction_costs.action_receipt_creation_config,{execution:P,send_sir:w}=m.transaction_costs.action_creation_config.transfer_cost,T=BigInt(w)+BigInt(P),N=BigInt(f)+BigInt(d),h=T+N,S=t.sweep?k(o):o,A=h*S;return ft.from({chain:x.Near,value:A})}catch(o){throw new u({errorKey:"toolbox_fee_estimation_failed",info:{chain:x.Near,message:D(o)}},o)}}let a=r?await _():void 0;return L(t,a)}async function O(t){let r=await(t||await g()).gasPrice(null);return BigInt(r.gas_price)}async function Ct(t,n,r){if(!await c())throw new u("toolbox_near_no_signer");let o=await _(),{formatNearAmount:i}=await import("@near-js/utils"),{PublicKey:m}=await import("@near-js/crypto"),d=i(r)||"0";return(await o.createAccount(t,m.fromString(n),BigInt(d))).transaction.hash}async function xt(t){let n=await c();try{if(!n)throw new u("toolbox_near_no_signer");let{actionCreators:r}=await import("@near-js/transactions"),{contractId:a,methodName:o,args:i,deposit:m}=t,d=await _(),f=await L({args:i||{},contractId:a,methodName:o}),P=r.functionCall(o,i||{},f.getBaseValue("bigint"),BigInt(m||"1"));return(await d.signAndSendTransaction({actions:[P],receiverId:a})).transaction_outcome.id}catch(r){throw new u("toolbox_near_transfer_failed",{error:r})}}async function vt(t){let n=await _();return lt({account:n,changeMethods:t.changeMethods,contractId:t.contractId,viewMethods:t.viewMethods})}async function It(t){if(!await c())throw new u("toolbox_near_no_signer");if(t.actions.length===0)throw new u("toolbox_near_empty_batch");return(await(await _()).signAndSendTransaction({actions:t.actions,receiverId:t.receiverId})).transaction.hash}async function L(t,n){let r=await pt(t).when(ot,()=>p.SIMPLE_TRANSFER).when(it,(o)=>dt(o.methodName)).when(st,(o)=>ut(o.actions)).when(ct,()=>p.ACCOUNT_CREATION).when(gt,()=>p.CONTRACT_DEPLOYMENT).when(mt,(o)=>{if(!n)throw new u("toolbox_near_no_account");return o.customEstimator(n)}).otherwise(()=>{throw new u("toolbox_near_invalid_gas_params")}),a=BigInt(r)*BigInt(1000000000000);return ft.from({chain:x.Near,value:a})}async function Et(){let t=await g();try{return(await t.gasPrice(null)).gas_price||"100000000"}catch{return"100000000"}}async function Bt(){let t=await c();return t?(await t.getPublicKey()).toString():""}return{broadcastTransaction:Q,callFunction:xt,createAction:v,createContract:vt,createContractFunctionCall:H,createSubAccount:Ct,createTransaction:Y,estimateGasLimit:L,estimateTransactionFee:Z,executeBatchTransaction:It,getAddress:y,getBalance:wt(x.Near),getGasPrice:Et,getNearProvider:g,getPublicKey:Bt,getSignerFromPhrase:M,getSignerFromPrivateKey:et,serializeTransaction:At,signAndBroadcastTransaction:X,signTransaction:q,transfer:ht,validateAddress:R}}export{p as GAS_COSTS,lt as createNearContract,ut as estimateBatchGas,Ut as gasToTGas,dt as getContractMethodGas,j as getFullAccessPublicKey,M as getNearSignerFromPhrase,et as getNearSignerFromPrivateKey,Qt as getNearToolbox,ct as isAccountCreation,st as isBatchTransaction,it as isContractCall,gt as isContractDeployment,mt as isCustomEstimator,ot as isSimpleTransfer,jt as tgasToGas,R as validateNearAddress};
@@ -1 +1 @@
1
- import{ha as p}from"../../chunk-4428244x.js";import{AssetValue as y,Chain as g,SKConfig as f,SwapKitError as b}from"@swapkit/helpers";function R(s){return s.startsWith("account_rdx1")&&s.length===66}async function w({address:s,networkApi:i}){let a=!0,c,o=[],e=await A(i);while(a){let r={address:s,at_ledger_state:{state_version:e},cursor:c,limit_per_page:100},n=await i.state.innerClient.entityFungiblesPage({stateEntityFungiblesPageRequest:r});if(o=o.concat(n.items),n.next_cursor)c=n.next_cursor;else a=!1}return o}async function x({resources:s,networkApi:i}){let a=[],c=50,o=[];for(let e=0;e<s.length;e+=50)o.push(s.slice(e,e+50));for(let e of o){let r=e.map((t)=>t.resource_address),n=await i.state.getEntityDetailsVaultAggregated(r),u=new Map;for(let t of n)if(t.details!==void 0){let l=t.metadata?.items.find((m)=>m.key==="symbol"),d=l?.value.typed.type==="String"?l.value.typed.value:"?";if(t.details.type==="FungibleResource")u.set(t.address,{decimals:t.details.divisibility,symbol:d})}for(let t of e)if(t.aggregation_level==="Global"){let l=u.get(t.resource_address)||{decimals:0,symbol:"?"},d=y.from({asset:l.symbol!==g.Radix?`${g.Radix}.${l.symbol}-${t.resource_address}`:"XRD.XRD",value:t.amount});a.push(d)}}return a}async function A(s){return(await s.status.getCurrent()).ledger_state.state_version}function _({dappConfig:s}={}){let i=s||f.get("integrations").radix,a;async function c(){if(a)return a;let{GatewayApiClient:e}=await import("@radixdlt/babylon-gateway-api-sdk"),{RadixDappToolkit:r}=await import("@radixdlt/radix-dapp-toolkit"),n=r({...i,networkId:i.network?.networkId||1});return a=e.initialize(n.gatewayApi.clientConfig),a}async function o(e){let r=await c(),n=await w({address:e,networkApi:r}),u=await x({networkApi:r,resources:n});if(!u.some((l)=>l.isGasAsset))return[y.from({chain:g.Radix}),...u];return u}return{getAddress:()=>"",getBalance:o,getNetworkApi:c,signAndBroadcast:()=>{throw new b("toolbox_radix_method_not_supported",{method:"signAndBroadcast"})},validateAddress:R}}export{_ as getRadixToolbox,R as validateRadixAddress};
1
+ import{ja as p}from"../../chunk-exyqap7m.js";import{AssetValue as y,Chain as g,SKConfig as f,SwapKitError as b}from"@swapkit/helpers";function R(s){return s.startsWith("account_rdx1")&&s.length===66}async function w({address:s,networkApi:i}){let a=!0,c,o=[],e=await A(i);while(a){let r={address:s,at_ledger_state:{state_version:e},cursor:c,limit_per_page:100},n=await i.state.innerClient.entityFungiblesPage({stateEntityFungiblesPageRequest:r});if(o=o.concat(n.items),n.next_cursor)c=n.next_cursor;else a=!1}return o}async function x({resources:s,networkApi:i}){let a=[],c=50,o=[];for(let e=0;e<s.length;e+=50)o.push(s.slice(e,e+50));for(let e of o){let r=e.map((t)=>t.resource_address),n=await i.state.getEntityDetailsVaultAggregated(r),u=new Map;for(let t of n)if(t.details!==void 0){let l=t.metadata?.items.find((m)=>m.key==="symbol"),d=l?.value.typed.type==="String"?l.value.typed.value:"?";if(t.details.type==="FungibleResource")u.set(t.address,{decimals:t.details.divisibility,symbol:d})}for(let t of e)if(t.aggregation_level==="Global"){let l=u.get(t.resource_address)||{decimals:0,symbol:"?"},d=y.from({asset:l.symbol!==g.Radix?`${g.Radix}.${l.symbol}-${t.resource_address}`:"XRD.XRD",value:t.amount});a.push(d)}}return a}async function A(s){return(await s.status.getCurrent()).ledger_state.state_version}function _({dappConfig:s}={}){let i=s||f.get("integrations").radix,a;async function c(){if(a)return a;let{GatewayApiClient:e}=await import("@radixdlt/babylon-gateway-api-sdk"),{RadixDappToolkit:r}=await import("@radixdlt/radix-dapp-toolkit"),n=r({...i,networkId:i.network?.networkId||1});return a=e.initialize(n.gatewayApi.clientConfig),a}async function o(e){let r=await c(),n=await w({address:e,networkApi:r}),u=await x({networkApi:r,resources:n});if(!u.some((l)=>l.isGasAsset))return[y.from({chain:g.Radix}),...u];return u}return{getAddress:()=>"",getBalance:o,getNetworkApi:c,signAndBroadcast:()=>{throw new b("toolbox_radix_method_not_supported",{method:"signAndBroadcast"})},validateAddress:R}}export{_ as getRadixToolbox,R as validateRadixAddress};