@swapkit/toolboxes 5.2.1 → 5.3.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.
@@ -1 +1 @@
1
- import"../../chunk-xbdjxeqd.js";import{base64 as o,bech32 as i}from"@scure/base";import{SwapKitError as L0}from"@swapkit/helpers";function t(Y){return o.encode(Uint8Array.from(i.fromWords(i.decode(Y).words)))}function r(Y,z="thor"){return i.encode(z,i.toWords(o.decode(Y)))}function P8(Y){return o.encode(Y)}function A8(Y){if(!Y.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new L0("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return o.decode(Y)}import{encodeMessage as f0,encodeTxBody as w0}from"@swapkit/cosmos-signer";import{AssetValue as j0,Chain as Z6,getChainConfig as h6,getRPCUrl as N6,SwapKitError as B6}from"@swapkit/helpers";import{base64 as G6}from"@scure/base";import{broadcastTx as a,getAccount as P6,getBalances as J0,createTendermintRpc as G0,defaultEncoders as q0,encodeAuthInfo as F6,encodeMessage as _0,encodePubkey as W0,encodeTxBody as O0,encodeTxRaw as v6,makeStdSignDoc as N0}from"@swapkit/cosmos-signer";import{AssetValue as q6,Chain as K,getChainConfig as S,getRPCUrl as B0,RequestClient as I0,SKConfig as D6,SwapKitError as D,SwapKitNumber as _6}from"@swapkit/helpers";var A6="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",E0="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",U0={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},K0={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},R0={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function C(Y){switch(Y){case K.Maya:return{amount:[],gas:"10000000000"};case K.THORChain:return{amount:[],gas:"500000000"};case K.Kujira:return K0;case K.Noble:return R0;default:return U0}}async function s(Y){let{isStagenet:z}=D6.get("envs"),H=D6.get("thornodeUrls"),Z=Y===K.Maya,X=`${Z?z?H.MAYA_STAGENET:H.MAYA:z?H.THOR_STAGENET:H.THOR}/${Z?"mayachain":"thorchain"}/constants`,L=S(Y).baseDecimal;try{let{int_64_values:{NativeTransactionFee:J}}=await I0.get(X);if(!Number.isInteger(J)||J<=0)throw new D("toolbox_cosmos_invalid_fee",{nativeFee:J.toString()});return _6.fromBigInt(BigInt(J),L)}catch{let J=Z?10000000000n:2000000n;return _6.fromBigInt(J,L)}}var y=(Y,z=!1)=>{if(z)return Y.toLowerCase();switch(Y){case"uUSK":case"USK":return A6;case"uYUM":case"YUM":return E0;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return Y}},e=({symbol:Y,chain:z})=>{if(z===K.Maya)return(Y.toUpperCase()!=="CACAO"?Y:`${K.Maya}.${Y}`).toUpperCase();if(z===K.THORChain)return(["RUNE","TCY","RUJI"].includes(Y.toUpperCase())?`${K.THORChain}.${Y}`:Y).toUpperCase();return y(Y,!1)},V0=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function S6(Y){return G0(Y,{headers:V0()})}function C6(Y){return{amount:Y.amount,denom:Y.denom}}function M0(Y,z){if(!Y)return null;if("toAmino"in Y&&typeof Y.toAmino==="function")return null;let Z=Y[z];return Z?{aminoType:Z.aminoType,toAmino:Z.toAmino}:null}async function $(Y){let z=S6(Y);return{async broadcastTx(H){let Z=await a(z,H,"sync");if(Z.code!==0)throw new D("core_swap_transaction_error",{code:Z.code,message:Z.log});return{code:Z.code,rawLog:Z.log,transactionHash:Z.hash}},async getAccount(H){let Z=await P6(z,H);if(!Z)return null;return{accountNumber:Number(Z.accountNumber),address:Z.address,pubkey:Z.pubKey?{type:Z.pubKey.typeUrl,value:Z.pubKey.key}:null,sequence:Number(Z.sequence)}},async getAllBalances(H){return(await J0(z,H)).map((Q)=>({amount:Q.amount,denom:Q.denom}))}}}function $6(Y,z={}){let H=T0(Y);async function Z(Q,X,L,J,G){let U=(await Y.getAccounts()).find((E)=>E.address===Q);if(!U)throw new D("toolbox_cosmos_signer_not_defined");let V=D0({memo:J,messages:X,registry:z.registry}),T=W0({type:"tendermint/PubKeySecp256k1",value:G6.encode(U.pubkey)});if(H){let E=X.map((v)=>v0(v,z.aminoTypes)),R=N0({accountNumber:G.accountNumber,chainId:G.chainId,fee:x0(L),memo:J,msgs:E,sequence:G.sequence}),M=await Y.signAmino(Q,R),x=F6({fee:F0(M.signed.fee,L),signerInfos:[{mode:"amino",pubkey:T,sequence:BigInt(M.signed.sequence)}]}),A=G6.decode(M.signature.signature);return{authInfoBytes:x,bodyBytes:V,signatures:[A]}}let N=F6({fee:k0(L),signerInfos:[{mode:"direct",pubkey:T,sequence:BigInt(G.sequence)}]}),I=await Y.signDirect(Q,{accountNumber:G.accountNumber,authInfoBytes:N,bodyBytes:V,chainId:G.chainId}),W=G6.decode(I.signature.signature);return{authInfoBytes:N,bodyBytes:V,signatures:[W]}}return{signWithRegistry:Z}}function T0(Y){return typeof Y.signAmino==="function"}function x0(Y){return{amount:Y.amount.map((z)=>({amount:z.amount,denom:z.denom})),gas:Y.gas,...Y.granter?{granter:Y.granter}:{},...Y.payer?{payer:Y.payer}:{}}}function k0(Y){return{amount:Y.amount.map(C6),gasLimit:BigInt(Y.gas),...Y.granter?{granter:Y.granter}:{},...Y.payer?{payer:Y.payer}:{}}}function F0(Y,z){return{amount:Y.amount.map(C6),gasLimit:BigInt(Y.gas),...Y.granter??z.granter?{granter:Y.granter??z.granter}:{},...Y.payer??z.payer?{payer:Y.payer??z.payer}:{}}}function v0(Y,z){if(z&&"toAmino"in z&&typeof z.toAmino==="function")return z.toAmino(Y);let H=M0(z,Y.typeUrl);if(!H){if(Y.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let Z=Y.value;return{type:"cosmos-sdk/MsgSend",value:{amount:Z.amount,from_address:Z.fromAddress,to_address:Z.toAddress}}}throw new D("toolbox_cosmos_invalid_params",{error:`No amino converter for ${Y.typeUrl}`})}return{type:H.aminoType,value:H.toAmino(Y.value)}}function D0(Y){let{memo:z,messages:H,registry:Z}=Y;if(Z&&"encode"in Z&&typeof Z.encode==="function")return Z.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:z,messages:H}});let Q={...q0,...Z??{}},X=H.map((L)=>_0(L,Q));return O0({memo:z,messages:X})}async function p(Y,z,H={}){let Z=typeof H==="string"?{}:H,Q=S6(Y),X=$6(z,Z);async function L(J,G){let B=await P6(Q,J);if(!B)throw new D("toolbox_cosmos_account_not_found",{sender:J});let U=G?.chainId??(await Q.status()).chainId;return{accountNumber:G?.accountNumber??B.accountNumber,chainId:U,sequence:G?.sequence??B.sequence}}return{async broadcastTx(J){let G=await a(Q,J,"sync");if(G.code!==0)throw new D("core_swap_transaction_error",{code:G.code,message:G.log});return{code:G.code,rawLog:G.log,transactionHash:G.hash}},async sendTokens(J,G,B,U,V=""){let T=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:B.map((R)=>({amount:R.amount,denom:R.denom})),fromAddress:J,toAddress:G}}],N=await L(J),I=await X.signWithRegistry(J,T,U,V,N),W=v6({authInfoBytes:I.authInfoBytes,bodyBytes:I.bodyBytes,signatures:I.signatures}),E=await a(Q,W,"sync");if(E.code!==0)throw new D("core_swap_transaction_error",{code:E.code,message:E.log});return{code:E.code,rawLog:E.log,transactionHash:E.hash}},async sign(J,G,B,U,V){let T=V??await L(J);return X.signWithRegistry(J,G,B,U,T)},async signAndBroadcast(J,G,B,U=""){let V=await L(J),T=await X.signWithRegistry(J,G,B,U,V),N=v6({authInfoBytes:T.authInfoBytes,bodyBytes:T.bodyBytes,signatures:T.signatures}),I=await a(Q,N,"sync");return{code:I.code,rawLog:I.log,transactionHash:I.hash}}}}async function y6(Y,z){let H=$6(Y,z??{});return{sign(Z,Q,X,L,J){if(!J)throw new D("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return H.signWithRegistry(Z,Q,X,L,J)}}}var P0=(Y)=>{switch(Y){case K.Maya:case K.THORChain:return"/types.MsgSend";case K.Cosmos:case K.Kujira:case K.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new D("toolbox_cosmos_not_supported",{chain:Y})}};async function A0({client:Y,sender:z}){let H=await Y.getAccount(z);if(!H)throw new D("toolbox_cosmos_account_not_found",{sender:z});return H}async function f6({sender:Y,recipient:z,assetValue:H,memo:Z="",feeRate:Q,sequence:X,accountNumber:L,sweep:J}){let{chain:G,chainId:B}=H,U=L===void 0||X===void 0,V=J||U?await $(await B0(G)):void 0,T=U&&V?await A0({client:V,sender:Y}):void 0,N=q6.from({chain:G}),I=y(N.symbol),W=C(G),E=I&&Q?{amount:[{amount:Q.toString(),denom:I}],gas:W.gas}:W,R=y(H.symbol),M=H;if(J){if(!V)throw new D("toolbox_cosmos_account_not_found",{sender:Y});M=m({assetValue:H,balances:await V.getAllBalances(Y),denom:R,feeAmount:W6(E.amount,R)})}let x={amount:[{amount:M.getBaseValue("string"),denom:R}],fromAddress:Y,toAddress:z};return{accountNumber:L??Number(T?.accountNumber),chainId:B,fee:E,memo:Z,msgs:[{typeUrl:P0(G),value:x}],sequence:X??Number(T?.sequence)}}function W6(Y,z){let H=z.toLowerCase();return Y.reduce((Z,Q)=>Q.denom.toLowerCase()===H?Z+BigInt(Q.amount):Z,0n)}function m({assetValue:Y,balances:z,denom:H,feeAmount:Z=0n}){let Q=H.toLowerCase(),X=z.find(({denom:G})=>G.toLowerCase()===Q),L=BigInt(X?.amount??"0"),J=L-Z;if(J<=0n)throw new D("toolbox_sweep_amount_too_low",{asset:Y.toString(),balance:L.toString(),fee:Z.toString()});return Y.set(_6.fromBigInt(J,Y.decimal))}var S0={atom:{chain:K.Cosmos,decimals:S(K.Cosmos).baseDecimal},cacao:{chain:K.Maya,decimals:10},kuji:{chain:K.Kujira,decimals:S(K.Kujira).baseDecimal},maya:{asset:`${K.Maya}.${K.Maya}`,decimals:4},rune:{chain:K.THORChain,decimals:S(K.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:S(K.THORChain).baseDecimal},uatom:{chain:K.Cosmos,decimals:S(K.Cosmos).baseDecimal},ukuji:{chain:K.Kujira,decimals:S(K.Kujira).baseDecimal},usdc:{chain:K.Noble,decimals:S(K.Noble).baseDecimal},uusdc:{chain:K.Noble,decimals:S(K.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:S(K.THORChain).baseDecimal},[A6.toLowerCase()]:{asset:`${K.Kujira}.USK`,decimals:S(K.Kujira).baseDecimal}},w6=(Y,z)=>{let H=S0[Y.toLowerCase()];if(!H)return q6.from({asset:Y,fromBaseDecimal:8,value:z});let{chain:Z,asset:Q,decimals:X}=H,L=Z?{chain:Z}:{asset:Q};return q6.from({...L,fromBaseDecimal:X,value:z})};import{defaultEncoders as C0}from"@swapkit/cosmos-signer";import{Chain as j6}from"@swapkit/helpers";import k from"protobufjs/minimal.js";var O=k.Reader,P=k.Writer,_=k.util,q=k.roots.default||(k.roots.default={});q.common=(()=>{let Y={};return Y.Asset=(()=>{function z(H){if(H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.chain="",z.prototype.symbol="",z.prototype.ticker="",z.prototype.synth=!1,z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.chain!=null&&Object.hasOwnProperty.call(Z,"chain"))Q.uint32(10).string(Z.chain);if(Z.symbol!=null&&Object.hasOwnProperty.call(Z,"symbol"))Q.uint32(18).string(Z.symbol);if(Z.ticker!=null&&Object.hasOwnProperty.call(Z,"ticker"))Q.uint32(26).string(Z.ticker);if(Z.synth!=null&&Object.hasOwnProperty.call(Z,"synth"))Q.uint32(32).bool(Z.synth);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.Asset;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.chain=Z.string();break;case 2:L.symbol=Z.string();break;case 3:L.ticker=Z.string();break;case 4:L.synth=Z.bool();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.chain!=null&&Z.hasOwnProperty("chain")){if(!_.isString(Z.chain))return"chain: string expected"}if(Z.symbol!=null&&Z.hasOwnProperty("symbol")){if(!_.isString(Z.symbol))return"symbol: string expected"}if(Z.ticker!=null&&Z.hasOwnProperty("ticker")){if(!_.isString(Z.ticker))return"ticker: string expected"}if(Z.synth!=null&&Z.hasOwnProperty("synth")){if(typeof Z.synth!=="boolean")return"synth: boolean expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.Asset)return Z;let Q=new q.common.Asset;if(Z.chain!=null)Q.chain=String(Z.chain);if(Z.symbol!=null)Q.symbol=String(Z.symbol);if(Z.ticker!=null)Q.ticker=String(Z.ticker);if(Z.synth!=null)Q.synth=Boolean(Z.synth);return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.defaults)X.chain="",X.symbol="",X.ticker="",X.synth=!1;if(Z.chain!=null&&Z.hasOwnProperty("chain"))X.chain=Z.chain;if(Z.symbol!=null&&Z.hasOwnProperty("symbol"))X.symbol=Z.symbol;if(Z.ticker!=null&&Z.hasOwnProperty("ticker"))X.ticker=Z.ticker;if(Z.synth!=null&&Z.hasOwnProperty("synth"))X.synth=Z.synth;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.Coin=(()=>{function z(H){if(H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.asset=null,z.prototype.amount="",z.prototype.decimals=_.Long?_.Long.fromBits(0,0,!1):0,z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.asset!=null&&Object.hasOwnProperty.call(Z,"asset"))q.common.Asset.encode(Z.asset,Q.uint32(10).fork()).ldelim();if(Z.amount!=null&&Object.hasOwnProperty.call(Z,"amount"))Q.uint32(18).string(Z.amount);if(Z.decimals!=null&&Object.hasOwnProperty.call(Z,"decimals"))Q.uint32(24).int64(Z.decimals);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.Coin;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.asset=q.common.Asset.decode(Z,Z.uint32());break;case 2:L.amount=Z.string();break;case 3:L.decimals=Z.int64();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.asset!=null&&Z.hasOwnProperty("asset")){let Q=q.common.Asset.verify(Z.asset);if(Q)return"asset."+Q}if(Z.amount!=null&&Z.hasOwnProperty("amount")){if(!_.isString(Z.amount))return"amount: string expected"}if(Z.decimals!=null&&Z.hasOwnProperty("decimals")){if(!_.isInteger(Z.decimals)&&!(Z.decimals&&_.isInteger(Z.decimals.low)&&_.isInteger(Z.decimals.high)))return"decimals: integer|Long expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.Coin)return Z;let Q=new q.common.Coin;if(Z.asset!=null){if(typeof Z.asset!=="object")throw TypeError(".common.Coin.asset: object expected");Q.asset=q.common.Asset.fromObject(Z.asset)}if(Z.amount!=null)Q.amount=String(Z.amount);if(Z.decimals!=null){if(_.Long)(Q.decimals=_.Long.fromValue(Z.decimals)).unsigned=!1;else if(typeof Z.decimals==="string")Q.decimals=Number.parseInt(Z.decimals,10);else if(typeof Z.decimals==="number")Q.decimals=Z.decimals;else if(typeof Z.decimals==="object")Q.decimals=new _.LongBits(Z.decimals.low>>>0,Z.decimals.high>>>0).toNumber()}return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.defaults)if(X.asset=null,X.amount="",_.Long){let L=new _.Long(0,0,!1);X.decimals=Q.longs===String?L.toString():Q.longs===Number?L.toNumber():L}else X.decimals=Q.longs===String?"0":0;if(Z.asset!=null&&Z.hasOwnProperty("asset"))X.asset=q.common.Asset.toObject(Z.asset,Q);if(Z.amount!=null&&Z.hasOwnProperty("amount"))X.amount=Z.amount;if(Z.decimals!=null&&Z.hasOwnProperty("decimals"))if(typeof Z.decimals==="number")X.decimals=Q.longs===String?String(Z.decimals):Z.decimals;else X.decimals=Q.longs===String?_.Long.prototype.toString.call(Z.decimals):Q.longs===Number?new _.LongBits(Z.decimals.low>>>0,Z.decimals.high>>>0).toNumber():Z.decimals;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.PubKeySet=(()=>{function z(H){if(H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.secp256k1="",z.prototype.ed25519="",z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.secp256k1!=null&&Object.hasOwnProperty.call(Z,"secp256k1"))Q.uint32(10).string(Z.secp256k1);if(Z.ed25519!=null&&Object.hasOwnProperty.call(Z,"ed25519"))Q.uint32(18).string(Z.ed25519);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.PubKeySet;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.secp256k1=Z.string();break;case 2:L.ed25519=Z.string();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.secp256k1!=null&&Z.hasOwnProperty("secp256k1")){if(!_.isString(Z.secp256k1))return"secp256k1: string expected"}if(Z.ed25519!=null&&Z.hasOwnProperty("ed25519")){if(!_.isString(Z.ed25519))return"ed25519: string expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.PubKeySet)return Z;let Q=new q.common.PubKeySet;if(Z.secp256k1!=null)Q.secp256k1=String(Z.secp256k1);if(Z.ed25519!=null)Q.ed25519=String(Z.ed25519);return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.defaults)X.secp256k1="",X.ed25519="";if(Z.secp256k1!=null&&Z.hasOwnProperty("secp256k1"))X.secp256k1=Z.secp256k1;if(Z.ed25519!=null&&Z.hasOwnProperty("ed25519"))X.ed25519=Z.ed25519;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.Tx=(()=>{function z(H){if(this.coins=[],this.gas=[],H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.id="",z.prototype.chain="",z.prototype.fromAddress="",z.prototype.toAddress="",z.prototype.coins=_.emptyArray,z.prototype.gas=_.emptyArray,z.prototype.memo="",z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.id!=null&&Object.hasOwnProperty.call(Z,"id"))Q.uint32(10).string(Z.id);if(Z.chain!=null&&Object.hasOwnProperty.call(Z,"chain"))Q.uint32(18).string(Z.chain);if(Z.fromAddress!=null&&Object.hasOwnProperty.call(Z,"fromAddress"))Q.uint32(26).string(Z.fromAddress);if(Z.toAddress!=null&&Object.hasOwnProperty.call(Z,"toAddress"))Q.uint32(34).string(Z.toAddress);if(Z.coins?.length)for(let X=0;X<Z.coins.length;++X)q.common.Coin.encode(Z.coins[X],Q.uint32(42).fork()).ldelim();if(Z.gas?.length)for(let X=0;X<Z.gas.length;++X)q.common.Coin.encode(Z.gas[X],Q.uint32(50).fork()).ldelim();if(Z.memo!=null&&Object.hasOwnProperty.call(Z,"memo"))Q.uint32(58).string(Z.memo);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.Tx;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.id=Z.string();break;case 2:L.chain=Z.string();break;case 3:L.fromAddress=Z.string();break;case 4:L.toAddress=Z.string();break;case 5:if(!L.coins?.length)L.coins=[];L.coins.push(q.common.Coin.decode(Z,Z.uint32()));break;case 6:if(!L.gas?.length)L.gas=[];L.gas.push(q.common.Coin.decode(Z,Z.uint32()));break;case 7:L.memo=Z.string();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.id!=null&&Z.hasOwnProperty("id")){if(!_.isString(Z.id))return"id: string expected"}if(Z.chain!=null&&Z.hasOwnProperty("chain")){if(!_.isString(Z.chain))return"chain: string expected"}if(Z.fromAddress!=null&&Z.hasOwnProperty("fromAddress")){if(!_.isString(Z.fromAddress))return"fromAddress: string expected"}if(Z.toAddress!=null&&Z.hasOwnProperty("toAddress")){if(!_.isString(Z.toAddress))return"toAddress: string expected"}if(Z.coins!=null&&Z.hasOwnProperty("coins")){if(!Array.isArray(Z.coins))return"coins: array expected";for(let Q=0;Q<Z.coins.length;++Q){let X=q.common.Coin.verify(Z.coins[Q]);if(X)return"coins."+X}}if(Z.gas!=null&&Z.hasOwnProperty("gas")){if(!Array.isArray(Z.gas))return"gas: array expected";for(let Q=0;Q<Z.gas.length;++Q){let X=q.common.Coin.verify(Z.gas[Q]);if(X)return"gas."+X}}if(Z.memo!=null&&Z.hasOwnProperty("memo")){if(!_.isString(Z.memo))return"memo: string expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.Tx)return Z;let Q=new q.common.Tx;if(Z.id!=null)Q.id=String(Z.id);if(Z.chain!=null)Q.chain=String(Z.chain);if(Z.fromAddress!=null)Q.fromAddress=String(Z.fromAddress);if(Z.toAddress!=null)Q.toAddress=String(Z.toAddress);if(Z.coins){if(!Array.isArray(Z.coins))throw TypeError(".common.Tx.coins: array expected");Q.coins=[];for(let X=0;X<Z.coins.length;++X){if(typeof Z.coins[X]!=="object")throw TypeError(".common.Tx.coins: object expected");Q.coins[X]=q.common.Coin.fromObject(Z.coins[X])}}if(Z.gas){if(!Array.isArray(Z.gas))throw TypeError(".common.Tx.gas: array expected");Q.gas=[];for(let X=0;X<Z.gas.length;++X){if(typeof Z.gas[X]!=="object")throw TypeError(".common.Tx.gas: object expected");Q.gas[X]=q.common.Coin.fromObject(Z.gas[X])}}if(Z.memo!=null)Q.memo=String(Z.memo);return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.arrays||Q.defaults)X.coins=[],X.gas=[];if(Q.defaults)X.id="",X.chain="",X.fromAddress="",X.toAddress="",X.memo="";if(Z.id!=null&&Z.hasOwnProperty("id"))X.id=Z.id;if(Z.chain!=null&&Z.hasOwnProperty("chain"))X.chain=Z.chain;if(Z.fromAddress!=null&&Z.hasOwnProperty("fromAddress"))X.fromAddress=Z.fromAddress;if(Z.toAddress!=null&&Z.hasOwnProperty("toAddress"))X.toAddress=Z.toAddress;if(Z.coins?.length){X.coins=[];for(let L=0;L<Z.coins.length;++L)X.coins[L]=q.common.Coin.toObject(Z.coins[L],Q)}if(Z.gas?.length){X.gas=[];for(let L=0;L<Z.gas.length;++L)X.gas[L]=q.common.Coin.toObject(Z.gas[L],Q)}if(Z.memo!=null&&Z.hasOwnProperty("memo"))X.memo=Z.memo;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.Fee=(()=>{function z(H){if(this.coins=[],H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.coins=_.emptyArray,z.prototype.poolDeduct="",z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.coins?.length)for(let X=0;X<Z.coins.length;++X)q.common.Coin.encode(Z.coins[X],Q.uint32(10).fork()).ldelim();if(Z.poolDeduct!=null&&Object.hasOwnProperty.call(Z,"poolDeduct"))Q.uint32(18).string(Z.poolDeduct);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.Fee;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:if(!L.coins?.length)L.coins=[];L.coins.push(q.common.Coin.decode(Z,Z.uint32()));break;case 2:L.poolDeduct=Z.string();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.coins!=null&&Z.hasOwnProperty("coins")){if(!Array.isArray(Z.coins))return"coins: array expected";for(let Q=0;Q<Z.coins.length;++Q){let X=q.common.Coin.verify(Z.coins[Q]);if(X)return"coins."+X}}if(Z.poolDeduct!=null&&Z.hasOwnProperty("poolDeduct")){if(!_.isString(Z.poolDeduct))return"poolDeduct: string expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.Fee)return Z;let Q=new q.common.Fee;if(Z.coins){if(!Array.isArray(Z.coins))throw TypeError(".common.Fee.coins: array expected");Q.coins=[];for(let X=0;X<Z.coins.length;++X){if(typeof Z.coins[X]!=="object")throw TypeError(".common.Fee.coins: object expected");Q.coins[X]=q.common.Coin.fromObject(Z.coins[X])}}if(Z.poolDeduct!=null)Q.poolDeduct=String(Z.poolDeduct);return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.arrays||Q.defaults)X.coins=[];if(Q.defaults)X.poolDeduct="";if(Z.coins?.length){X.coins=[];for(let L=0;L<Z.coins.length;++L)X.coins[L]=q.common.Coin.toObject(Z.coins[L],Q)}if(Z.poolDeduct!=null&&Z.hasOwnProperty("poolDeduct"))X.poolDeduct=Z.poolDeduct;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.ProtoUint=(()=>{function z(H){if(H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.value="",z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.value!=null&&Object.hasOwnProperty.call(Z,"value"))Q.uint32(10).string(Z.value);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.common.ProtoUint;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.value=Z.string();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.value!=null&&Z.hasOwnProperty("value")){if(!_.isString(Z.value))return"value: string expected"}return null},z.fromObject=function(Z){if(Z instanceof q.common.ProtoUint)return Z;let Q=new q.common.ProtoUint;if(Z.value!=null)Q.value=String(Z.value);return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.defaults)X.value="";if(Z.value!=null&&Z.hasOwnProperty("value"))X.value=Z.value;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y})();q.types=(()=>{let Y={};return Y.MsgDeposit=(()=>{function z(H){if(this.coins=[],H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.coins=_.emptyArray,z.prototype.memo="",z.prototype.signer=_.newBuffer([]),z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.coins?.length)for(let X=0;X<Z.coins.length;++X)q.common.Coin.encode(Z.coins[X],Q.uint32(10).fork()).ldelim();if(Z.memo!=null&&Object.hasOwnProperty.call(Z,"memo"))Q.uint32(18).string(Z.memo);if(Z.signer!=null&&Object.hasOwnProperty.call(Z,"signer"))Q.uint32(26).bytes(Z.signer);return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.types.MsgDeposit;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:if(!L.coins?.length)L.coins=[];L.coins.push(q.common.Coin.decode(Z,Z.uint32()));break;case 2:L.memo=Z.string();break;case 3:L.signer=Z.bytes();break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.coins!=null&&Z.hasOwnProperty("coins")){if(!Array.isArray(Z.coins))return"coins: array expected";for(let Q=0;Q<Z.coins.length;++Q){let X=q.common.Coin.verify(Z.coins[Q]);if(X)return"coins."+X}}if(Z.memo!=null&&Z.hasOwnProperty("memo")){if(!_.isString(Z.memo))return"memo: string expected"}if(Z.signer!=null&&Z.hasOwnProperty("signer")){if(!(Z.signer&&typeof Z.signer.length==="number"||_.isString(Z.signer)))return"signer: buffer expected"}return null},z.fromObject=function(Z){if(Z instanceof q.types.MsgDeposit)return Z;let Q=new q.types.MsgDeposit;if(Z.coins){if(!Array.isArray(Z.coins))throw TypeError(".types.MsgDeposit.coins: array expected");Q.coins=[];for(let X=0;X<Z.coins.length;++X){if(typeof Z.coins[X]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");Q.coins[X]=q.common.Coin.fromObject(Z.coins[X])}}if(Z.memo!=null)Q.memo=String(Z.memo);if(Z.signer!=null){if(typeof Z.signer==="string")_.base64.decode(Z.signer,Q.signer=_.newBuffer(_.base64.length(Z.signer)),0);else if(Z.signer.length)Q.signer=Z.signer}return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.arrays||Q.defaults)X.coins=[];if(Q.defaults){if(X.memo="",Q.bytes===String)X.signer="";else if(X.signer=[],Q.bytes!==Array)X.signer=_.newBuffer(X.signer)}if(Z.coins?.length){X.coins=[];for(let L=0;L<Z.coins.length;++L)X.coins[L]=q.common.Coin.toObject(Z.coins[L],Q)}if(Z.memo!=null&&Z.hasOwnProperty("memo"))X.memo=Z.memo;if(Z.signer!=null&&Z.hasOwnProperty("signer"))X.signer=Q.bytes===String?_.base64.encode(Z.signer,0,Z.signer.length):Q.bytes===Array?Array.prototype.slice.call(Z.signer):Z.signer;return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y.MsgSend=(()=>{function z(H){if(this.amount=[],H){for(let Z=Object.keys(H),Q=0;Q<Z.length;++Q)if(H[Z[Q]]!=null)this[Z[Q]]=H[Z[Q]]}}return z.prototype.fromAddress=_.newBuffer([]),z.prototype.toAddress=_.newBuffer([]),z.prototype.amount=_.emptyArray,z.create=function(Z){return new z(Z)},z.encode=function(Z,Q){if(!Q)Q=P.create();if(Z.fromAddress!=null&&Object.hasOwnProperty.call(Z,"fromAddress"))Q.uint32(10).bytes(Z.fromAddress);if(Z.toAddress!=null&&Object.hasOwnProperty.call(Z,"toAddress"))Q.uint32(18).bytes(Z.toAddress);if(Z.amount?.length)for(let X=0;X<Z.amount.length;++X)q.cosmos.base.v1beta1.Coin.encode(Z.amount[X],Q.uint32(26).fork()).ldelim();return Q},z.encodeDelimited=function(Z,Q){return this.encode(Z,Q).ldelim()},z.decode=function(Z,Q){if(!(Z instanceof O))Z=O.create(Z);let X=Q===void 0?Z.len:Z.pos+Q,L=new q.types.MsgSend;while(Z.pos<X){let J=Z.uint32();switch(J>>>3){case 1:L.fromAddress=Z.bytes();break;case 2:L.toAddress=Z.bytes();break;case 3:if(!L.amount?.length)L.amount=[];L.amount.push(q.cosmos.base.v1beta1.Coin.decode(Z,Z.uint32()));break;default:Z.skipType(J&7);break}}return L},z.decodeDelimited=function(Z){if(!(Z instanceof O))Z=new O(Z);return this.decode(Z,Z.uint32())},z.verify=function(Z){if(typeof Z!=="object"||Z===null)return"object expected";if(Z.fromAddress!=null&&Z.hasOwnProperty("fromAddress")){if(!(Z.fromAddress&&typeof Z.fromAddress.length==="number"||_.isString(Z.fromAddress)))return"fromAddress: buffer expected"}if(Z.toAddress!=null&&Z.hasOwnProperty("toAddress")){if(!(Z.toAddress&&typeof Z.toAddress.length==="number"||_.isString(Z.toAddress)))return"toAddress: buffer expected"}if(Z.amount!=null&&Z.hasOwnProperty("amount")){if(!Array.isArray(Z.amount))return"amount: array expected";for(let Q=0;Q<Z.amount.length;++Q){let X=q.cosmos.base.v1beta1.Coin.verify(Z.amount[Q]);if(X)return"amount."+X}}return null},z.fromObject=function(Z){if(Z instanceof q.types.MsgSend)return Z;let Q=new q.types.MsgSend;if(Z.fromAddress!=null){if(typeof Z.fromAddress==="string")_.base64.decode(Z.fromAddress,Q.fromAddress=_.newBuffer(_.base64.length(Z.fromAddress)),0);else if(Z.fromAddress.length)Q.fromAddress=Z.fromAddress}if(Z.toAddress!=null){if(typeof Z.toAddress==="string")_.base64.decode(Z.toAddress,Q.toAddress=_.newBuffer(_.base64.length(Z.toAddress)),0);else if(Z.toAddress.length)Q.toAddress=Z.toAddress}if(Z.amount){if(!Array.isArray(Z.amount))throw TypeError(".types.MsgSend.amount: array expected");Q.amount=[];for(let X=0;X<Z.amount.length;++X){if(typeof Z.amount[X]!=="object")throw TypeError(".types.MsgSend.amount: object expected");Q.amount[X]=q.cosmos.base.v1beta1.Coin.fromObject(Z.amount[X])}}return Q},z.toObject=function(Z,Q){if(!Q)Q={};let X={};if(Q.arrays||Q.defaults)X.amount=[];if(Q.defaults){if(Q.bytes===String)X.fromAddress="";else if(X.fromAddress=[],Q.bytes!==Array)X.fromAddress=_.newBuffer(X.fromAddress);if(Q.bytes===String)X.toAddress="";else if(X.toAddress=[],Q.bytes!==Array)X.toAddress=_.newBuffer(X.toAddress)}if(Z.fromAddress!=null&&Z.hasOwnProperty("fromAddress"))X.fromAddress=Q.bytes===String?_.base64.encode(Z.fromAddress,0,Z.fromAddress.length):Q.bytes===Array?Array.prototype.slice.call(Z.fromAddress):Z.fromAddress;if(Z.toAddress!=null&&Z.hasOwnProperty("toAddress"))X.toAddress=Q.bytes===String?_.base64.encode(Z.toAddress,0,Z.toAddress.length):Q.bytes===Array?Array.prototype.slice.call(Z.toAddress):Z.toAddress;if(Z.amount?.length){X.amount=[];for(let L=0;L<Z.amount.length;++L)X.amount[L]=q.cosmos.base.v1beta1.Coin.toObject(Z.amount[L],Q)}return X},z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},z})(),Y})();q.cosmos=(()=>{let Y={};return Y.base=(()=>{let z={};return z.v1beta1=(()=>{let H={};return H.Coin=(()=>{function Z(Q){if(Q){for(let X=Object.keys(Q),L=0;L<X.length;++L)if(Q[X[L]]!=null)this[X[L]]=Q[X[L]]}}return Z.prototype.denom="",Z.prototype.amount="",Z.create=function(X){return new Z(X)},Z.encode=function(X,L){if(!L)L=P.create();if(X.denom!=null&&Object.hasOwnProperty.call(X,"denom"))L.uint32(10).string(X.denom);if(X.amount!=null&&Object.hasOwnProperty.call(X,"amount"))L.uint32(18).string(X.amount);return L},Z.encodeDelimited=function(X,L){return this.encode(X,L).ldelim()},Z.decode=function(X,L){if(!(X instanceof O))X=O.create(X);let J=L===void 0?X.len:X.pos+L,G=new q.cosmos.base.v1beta1.Coin;while(X.pos<J){let B=X.uint32();switch(B>>>3){case 1:G.denom=X.string();break;case 2:G.amount=X.string();break;default:X.skipType(B&7);break}}return G},Z.decodeDelimited=function(X){if(!(X instanceof O))X=new O(X);return this.decode(X,X.uint32())},Z.verify=function(X){if(typeof X!=="object"||X===null)return"object expected";if(X.denom!=null&&X.hasOwnProperty("denom")){if(!_.isString(X.denom))return"denom: string expected"}if(X.amount!=null&&X.hasOwnProperty("amount")){if(!_.isString(X.amount))return"amount: string expected"}return null},Z.fromObject=function(X){if(X instanceof q.cosmos.base.v1beta1.Coin)return X;let L=new q.cosmos.base.v1beta1.Coin;if(X.denom!=null)L.denom=String(X.denom);if(X.amount!=null)L.amount=String(X.amount);return L},Z.toObject=function(X,L){if(!L)L={};let J={};if(L.defaults)J.denom="",J.amount="";if(X.denom!=null&&X.hasOwnProperty("denom"))J.denom=X.denom;if(X.amount!=null&&X.hasOwnProperty("amount"))J.amount=X.amount;return J},Z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},Z})(),H.DecCoin=(()=>{function Z(Q){if(Q){for(let X=Object.keys(Q),L=0;L<X.length;++L)if(Q[X[L]]!=null)this[X[L]]=Q[X[L]]}}return Z.prototype.denom="",Z.prototype.amount="",Z.create=function(X){return new Z(X)},Z.encode=function(X,L){if(!L)L=P.create();if(X.denom!=null&&Object.hasOwnProperty.call(X,"denom"))L.uint32(10).string(X.denom);if(X.amount!=null&&Object.hasOwnProperty.call(X,"amount"))L.uint32(18).string(X.amount);return L},Z.encodeDelimited=function(X,L){return this.encode(X,L).ldelim()},Z.decode=function(X,L){if(!(X instanceof O))X=O.create(X);let J=L===void 0?X.len:X.pos+L,G=new q.cosmos.base.v1beta1.DecCoin;while(X.pos<J){let B=X.uint32();switch(B>>>3){case 1:G.denom=X.string();break;case 2:G.amount=X.string();break;default:X.skipType(B&7);break}}return G},Z.decodeDelimited=function(X){if(!(X instanceof O))X=new O(X);return this.decode(X,X.uint32())},Z.verify=function(X){if(typeof X!=="object"||X===null)return"object expected";if(X.denom!=null&&X.hasOwnProperty("denom")){if(!_.isString(X.denom))return"denom: string expected"}if(X.amount!=null&&X.hasOwnProperty("amount")){if(!_.isString(X.amount))return"amount: string expected"}return null},Z.fromObject=function(X){if(X instanceof q.cosmos.base.v1beta1.DecCoin)return X;let L=new q.cosmos.base.v1beta1.DecCoin;if(X.denom!=null)L.denom=String(X.denom);if(X.amount!=null)L.amount=String(X.amount);return L},Z.toObject=function(X,L){if(!L)L={};let J={};if(L.defaults)J.denom="",J.amount="";if(X.denom!=null&&X.hasOwnProperty("denom"))J.denom=X.denom;if(X.amount!=null&&X.hasOwnProperty("amount"))J.amount=X.amount;return J},Z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},Z})(),H.IntProto=(()=>{function Z(Q){if(Q){for(let X=Object.keys(Q),L=0;L<X.length;++L)if(Q[X[L]]!=null)this[X[L]]=Q[X[L]]}}return Z.prototype.int="",Z.create=function(X){return new Z(X)},Z.encode=function(X,L){if(!L)L=P.create();if(X.int!=null&&Object.hasOwnProperty.call(X,"int"))L.uint32(10).string(X.int);return L},Z.encodeDelimited=function(X,L){return this.encode(X,L).ldelim()},Z.decode=function(X,L){if(!(X instanceof O))X=O.create(X);let J=L===void 0?X.len:X.pos+L,G=new q.cosmos.base.v1beta1.IntProto;while(X.pos<J){let B=X.uint32();switch(B>>>3){case 1:G.int=X.string();break;default:X.skipType(B&7);break}}return G},Z.decodeDelimited=function(X){if(!(X instanceof O))X=new O(X);return this.decode(X,X.uint32())},Z.verify=function(X){if(typeof X!=="object"||X===null)return"object expected";if(X.int!=null&&X.hasOwnProperty("int")){if(!_.isString(X.int))return"int: string expected"}return null},Z.fromObject=function(X){if(X instanceof q.cosmos.base.v1beta1.IntProto)return X;let L=new q.cosmos.base.v1beta1.IntProto;if(X.int!=null)L.int=String(X.int);return L},Z.toObject=function(X,L){if(!L)L={};let J={};if(L.defaults)J.int="";if(X.int!=null&&X.hasOwnProperty("int"))J.int=X.int;return J},Z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},Z})(),H.DecProto=(()=>{function Z(Q){if(Q){for(let X=Object.keys(Q),L=0;L<X.length;++L)if(Q[X[L]]!=null)this[X[L]]=Q[X[L]]}}return Z.prototype.dec="",Z.create=function(X){return new Z(X)},Z.encode=function(X,L){if(!L)L=P.create();if(X.dec!=null&&Object.hasOwnProperty.call(X,"dec"))L.uint32(10).string(X.dec);return L},Z.encodeDelimited=function(X,L){return this.encode(X,L).ldelim()},Z.decode=function(X,L){if(!(X instanceof O))X=O.create(X);let J=L===void 0?X.len:X.pos+L,G=new q.cosmos.base.v1beta1.DecProto;while(X.pos<J){let B=X.uint32();switch(B>>>3){case 1:G.dec=X.string();break;default:X.skipType(B&7);break}}return G},Z.decodeDelimited=function(X){if(!(X instanceof O))X=new O(X);return this.decode(X,X.uint32())},Z.verify=function(X){if(typeof X!=="object"||X===null)return"object expected";if(X.dec!=null&&X.hasOwnProperty("dec")){if(!_.isString(X.dec))return"dec: string expected"}return null},Z.fromObject=function(X){if(X instanceof q.cosmos.base.v1beta1.DecProto)return X;let L=new q.cosmos.base.v1beta1.DecProto;if(X.dec!=null)L.dec=String(X.dec);return L},Z.toObject=function(X,L){if(!L)L={};let J={};if(L.defaults)J.dec="";if(X.dec!=null&&X.hasOwnProperty("dec"))J.dec=X.dec;return J},Z.prototype.toJSON=function(){return this.constructor.toObject(this,k.util.toJSONOptions)},Z})(),H})(),z})(),Y})();function O6(Y){if(Y instanceof Uint8Array)return Y;if(typeof Y==="string")return Uint8Array.from(globalThis.atob(Y),(H)=>H.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var $0=(Y)=>{let z=Y;return q.types.MsgSend.encode({amount:z.amount,fromAddress:O6(z.fromAddress),toAddress:O6(z.toAddress)}).finish()},y0=(Y)=>{let z=Y;return q.types.MsgDeposit.encode({coins:z.coins.map((H)=>({amount:H.amount,asset:H.asset})),memo:z.memo,signer:O6(z.signer)}).finish()};function d(){return{...C0,"/types.MsgDeposit":y0,"/types.MsgSend":$0}}function j(Y,z=Y===j6.THORChain?"thor":"maya"){let H=Y===j6.THORChain?"thorchain":"mayachain",Z={"/types.MsgDeposit":{aminoType:`${H}/MsgDeposit`,fromAmino:({signer:Q,...X})=>({...X,signer:t(Q)}),toAmino:({signer:Q,...X})=>({...X,signer:typeof Q==="string"?r(Q,z):Q})},"/types.MsgSend":{aminoType:`${H}/MsgSend`,fromAmino:({from_address:Q,to_address:X,...L})=>({...L,fromAddress:t(Q),toAddress:t(X)}),toAmino:({fromAddress:Q,toAddress:X,...L})=>({...L,from_address:typeof Q==="string"?r(Q,z):Q,to_address:typeof X==="string"?r(X,z):X})}};return Object.assign(Z,{fromAmino(Q){let X=Object.entries(Z).find(([,G])=>G.aminoType===Q.type);if(!X)throw TypeError(`No converter for amino type ${Q.type}`);let[L,J]=X;return{typeUrl:L,value:J.fromAmino(Q.value)}},toAmino(Q){let X=Z[Q.typeUrl];if(!X)throw TypeError(`No converter for type URL ${Q.typeUrl}`);return{type:X.aminoType,value:X.toAmino(Q.value)}}})}var g8=C(Z6.THORChain).gas,i8=C(Z6.Maya).gas,u6=({sender:Y,recipient:z,assetValue:H})=>{return{type:`${H.chain===Z6.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:H.getBaseValue("string"),denom:y(H.symbol,!0)}],from_address:Y,to_address:z}}},l6=({sender:Y,assetValue:z,memo:H=""})=>{return{type:`${z.chain===Z6.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:z.getBaseValue("string"),asset:e(z)}],memo:H,signer:Y}}},I6=({sender:Y,recipient:z,assetValue:H,memo:Z})=>{return!z?l6({assetValue:H,memo:Z,sender:Y}):u6({assetValue:H,recipient:z,sender:Y})};function b6(Y,z){for(let H of["/types.MsgDeposit","/types.MsgSend"]){let Z=Y[H];if(Z.aminoType===z)return{fromAmino:Z.fromAmino,typeUrl:H}}return null}var h=(Y,z)=>{let H=j(z),Z=b6(H,Y.type);if(!Z)throw new B6("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${Y.type}`});return{typeUrl:Z.typeUrl,value:Z.fromAmino(Y.value)}},p6=async({rpcUrl:Y,sender:z})=>{let Z=await(await $(Y)).getAccount(z);if(!Z)throw new B6("toolbox_cosmos_account_not_found",{sender:z});return Z};async function d6(Y){let{assetValue:z,recipient:H,memo:Z,sender:Q,asSignable:X,asAminoMessage:L,sequence:J,accountNumber:G}=Y,B=Y.sweep?await E6({assetValue:z,sender:Q}):z;if(H)return h0({accountNumber:G,asAminoMessage:L,asSignable:X,assetValue:B,memo:Z,recipient:H,sender:Q,sequence:J});return u0({accountNumber:G,asAminoMessage:L,asSignable:X,assetValue:B,memo:Z,sender:Q,sequence:J})}async function E6({assetValue:Y,sender:z}){let H=Y.chain,Z=await N6(H),X=await(await $(Z)).getAllBalances(z),L=Y.isGasAsset?(await s(H)).getBaseValue("bigint"):0n;return m({assetValue:Y,balances:X,denom:y(Y.symbol,!0),feeAmount:L})}async function h0({sender:Y,recipient:z,assetValue:H,memo:Z="",asSignable:Q=!0,asAminoMessage:X=!1,sequence:L,accountNumber:J}){let G=H.chain,B=J!==void 0&&L!==void 0?void 0:await p6({rpcUrl:await N6(G),sender:Y}),{chainId:U}=h6(G),V=u6({assetValue:H,recipient:z,sender:Y}),T=Q?h(X?V:u(V),G):V;return{accountNumber:J??Number(B?.accountNumber),chainId:U,fee:C(G),memo:Z,msgs:[T],sequence:L??Number(B?.sequence)}}async function u0({sender:Y,assetValue:z,memo:H="",asSignable:Z=!0,asAminoMessage:Q=!1,sequence:X,accountNumber:L}){let J=z.chain,G=L!==void 0&&X!==void 0?void 0:await p6({rpcUrl:await N6(J),sender:Y}),{chainId:B}=h6(J),U=l6({assetValue:z,memo:H,sender:Y}),V=Z?h(Q?U:u(U),J):U;return{accountNumber:L??Number(G?.accountNumber),chainId:B,fee:C(J),memo:H,msgs:[V],sequence:X??Number(G?.sequence)}}function u(Y){if(Y.type==="thorchain/MsgSend"||Y.type==="mayachain/MsgSend")return Y;return{...Y,value:{...Y.value,coins:Y.value.coins.map((z)=>{let H=j0.from({asset:z.asset}),Z=(H.isSynthetic?H.symbol.split("/")?.[1]:H.symbol)?.toUpperCase(),Q=(H.isSynthetic?H.symbol.split("/")?.[0]:H.chain)?.toUpperCase();return{...z,asset:{chain:Q,symbol:Z,synth:H.isSynthetic,ticker:H.ticker}}})}}}function Q6({chain:Y,memo:z,msgs:H}){let Z=d(),Q=j(Y),L=H.map((J)=>{let G=b6(Q,J.type);if(!G)throw new B6("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${J.type}`});return{typeUrl:G.typeUrl,value:G.fromAmino(J.value)}}).map((J)=>f0(J,Z));return w0({memo:z,messages:L})}import{Chain as g,SwapKitError as k8}from"@swapkit/helpers";import{secp256k1 as l0}from"@noble/curves/secp256k1.js";import{base64 as V6,bech32 as U6}from"@scure/base";import{HDKey as b0}from"@scure/bip32";import{verifySignature as p0,createWalletFromMnemonic as d0,createWalletFromPrivateKey as c0,mnemonicToSeed as m0,signDirect as n0}from"@swapkit/cosmos-signer";import{AssetValue as M6,applyFeeMultiplier as c6,Chain as F,CosmosChainPrefixes as t6,DerivationPath as g0,derivationPathToString as m6,FeeOption as T6,getChainConfig as i0,getRPCUrl as n,NetworkDerivationPath as o0,SwapKitError as f,SwapKitNumber as K6,updateDerivationPath as t0}from"@swapkit/helpers";import{SwapKitApi as r6}from"@swapkit/helpers/api";import{PubKey as r0}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as a0,P as n6}from"ts-pattern";async function a6(Y,z){try{let Z=(await r6.getGasRate()).find((Q)=>Q.chainId===Y)?.value;return Z?Number.parseFloat(Z):z}catch{return z}}function s6(Y){let z=[{address:Y.address,algo:"secp256k1",pubkey:Y.publicKey}];return{getAccounts:()=>Promise.resolve(z),async signDirect(H,Z){if(H!==Y.address)throw new f("toolbox_cosmos_signer_not_defined");let Q=await n0(Y.privateKey,Y.publicKey,{accountNumber:Z.accountNumber,authInfoBytes:Z.authInfoBytes,bodyBytes:Z.bodyBytes,chainId:Z.chainId});return{signature:Q.signature,signed:{accountNumber:Q.signed.accountNumber,authInfoBytes:Q.signed.authInfoBytes,bodyBytes:Q.signed.bodyBytes,chainId:Q.signed.chainId}}}}}async function g6({phrase:Y,prefix:z,...H}){let Z="derivationPath"in H?H.derivationPath:`${g0[H.chain]}/${H.index??0}`,Q=await d0({hdPath:Z,mnemonic:Y,prefix:z??""});return s6(Q)}async function s0({privateKey:Y,prefix:z}){let H=c0({prefix:z,privateKey:Y});return s6(H)}var i6={[F.Cosmos]:1000,[F.Kujira]:1000,[F.Noble]:1000,[F.THORChain]:5000000,[F.Maya]:5000000,[F.Harbor]:5000000};function e0(Y){return async function({signature:H,message:Z,address:Q}){let X=await Y(Q);if(!X?.pubkey)throw new f("toolbox_cosmos_verify_signature_no_pubkey");let L=X.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?r0.decode(X.pubkey.value).key:X.pubkey.value;return p0(V6.decode(Z),V6.decode(H),L)}}function X6({chain:Y,...z}){let H=t6[Y],Z="index"in z?z.index||0:0,Q=m6("derivationPath"in z&&z.derivationPath?z.derivationPath:t0(o0[Y],{index:Z})),X;async function L(){if(X)return X;return X=await a0(z).with({phrase:n6.string},({phrase:N})=>g6({derivationPath:Q,phrase:N,prefix:H})).with({signer:n6.any},({signer:N})=>N).otherwise(()=>{return}),X}async function J(N){let I=await n(Y);return(await $(I)).getAccount(N)}async function G(){let N=await L(),[I]=await N?.getAccounts()||[];return I?.address}async function B(){let N=await L(),[I]=await N?.getAccounts()||[];if(!I?.pubkey)throw new f("toolbox_cosmos_signer_not_defined");return V6.encode(I?.pubkey)}async function U(N){let I=await L(),W=await G(),E=await n(Y);if(!(I&&W))throw new f("toolbox_cosmos_signer_not_defined");return(await p(E,I)).sign(W,N.msgs,N.fee,N.memo,{accountNumber:BigInt(N.accountNumber),chainId:N.chainId,sequence:N.sequence})}async function V(N){let I=await L(),W=await G(),E=await n(Y);if(!(I&&W))throw new f("toolbox_cosmos_signer_not_defined");let M=await(await p(E,I)).signAndBroadcast(W,N.msgs,N.fee,N.memo);if(M.code!==0)throw new f("core_swap_transaction_error",{code:M.code,message:M.rawLog});return M.transactionHash}async function T({recipient:N,assetValue:I,memo:W="",feeRate:E,feeOptionKey:R=T6.Fast,sweep:M}){let x=await L(),A=await G();if(!(x&&A))throw new f("toolbox_cosmos_signer_not_defined");let v=await n(Y),z6=M6.from({chain:Y}),Y6=e(z6),b=Z8(E||(await o6(Y,i6[Y]))[R],Y6,Y),H6=await p(v,x),c=y(I.symbol),L6=[{amount:(M?m({assetValue:I,balances:await R6(Y)(A),denom:c,feeAmount:W6(b.amount,c)}):I).getBaseValue("string"),denom:c}],{transactionHash:J6}=await H6.sendTokens(A,N,L6,b,W);return J6}return{createPrivateKeyFromPhrase:z8(Q),createTransaction:f6,fetchFeeRateFromSwapKit:a6,getAccount:J,getAddress:G,getBalance:async(N,I)=>{let W=await R6(Y)(N),E=await Promise.all(W.filter(({denom:R})=>R&&!R.includes("IBC/")&&!([F.THORChain,F.Maya].includes(Y)&&R.split("-").length>2)).map(({denom:R,amount:M})=>{let x=[F.THORChain,F.Maya].includes(Y)&&(R.includes("/")||R.includes("˜"))?`${Y}.${R}`:R;return w6(x,M)}));if(E.length===0)return[M6.from({chain:Y})];return E},getBalanceAsDenoms:R6(Y),getFees:()=>o6(Y,i6[Y]),getPubKey:B,getSignerFromPhrase:({phrase:N,derivationPath:I})=>g6({derivationPath:m6(I),index:Z,phrase:N,prefix:H}),getSignerFromPrivateKey:(N)=>s0({prefix:H,privateKey:N}),signAndBroadcastTransaction:V,signTransaction:U,transfer:T,validateAddress:X8(Y),verifySignature:e0(J)}}async function _Z(Y,z){try{let Z=(await r6.getGasRate()).find((Q)=>Q.chainId===Y)?.value;return Z?Number.parseFloat(Z):z}catch{return z}}function WZ({assetValue:{chain:Y}}){return M6.from({chain:Y,value:Q8(Y)})}async function o6(Y,z){let{chainId:H,baseDecimal:Z}=i0(Y),Q=await a6(H,z);return{average:K6.fromBigInt(BigInt(Q),Z),fast:K6.fromBigInt(BigInt(c6(Q,T6.Fast,!0)),Z),fastest:K6.fromBigInt(BigInt(c6(Q,T6.Fastest,!0)),Z)}}function Z8(Y,z,H){return{amount:[{amount:typeof Y==="number"?Y.toString():Y.getBaseValue("string"),denom:z}],gas:C(H).gas}}function Q8(Y){return{[F.Cosmos]:0.007,[F.Kujira]:0.02,[F.Noble]:0.01,[F.THORChain]:0.02,[F.Maya]:0.02,[F.Harbor]:0.02}[Y]||0}function X8(Y){let z=t6[Y];return function(Z){if(!Z.startsWith(z))return!1;try{let{prefix:Q,words:X}=U6.decode(Z);return U6.encode(Q,X)===Z.toLocaleLowerCase()}catch{return!1}}}function R6(Y){return async function(H){let Z=await n(Y);return(await(await $(Z)).getAllBalances(H)).map((J)=>({...J,denom:J.denom.includes("/")?J.denom.toUpperCase():J.denom}))}}function z8(Y){return async function(H){let Z=await m0(H),X=b0.fromMasterSeed(Z).derive(Y);if(!X.privateKey)throw new f("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return l0.getPublicKey(X.privateKey,!0),Uint8Array.from(X.privateKey)}}import{secp256k1 as Y8}from"@noble/curves/secp256k1.js";import{base64 as w}from"@scure/base";import{buildMultisignedTx as H8,createMultisigThresholdPubkey as L8,signAmino as J8,createWalletFromMnemonic as G8,encodeTxRaw as q8,multisigPubkeyToAddress as _8,singlePubkeyToAddress as Z0}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as W8,derivationPathToString as O8,FeeOption as x6,getRPCUrl as Q0,NetworkDerivationPath as N8,SKConfig as B8,SwapKitError as l,updateDerivationPath as I8}from"@swapkit/helpers";import{match as E8,P as e6}from"ts-pattern";function U8(Y){let z=[{address:Y.address,algo:"secp256k1",pubkey:Y.publicKey}];return{accounts:z,getAccounts:()=>Promise.resolve(z),async signAmino(H,Z){if(H!==Y.address)throw new l("toolbox_cosmos_signer_not_defined");let Q=await J8(Y.privateKey,Y.publicKey,{signDoc:Z});return{signature:Q.signature,signed:Q.signed}}}}function K8({prefix:Y,derivationPath:z}){return async function(Z,Q=0){let X=await G8({hdPath:`${z}/${Q}`,mnemonic:Z,prefix:Y});return U8(X)}}function R8(Y){return w.encode(Y)}function V8(Y,z){return async function({wallet:Z,tx:Q}){let{msgs:X,accountNumber:L,sequence:J,chainId:G,fee:B,memo:U}=typeof Q==="string"?JSON.parse(Q):Q,V=(await Z.getAccounts())?.[0]?.address||"",T=j(Y,z),N=d(),I=await y6(Z,{aminoTypes:T,registry:N}),W=[];for(let M of X){let x=h(M,Y);W.push(x)}let{signatures:[E]}=await I.sign(V,W,B,U,{accountNumber:BigInt(L),chainId:G,sequence:J});return{bodyBytes:Q6({chain:Y,memo:U,msgs:X.map(u)}),signature:R8(E)}}}function X0(Y){if(Y.length!==33||Y[0]!==2&&Y[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:w.encode(Y)}}function M8({prefix:Y,chain:z}){return async function(Z,Q,X,L,J){let G=await Q0(z),{sequence:B,fee:U}=JSON.parse(Z),V=z0(X,L),T=Q.map((W)=>[Z0(X0(w.decode(W.pubKey)),Y),w.decode(W.signature)]),N=await $(G),{transactionHash:I}=await N.broadcastTx(H8({bodyBytes:J,fee:{amount:U.amount,gasLimit:BigInt(U.gas),...U.payer?{payer:U.payer}:{},...U.granter?{granter:U.granter}:{}},multisigPubkey:V,prefix:Y,sequence:B,signatures:new Map(T)}));return I}}function z0(Y,z,H=!0){return L8(Y.map((Z)=>X0(w.decode(Z))),z,H)}function T8(Y){return w.decode(Y)}function x8({privateKey:Y,message:z}){let H=Y8.sign(w.decode(z),Y,{lowS:!0,prehash:!1});return Promise.resolve(w.encode(H))}function Y0({chain:Y,...z}){let{isStagenet:H}=B8.get("envs"),Z=`${H?"s":""}${W8[Y]}`,Q="index"in z?z.index||0:0,X="derivationPath"in z&&z.derivationPath?z.derivationPath:I8(N8[Y],{index:Q}),L=X6({chain:Y,...z}),J=C(Y),G;function B(){return G??=E8(z).with({phrase:e6.string},({phrase:W})=>L.getSignerFromPhrase({derivationPath:X,phrase:W})).with({signer:e6.any},({signer:W})=>Promise.resolve(W)).otherwise(()=>Promise.resolve(void 0)),G}async function U(){let W=await Q0(Y),E=await B();if(!E)throw new l("toolbox_cosmos_no_signer");let R=d(),M=j(Y,Z),x=await p(W,E,{aminoTypes:M,registry:R});return{signer:E,signingClient:x}}async function V({fee:W,memo:E,msgs:R}){let{signer:M,signingClient:x}=await U(),A=(await M.getAccounts())?.[0]?.address;if(!A)throw new l("toolbox_cosmos_signer_not_defined");let v=await x.signAndBroadcast(A,R,W,E);if(v.code!==0)throw new l("core_swap_transaction_error",{code:v.code,message:v.rawLog});return v.transactionHash}async function T(){let W=await s(Y);return{[x6.Average]:W,[x6.Fast]:W,[x6.Fastest]:W}}async function N({assetValue:W,memo:E="",recipient:R,sweep:M}){let{signer:x,signingClient:A}=await U(),v=(await x.getAccounts())?.[0]?.address;if(!v)throw new l("toolbox_cosmos_no_signer");let z6="signAmino"in x,Y6=M?await E6({assetValue:W,sender:v}):W,b=I6({assetValue:Y6,memo:E,recipient:R,sender:v});if(z6){let k6=h(b,Y),{signatures:L6,authInfoBytes:J6}=await A.sign(v,[k6],J,E),H0=q8({authInfoBytes:J6,bodyBytes:Q6({chain:Y,memo:E,msgs:[b].map(u)}),signatures:L6});return(await A.broadcastTx(H0)).transactionHash}let H6=u(b),c=h(H6,Y);return V({fee:J,memo:E,msgs:[c]})}async function I(W){let{signer:E,signingClient:R}=await U(),M=(await E.getAccounts())?.[0]?.address;if(!M)throw new l("toolbox_cosmos_signer_not_defined");return R.sign(M,W.msgs,W.fee,W.memo,{accountNumber:BigInt(W.accountNumber),chainId:W.chainId,sequence:W.sequence})}return{...L,broadcastMultisigTx:M8({chain:Y,prefix:Z}),buildAminoMsg:I6,buildEncodedTxBody:Q6,convertToSignable:h,createDefaultAminoTypes:()=>j(Y,Z),createDefaultRegistry:d,createMultisig:z0,createTransaction:d6,deposit:N,getFees:T,importSignature:T8,parseAminoMessageForDirectSigning:u,pubkeyToAddress:(W)=>{if(W.type==="tendermint/PubKeyMultisigThreshold")return _8(W,Z);return Z0(W,Z)},secp256k1HdWalletFromMnemonic:K8({derivationPath:O8(X),prefix:Z}),signAndBroadcastTransaction:V,signMultisigTx:V8(Y,Z),signTransaction:I,signWithPrivateKey:x8,transfer:N}}var FZ=(Y,z)=>{switch(Y){case g.Cosmos:case g.Kujira:case g.Noble:return X6({chain:Y,...z});case g.Maya:case g.THORChain:return Y0({chain:Y,...z});default:throw new k8("toolbox_cosmos_not_supported",{chain:Y})}};export{e0 as verifySignature,u6 as transferMsgAmino,P8 as toBase64,E6 as resolveThorchainSweepAssetValue,u as parseAminoMessageForDirectSigning,s as getThorchainNativeFee,m as getSweepAssetValue,s0 as getSignerFromPrivateKey,g6 as getSignerFromPhrase,y as getMsgSendDenom,_Z as getFeeRateFromSwapKit,W6 as getFeeAmountForDenom,e as getDenomWithChain,C as getDefaultChainFee,FZ as getCosmosToolbox,X8 as getCosmosAddressValidator,w6 as getAssetFromDenom,A8 as fromBase64,a6 as fetchFeeRateFromSwapKit,WZ as estimateTransactionFee,l6 as depositMsgAmino,d6 as createTransaction,Y0 as createThorchainToolbox,$ as createStargateClient,p as createSigningStargateClient,y6 as createOfflineStargateClient,d as createDefaultRegistry,j as createDefaultAminoTypes,X6 as createCosmosToolbox,f6 as cosmosCreateTransaction,h as convertToSignable,h0 as buildTransferTx,Q6 as buildEncodedTxBody,u0 as buildDepositTx,I6 as buildAminoMsg,t as bech32ToBase64,r as base64ToBech32,E0 as YUM_KUJIRA_FACTORY_DENOM,A6 as USK_KUJIRA_FACTORY_DENOM,g8 as THORCHAIN_GAS_VALUE,i8 as MAYA_GAS_VALUE,R0 as DEFAULT_NOBLE_FEE_MAINNET,K0 as DEFAULT_KUJI_FEE_MAINNET,U0 as DEFAULT_COSMOS_FEE_MAINNET};
1
+ import"../../chunk-k50sjysj.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 +1 @@
1
- import{a as da}from"../../chunk-44m22jy1.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 as $,b as a,ba as aa,c as b,ca as ba,d as c,da as ca,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}from"../../chunk-ye1j5pz2.js";import"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";export{p as validateEVMAddress,m as validateAuthorizations,j as validateAuthorization,f as toHexString,u as toChecksumAddress,i as signAuthorization,l as parseEIP712FromEVMTx,t as isStateChangingCall,B as isEIP7702Transaction,C as isEIP1559Transaction,q as isBrowserProvider,y as getTokenAddress,c as getProviderSync,d as getProvider,g as getNetworkParams,h as getIsEIP1559Compatible,e as getFallbackProvider,ca as getEvmToolboxAsync,ba as getEvmToolbox,a as getEvmApi,A as getEstimateGasPrices,D as getEVMTxType,v as getEIP1193SendTransaction,z as getCreateContractTxObject,s as getCreateContract,w as getChecksumAddressFromAsset,E as createOPStackToolbox,b as createCustomEvmApi,r as createContract,k as buildEIP712DomainType,aa as XLayerToolbox,$ as UNIToolbox,_ as SONICToolbox,Z as PLASMAToolbox,F as OPToolbox,Y as MONADToolbox,X as MEGAETHToolbox,n as MAX_APPROVAL,W as MATICToolbox,V as LINEAToolbox,U as HYPEREVMToolbox,T as HOODToolbox,S as GNOToolbox,da as EthNetwork,G as ETHToolbox,x as ContractAddress,R as CROToolbox,Q as CORNToolbox,P as COREToolbox,O as BotanixToolbox,o as BaseEVMToolbox,N as BSCToolbox,M as BERAToolbox,L as BASEToolbox,K as AVAXToolbox,J as AURORAToolbox,I as ARBToolbox,H as ADIToolbox};
1
+ import{a as ea}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,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-1ma8fv42.js";import"../../chunk-s1528ghz.js";import"../../chunk-k50sjysj.js";export{H as ADIToolbox,I as ARBToolbox,J as AURORAToolbox,K as AVAXToolbox,L as BASEToolbox,M as BERAToolbox,N as BSCToolbox,o as BaseEVMToolbox,O as BotanixToolbox,P as COREToolbox,Q as CORNToolbox,R as CROToolbox,x as ContractAddress,G as ETHToolbox,ea as EthNetwork,S as GNOToolbox,T as HOODToolbox,U as HYPEREVMToolbox,V as LINEAToolbox,W as MATICToolbox,n as MAX_APPROVAL,X as MEGAETHToolbox,Y as MONADToolbox,F as OPToolbox,Z as PLASMAToolbox,_ as SONICToolbox,aa as UNIToolbox,ba 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,ca as getEvmToolbox,da 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 +1 @@
1
- import"../../chunk-44m22jy1.js";import{q as KH}from"../../chunk-ye1j5pz2.js";import"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";function zM({builder:H,grouping:M="na",orders:G}){return{builder:H,grouping:M,orders:G,type:"order"}}function FM({cancels:H}){return{cancels:H,type:"cancel"}}function VM({cancels:H}){return{cancels:H,type:"cancelByCloid"}}function KM({oid:H,order:M}){return{oid:H,order:M,type:"modify"}}function EM({modifies:H}){return{modifies:H,type:"batchModify"}}function BM({asset:H,isCross:M,leverage:G}){return{asset:H,isCross:M,leverage:G,type:"updateLeverage"}}function PM({asset:H,isBuy:M,ntli:G}){return{asset:H,isBuy:M,ntli:G,type:"updateIsolatedMargin"}}function wM({asset:H,leverage:M}){return{asset:H,leverage:M,type:"topUpIsolatedOnlyMargin"}}function TM({time:H}){return{time:H,type:"scheduleCancel"}}function DM({amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X}){return{amount:H,hyperliquidChain:M,nonce:G,signatureChainId:J,toPerp:X,type:"usdClassTransfer"}}function XH({amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:Z,signatureChainId:$,sourceDex:Q,token:C}){return{amount:H,destination:M,destinationDex:G,fromSubAccount:J,hyperliquidChain:X,nonce:Z,signatureChainId:$,sourceDex:Q,token:C,type:"sendAsset"}}function AM({agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X}){return{agentAddress:H,agentName:M,hyperliquidChain:G,nonce:J,signatureChainId:X,type:"approveAgent"}}function bM({builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X}){return{builder:H,hyperliquidChain:M,maxFeeRate:G,nonce:J,signatureChainId:X,type:"approveBuilderFee"}}function yM({hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,validator:X,wei:Z}){return{hyperliquidChain:H,isUndelegate:M,nonce:G,signatureChainId:J,type:"tokenDelegate",validator:X,wei:Z}}import{SwapKitError as rH,SwapKitNumber as oH}from"@swapkit/helpers";import{HYPERCORE_USDC_TOKEN_ID as x}from"@swapkit/helpers/api";import{SwapKitError as o}from"@swapkit/helpers";import{keccak256 as hH,Signature as gH}from"ethers";var k="0x0000000000000000000000000000000000000000",w="0xa4b1",S={name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},vH={chainId:1337,name:"Exchange",verifyingContract:k,version:"1"},pH={Agent:[{name:"source",type:"string"},{name:"connectionId",type:"bytes32"}]},$H="Mainnet",i={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"}]},s={approveAgent:"HyperliquidTransaction:ApproveAgent",approveBuilderFee:"HyperliquidTransaction:ApproveBuilderFee",sendAsset:"HyperliquidTransaction:SendAsset",tokenDelegate:"HyperliquidTransaction:TokenDelegate",usdClassTransfer:"HyperliquidTransaction:UsdClassTransfer"},mH=new TextEncoder;function F(...H){let M=H.reduce((X,Z)=>X+Z.length,0),G=new Uint8Array(M),J=0;for(let X of H)G.set(X,J),J+=X.length;return G}function lH(H,M,G){if(G<M)return new Uint8Array([H+G]);if(G<=255)return new Uint8Array([H+M,G]);if(G<=65535)return new Uint8Array([H+M+1,G>>8,G&255]);return new Uint8Array([H+M+2,G>>>24&255,G>>>16&255,G>>>8&255,G&255])}function b(H,M){let G=new Uint8Array(M),J=H;for(let X=M-1;X>=0;X-=1)G[X]=Number(J&0xffn),J>>=8n;return G}function ZH(H){if(H>=0n){if(H<=0x7fn)return new Uint8Array([Number(H)]);if(H<=0xffn)return new Uint8Array([204,Number(H)]);if(H<=0xffffn)return F(new Uint8Array([205]),b(H,2));if(H<=0xffffffffn)return F(new Uint8Array([206]),b(H,4));return F(new Uint8Array([207]),b(H,8))}if(H>=-32n)return new Uint8Array([256+Number(H)]);if(H>=-128n)return new Uint8Array([208,256+Number(H)]);if(H>=-32768n)return F(new Uint8Array([209]),b(BigInt.asUintN(16,H),2));if(H>=-2147483648n)return F(new Uint8Array([210]),b(BigInt.asUintN(32,H),4));return F(new Uint8Array([211]),b(BigInt.asUintN(64,H),8))}function OH(H){let M=mH.encode(H);if(M.length<32)return F(new Uint8Array([160+M.length]),M);return F(lH(217,0,M.length),M)}function uH(H){let M=H.map((J)=>n(J)),G=H.length<16?new Uint8Array([144+H.length]):H.length<=65535?new Uint8Array([220,H.length>>8,H.length&255]):new Uint8Array([221,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(G,...M)}function cH(H){let M=Object.entries(H).filter(([,J])=>typeof J<"u"),G=M.length<16?new Uint8Array([128+M.length]):M.length<=65535?new Uint8Array([222,M.length>>8,M.length&255]):new Uint8Array([223,M.length>>>24&255,M.length>>>16&255,M.length>>>8&255,M.length&255]);return F(G,...M.flatMap(([J,X])=>[OH(J),n(X)]))}function n(H){if(H===null)return new Uint8Array([192]);if(typeof H==="boolean")return new Uint8Array([H?195:194]);if(typeof H==="string")return OH(H);if(typeof H==="number"){if(!Number.isFinite(H)||!Number.isInteger(H))throw new o("helpers_invalid_params",{message:"Hyperliquid msgpack only supports integers"});return ZH(BigInt(H))}if(typeof H==="bigint")return ZH(H);if(H instanceof Uint8Array){let M=H.length<=255?new Uint8Array([196,H.length]):H.length<=65535?new Uint8Array([197,H.length>>8,H.length&255]):new Uint8Array([198,H.length>>>24&255,H.length>>>16&255,H.length>>>8&255,H.length&255]);return F(M,H)}if(Array.isArray(H))return uH(H);if(typeof H==="object")return cH(H);throw new o("helpers_invalid_params",{message:`Unsupported Hyperliquid msgpack value: ${String(H)}`})}function dH(H){let M=H.startsWith("0x")?H.slice(2):H;if(M.length%2!==0||/[^a-fA-F0-9]/u.test(M))throw new o("helpers_invalid_params",{hexValue:H});let G=new Uint8Array(M.length/2);for(let J=0;J<M.length;J+=2)G[J/2]=Number.parseInt(M.slice(J,J+2),16);return G}function QH(H){return{domain:vH,message:{connectionId:H,source:"a"},primaryType:"Agent",types:{Agent:[...pH.Agent]}}}function YH(H){let M=s[H.type],G=i[H.type],{signatureChainId:J,type:X,...Z}=H,$=Number.parseInt(J||w,16);return{domain:{...S,chainId:$},message:{...Z,hyperliquidChain:Z.hyperliquidChain||$H},primaryType:M,types:{[M]:G}}}function WH(H){let M=gH.from(H);return{r:M.r,s:M.s,v:M.v}}function _H(H,M,{expiresAfter:G,vaultAddress:J}={}){let X=n(H),Z=b(BigInt(M),8),$=J?F(new Uint8Array([1]),dH(J.toLowerCase())):new Uint8Array([0]),Q=typeof G==="number"?F(new Uint8Array([0]),b(BigInt(G),8)):new Uint8Array;return hH(F(X,Z,$,Q))}function CH(H){let M=H.hyperliquidChain||$H;switch(H.type){case"approveAgent":return{...H,agentAddress:H.agentAddress.toLowerCase(),hyperliquidChain:M};case"approveBuilderFee":return{...H,builder:H.builder.toLowerCase(),hyperliquidChain:M};case"sendAsset":return{...H,destination:H.destination.toLowerCase(),fromSubAccount:H.fromSubAccount.toLowerCase(),hyperliquidChain:M};case"tokenDelegate":return{...H,hyperliquidChain:M,validator:H.validator.toLowerCase()};case"usdClassTransfer":return{...H,hyperliquidChain:M};default:return H}}var RH=Number.parseInt(w,16),iH=new Set(["chainId","name","verifyingContract","version"]),NH=/^0x[0-9a-fA-F]{40}$/,t=i.sendAsset;var Y=(H)=>{throw new rH("toolbox_hypercore_payload_mismatch",{problems:[H]})};function UH(H){try{return new URL(H)}catch{return}}function jH(H){if(!("EIP712Domain"in H.types))return H;let{EIP712Domain:M,...G}=H.types;return{...H,types:G}}function IH({action:H,allowedEndpoints:M,expectedAmount:G,expectedDestination:J,expectedFromSubAccount:X,expectedSourceDex:Z,expectedToken:$,submitTo:Q,typedData:C}){let{domain:U,message:K,primaryType:j,types:q}=C,O=s.sendAsset;if(j!==O)Y(`primaryType is ${JSON.stringify(j)}, expected "${O}"`);if(H.type!=="sendAsset")Y(`action.type is ${JSON.stringify(H.type)}, expected "sendAsset"`);let _=t.map(({name:W})=>W),I=new Set([..._,"signatureChainId","type"]),z=Object.keys(H).filter((W)=>!I.has(W));if(z.length)Y(`action carries unexpected keys: ${z.join(", ")}`);for(let{name:W}of t)if(K[W]!==H[W])Y(`${W}: signed ${JSON.stringify(K[W])} != submitted ${JSON.stringify(H[W])}`);let f=Object.keys(K),R=f.filter((W)=>!_.includes(W)),V=_.filter((W)=>!f.includes(W));if(R.length||V.length){let W=[R.length?`declares undeclared keys [${R.join(",")}]`:"",V.length?`is missing keys [${V.join(",")}]`:""].filter(Boolean).join(" / ");Y(`message ${W}`)}let P=t.map(({name:W,type:r})=>`${W}:${r}`).join(","),E=(q[O]??[]).map(({name:W,type:r})=>`${W}:${r}`).join(",");if(E!==P)Y(`types.${O} is [${E}], expected [${P}]`);let y=Object.keys(q).filter((W)=>W!==O&&W!=="EIP712Domain");if(y.length)Y(`types carries unexpected entries: ${y.join(", ")}`);if(Number(U.chainId)!==RH)Y(`domain.chainId is ${U.chainId}, expected ${RH} (Arbitrum)`);if(U.name!==S.name)Y(`domain.name is ${JSON.stringify(U.name)}, expected "${S.name}"`);if(U.version!==S.version)Y(`domain.version is ${JSON.stringify(U.version)}, expected "${S.version}"`);if(U.verifyingContract!==k)Y(`domain.verifyingContract is ${U.verifyingContract}, expected the zero address`);let A=Object.keys(U).filter((W)=>!iH.has(W));if(A.length)Y(`domain carries unexpected keys: ${A.join(", ")}`);if(typeof H.signatureChainId!=="string"||H.signatureChainId.toLowerCase()!==w)Y(`action.signatureChainId is ${JSON.stringify(H.signatureChainId)}, expected "${w}"`);if(H.hyperliquidChain!=="Mainnet")Y(`action.hyperliquidChain is ${JSON.stringify(H.hyperliquidChain)}, expected "Mainnet"`);if(typeof H.nonce!=="number"||!Number.isSafeInteger(H.nonce)||H.nonce<=0)Y(`action.nonce is ${JSON.stringify(H.nonce)}, expected a positive safe integer`);if(H.destinationDex!=="")Y(`action.destinationDex is ${JSON.stringify(H.destinationDex)}, expected ""`);if($!==x)Y(`route sell token is ${JSON.stringify($)}, expected "${x}"`);if(H.token!==$)Y(`action.token is ${JSON.stringify(H.token)}, expected route sell token "${$}"`);if(H.sourceDex!==""&&H.sourceDex!=="spot")Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected "" or "spot"`);if(typeof H.sourceDex!=="string"||H.sourceDex!==Z)Y(`action.sourceDex is ${JSON.stringify(H.sourceDex)}, expected route sourceDex ${JSON.stringify(Z)}`);let p=H.fromSubAccount;if(typeof p!=="string"||typeof X!=="string"||p.toLowerCase()!==X.toLowerCase())Y(`action.fromSubAccount is ${JSON.stringify(H.fromSubAccount)}, expected ${JSON.stringify(X)}`);if(X&&!NH.test(X))Y(`expectedFromSubAccount ${JSON.stringify(X)} is not a well-formed 0x address`);if(!G)Y("expectedAmount is missing — cannot verify action.amount");let m=!1;try{m=new oH(String(H.amount)).eqValue(G)}catch{Y(`action.amount ${JSON.stringify(H.amount)} is not comparable to ${G}`)}if(!m)Y(`action.amount ${JSON.stringify(H.amount)} != route sell amount ${G}`);let c=typeof H.destination==="string"?H.destination:"";if(!NH.test(c))Y(`action.destination ${JSON.stringify(H.destination)} is not a well-formed 0x address`);if(!J)Y("expectedDestination is missing — cannot verify action.destination");if(c.toLowerCase()!==J.toLowerCase())Y(`action.destination ${c} != expected destination ${J}`);let GH=UH(Q),d=GH?.origin,JH=M.flatMap((W)=>UH(W)?.origin??[]);if(GH?.protocol!=="https:")Y(`submitTo ${JSON.stringify(Q)} must be an https URL`);if(!d||!JH.includes(d))Y(`submitTo origin ${d} is not one of the allowed exchange origins [${JH.join(", ")}]`)}import{AssetValue as g,Chain as sH,derivationPathToString as nH,getChainConfig as EH,getRPCUrl as tH,NetworkDerivationPath as aH,RequestClient as h,SwapKitError as N,SwapKitNumber as T,updateDerivationPath as eH}from"@swapkit/helpers";import{SwapKitApi as HM}from"@swapkit/helpers/api";import{HDNodeWallet as MM}from"ethers";import{match as GM,P as a}from"ts-pattern";var B=sH.Hype,{baseDecimal:e,rpcUrls:fH}=EH(B),JM=fH[0]?`${fH[0]}/exchange`:void 0,XM={HYPE:e,USDC:6,USDT:6},BH="Mainnet",ZM=/^\d+(?:\.\d+)?$/,$M=/^[^:]+:0x[0-9a-fA-F]+$/,OM={spotSend:[{name:"hyperliquidChain",type:"string"},{name:"destination",type:"string"},{name:"token",type:"string"},{name:"amount",type:"string"},{name:"time",type:"uint64"}]},QM={spotSend:"HyperliquidTransaction:SpotSend"};function L(H,M){if(!xH(H))throw new N(M,{address:H});return H.toLowerCase()}function v(H){if(H===void 0)return;try{return new T(H)}catch{return}}var PH={retry:{maxRetries:0},timeoutMs:5000};async function D({requestOptions:H,...M}){let G=await l();return h.post(`${G}/info`,{json:M,...H})}function HH({dex:H,user:M}){return D({...H?{dex:H}:{},type:"clearinghouseState",user:L(M,"helpers_invalid_params")})}function wH({user:H}){return D({type:"spotClearinghouseState",user:L(H,"helpers_invalid_params")})}function YM({destination:H,sender:M}){let G=L(M,"helpers_invalid_params"),J=L(H,"helpers_invalid_params");return D({requestOptions:PH,source:G,type:"preTransferCheck",user:J})}function WM({dex:H,user:M}){return D({...H?{dex:H}:{},type:"openOrders",user:L(M,"helpers_invalid_params")})}function _M({dex:H,user:M}){return D({...H?{dex:H}:{},type:"frontendOpenOrders",user:L(M,"helpers_invalid_params")})}function CM({oidOrCloid:H,user:M}){return D({oid:H,type:"orderStatus",user:L(M,"helpers_invalid_params")})}function RM({aggregateByTime:H,user:M}){return D({...typeof H==="boolean"?{aggregateByTime:H}:{},type:"userFills",user:L(M,"helpers_invalid_params")})}function NM({aggregateByTime:H,endTime:M,startTime:G,user:J}){return D({...typeof H==="boolean"?{aggregateByTime:H}:{},...typeof M==="number"?{endTime:M}:{},startTime:G,type:"userFillsByTime",user:L(J,"helpers_invalid_params")})}function LH({coin:H,token:M,value:G,spotMeta:J}){if(!G||Number(G)<=0)return null;let X=H?.toUpperCase()||`TOKEN-${M||"UNKNOWN"}`,Z=J?.tokens?.find((C)=>C.name===H||M!==void 0&&C.index===Number(M)),$=Z?.weiDecimals??XM[X]??e,Q=Z?`${B}.${X}-${Z.name}:${Z.tokenId}`:`${B}.${X}`;return new g({decimal:$,identifier:Q,value:G})}function UM(H){let M=new Map;for(let G of H){let J=G.toString({includeSynthProtocol:!0}),X=M.get(J);M.set(J,X?X.add(G):G)}if(![...M.values()].some((G)=>G.isGasAsset||G.ticker==="HYPE")){let G=g.from({chain:B,value:0});M.set(G.toString({includeSynthProtocol:!0}),G)}return[...M.values()]}async function l(){try{return await tH(B)}catch{let[H]=EH(B).rpcUrls;if(!H)throw new N("helpers_chain_no_public_or_set_rpc_url",{chain:B});return H}}async function u(){return`${await l()}/exchange`}function jM(H){let M=QM[H.type],{type:G,...J}=H;return{domain:{chainId:Number.parseInt(H.signatureChainId,16),name:"HyperliquidSignTransaction",verifyingContract:k,version:"1"},message:J,primaryType:M,types:{[M]:OM[G]}}}async function IM({action:H,expiresAfter:M,nonce:G,vaultAddress:J}){let X=G||Date.now(),Z=J?L(J,"helpers_invalid_params"):void 0,$=await u(),Q=_H(H,X,{expiresAfter:M,vaultAddress:Z});return{action:H,endpoint:$,expiresAfter:M,nonce:X,typedData:QH(Q),vaultAddress:Z}}async function TH({action:H,endpoint:M,nonce:G,signatureChainId:J}){let X=G||H.nonce||Date.now(),Z=J||H.signatureChainId||w,$=CH({...H,nonce:X,signatureChainId:Z});return{action:$,endpoint:M??await u(),nonce:X,typedData:YH($)}}async function MH({token:H,user:M}){let G=await wH({user:M}),X=(G.spotState?.balances||G.balances||[]).find(({coin:Q})=>Q&&H.startsWith(`${Q}:`)),Z=v(X?.total||0),$=v(X?.hold||0);return Z&&$?Z.sub($):void 0}async function DH({assetValue:H,sender:M,token:G}){let J=(await MH({token:G,user:M}))?.getValue("string");if(!J||Number(J)<=0)throw new N("toolbox_sweep_amount_too_low",{asset:H.toString(),balance:J||"0"});return J}async function fM(H){if(H.address&&$M.test(H.address))return H.address;let G=(await D({type:"spotMeta"}))?.tokens?.find(({name:J})=>J?.toUpperCase()===H.ticker.toUpperCase());if(G)return`${G.name}:${G.tokenId}`;throw new N("helpers_invalid_params",{asset:H.toString(),message:"Unable to resolve the HyperCore spot token id"})}async function AH({destination:H,sender:M}){let G;try{G=await YM({destination:H,sender:M})}catch(Z){throw new N("toolbox_hypercore_pre_transfer_check_failed",Z)}if(typeof G?.isSanctioned!=="boolean"||typeof G.userExists!=="boolean")throw new N("toolbox_hypercore_pre_transfer_check_failed",{response:G});let{fee:J}=G,X=typeof J==="string"&&ZM.test(J)?Number(J):Number.NaN;if(!Number.isFinite(X))throw new N("toolbox_hypercore_pre_transfer_check_failed",{response:G});if(G.isSanctioned)throw new N("toolbox_hypercore_destination_sanctioned",{destination:H,sender:M});return X}function bH(H){return H.toUpperCase().startsWith("USDC:")}async function yH({activationFee:H,token:M,user:G}){if(H<=0)return;let[J,X]=await Promise.all([HH({user:G}),MH({token:x,user:G})]),Z=v(J.withdrawable||"0")??new T(0),$=X??new T(0);if(new T(H).lte(Z)||new T(H).lte($))return;throw new N("toolbox_hypercore_insufficient_balance",{activationFee:H,feeToken:x,perpsWithdrawable:Z.getValue("string"),spotAvailable:$.getValue("string"),token:M})}async function kH({activationFee:H,amount:M,sourceDex:G,token:J,user:X}){let Z=bH(J),$=Z?new T(M).add(H):new T(M);if(G!==void 0&&G!==""&&G!=="spot")throw new N("helpers_invalid_params",{message:"Unsupported HyperCore sourceDex",sourceDex:G});if(!Z&&G==="")throw new N("helpers_invalid_params",{message:"Only a collateral token can be sent from a perp DEX",sourceDex:G,token:J});let Q="0";if(Z&&G!=="spot"){if(Q=(await HH({user:X})).withdrawable||"0",$.lte(v(Q)??0))return"";if(G==="")throw new N("toolbox_hypercore_insufficient_balance",{amountRequired:$.getValue("string"),perpsWithdrawable:Q,spotAvailable:"0",token:J})}let C=await MH({token:J,user:X})??new T(0);if(C.gte($)){if(!Z)await yH({activationFee:H,token:J,user:X});return"spot"}throw new N("toolbox_hypercore_insufficient_balance",{amountRequired:$.getValue("string"),perpsWithdrawable:Q,spotAvailable:C.getValue("string"),token:J})}async function LM({amount:H,destination:M,sender:G,sourceDex:J,sweep:X,token:Z}){if(X&&J!==void 0&&J!=="spot")throw new N("helpers_invalid_params",{message:"HyperCore sweep drains spot and requires sourceDex spot",sourceDex:J});let $=await AH({destination:M,sender:G});if(!X){let C=await kH({activationFee:$,amount:H,sourceDex:J,token:Z,user:G});return{amount:H,sourceDex:C}}if(!bH(Z))return await yH({activationFee:$,token:Z,user:G}),{amount:H,sourceDex:"spot"};if($<=0)return{amount:H,sourceDex:"spot"};let Q=new T(H).sub($);if(Q.lte(0))throw new N("toolbox_hypercore_insufficient_balance",{activationFee:$,spotAvailable:H,token:Z});return{amount:Q.getValue("string"),sourceDex:"spot"}}async function qM({assetValue:H,recipient:M,sender:G,signatureChainId:J,sweep:X,time:Z,endpoint:$}){let Q=L(M,"core_transaction_invalid_recipient_address"),C=L(G,"core_transaction_invalid_sender_address"),U=H.address;if(!U)throw new N("helpers_invalid_params",{asset:H.toString(),from:C});let K=X?await DH({assetValue:H,sender:C,token:U}):H.getValue("string"),j=$??await u(),q=Z||Date.now(),O={amount:K,destination:Q,hyperliquidChain:BH,signatureChainId:J||w,time:q,token:U,type:"spotSend"};return{action:O,endpoint:j,nonce:q,typedData:jM(O)}}async function qH({assetValue:H,destinationDex:M,endpoint:G,fromSubAccount:J,recipient:X,sender:Z,signatureChainId:$,sourceDex:Q,sweep:C,time:U}){let K=L(X,"core_transaction_invalid_recipient_address"),j=L(Z,"core_transaction_invalid_sender_address"),q=J?L(J,"helpers_invalid_params"):"",O=q||j,_=await fM(H),I=C?await DH({assetValue:H,sender:O,token:_}):H.getValue("string"),{amount:z,sourceDex:f}=await LM({amount:I,destination:K,sender:O,sourceDex:Q,sweep:C,token:_}),R=XH({amount:z,destination:K,destinationDex:M??"spot",fromSubAccount:q,hyperliquidChain:BH,nonce:U||Date.now(),signatureChainId:$||w,sourceDex:f,token:_});return TH({action:R,endpoint:G})}async function SH(H){let M=await h.post(H.endpoint,{json:{action:H.action,...typeof H.expiresAfter==="number"?{expiresAfter:H.expiresAfter}:{},nonce:H.nonce,signature:H.signature,vaultAddress:H.vaultAddress??null},retry:{maxRetries:0}});if(M?.status!=="ok")throw new N("core_transaction_failed",{definitive:M?.status==="err",response:M});return M}async function zH({amount:H,destination:M,nonce:G,token:J,user:X}){let Z=L(X,"helpers_invalid_params"),$=await l(),Q=G-5000,C=M?.toLowerCase(),U=J?.toUpperCase(),K=({delta:j,time:q})=>{if(!(q&&q>=Q&&j?.type==="send"&&j.nonce===G))return!1;if(C&&j?.destination?.toLowerCase()!==C)return!1;let O=v(j?.amount);if(H!==void 0&&!O?.eqValue(H))return!1;if(U!==void 0){if(!j?.token)return!1;let _=j.token.toUpperCase();if(_!==U&&!U.startsWith(`${_}:`))return!1}return!0};for(let j=0;j<8;j++){if(j>0)await new Promise((q)=>setTimeout(q,1500));try{let q=await h.post(`${$}/info`,{json:{startTime:Q,type:"userNonFundingLedgerUpdates",user:Z},...PH}),O=Array.isArray(q)?q.find(K):void 0;if(O?.hash)return O.hash}catch{}}return""}async function FH({kind:H,lookup:M,signed:G}){try{await SH(G)}catch(X){if(X instanceof N&&X.errorKey==="core_transaction_failed"&&X.cause?.definitive===!0)throw X;let $=await zH(M);if($)return $;throw new N("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:M.nonce,transportError:String(X)})}let J=await zH(M);if(!J)throw new N("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 ${H}. Check the account ledger for the transfer first.`,nonce:M.nonce});return J}function VH({action:H,nonce:M,user:G}){return{amount:H.amount,destination:H.destination,nonce:M,token:H.token,user:G}}function xH(H){return H.startsWith("0x")&&KH(H)}function nM(H){let M=H&&"index"in H?H.index||0:0,G=nH(H&&"derivationPath"in H&&H.derivationPath?H.derivationPath:eH(aH[B],{index:M})),J,X=!1;function Z(){if(X)return J;return J=GM(H).with({phrase:a.string},({phrase:O})=>{return MM.fromPhrase(O,void 0,G)}).with({signer:a.not(a.nullish)},({signer:O})=>O).otherwise(()=>{return}),X=!0,J}async function $(){let O=Z();return O?await O.getAddress():""}async function Q(O){let _=Z();if(!_)throw new N("toolbox_hypercore_no_signer");let I=jH(O.typedData),z=await _.signTypedData(I.domain,I.types,I.message);return{action:O.action,endpoint:O.endpoint,nonce:O.nonce,signature:WH(z),..."expiresAfter"in O?{expiresAfter:O.expiresAfter}:{},..."vaultAddress"in O?{vaultAddress:O.vaultAddress}:{}}}async function C(O){let _=L(O,"helpers_invalid_params"),I=await l(),[z,f,R]=await Promise.all([h.post(`${I}/info`,{json:{type:"spotClearinghouseState",user:_}}),h.post(`${I}/info`,{json:{type:"clearinghouseState",user:_}}),h.post(`${I}/info`,{json:{type:"spotMeta"}})]),V=(z.spotState?.balances||z.balances||[]).map(({coin:E,token:y,total:A})=>LH({coin:E,spotMeta:R,token:y,value:A})).filter((E)=>!!E),P=LH({coin:"USDC",spotMeta:R,value:f.withdrawable||f.marginSummary?.accountValue||f.marginSummary?.totalRawUsd});return UM(P?[...V,P]:V)}async function U(O,_=!0){let I=L(O,"helpers_invalid_params");try{let z=await HM.getChainBalance({address:I,chain:B,scamFilter:_});if(z.length){let f=z.map(({identifier:V,value:P,decimal:E})=>new g({decimal:E||e,identifier:V,value:P}));return f.some((V)=>V.isGasAsset)?f:[g.from({chain:B}),...f]}}catch{}return C(I)}async function K({sweep:O,..._}){let I=Z();if(!I)throw new N("toolbox_hypercore_no_signer");let z=_.sender||await I.getAddress(),f=await qH({..._,feeRate:0,sender:z,sweep:O}),R=await Q(f);return FH({kind:"transfer",lookup:VH({action:f.action,nonce:f.nonce,user:f.action.fromSubAccount||z}),signed:R})}async function j(O){let _=Z();if(!_)throw new N("toolbox_hypercore_no_signer");let{action:I,typedData:z,...f}=O,R=structuredClone(I),V=structuredClone(z),P=await _.getAddress(),E=await u(),y=[...new Set([E,JM??E])];IH({...f,action:R,allowedEndpoints:y,typedData:V});let A=R.fromSubAccount?L(R.fromSubAccount,"helpers_invalid_params"):P,p=await AH({destination:R.destination,sender:A});await kH({activationFee:p,amount:R.amount,sourceDex:R.sourceDex,token:R.token,user:A});let m=await Q({action:R,endpoint:E,nonce:R.nonce,typedData:V});return FH({kind:"payin",lookup:VH({action:R,nonce:R.nonce,user:A}),signed:m})}function q(){return g.from({chain:B,value:0})}return{broadcastTransaction:SH,createL1ActionRequest:IM,createSendAssetTransaction:qH,createTransaction:qM,createUserSignedActionRequest:TH,estimateTransactionFee:q,getAddress:$,getBalance:U,getBalanceFromChain:C,getState:{clearinghouse:HH,frontendOpenOrders:_M,openOrders:WM,orderStatus:CM,spotClearinghouse:wH,userFills:RM,userFillsByTime:NM},signAndBroadcastSendAsset:j,signTransaction:Q,transfer:K,validateAddress:xH}}export{xH as validateHyperCoreAddress,nM as getHyperCoreToolbox,TH as createUserSignedActionRequest,qM as createTransaction,qH as createSendAssetTransaction,IM as createL1ActionRequest,DM as buildUsdClassTransferAction,BM as buildUpdateLeverageAction,PM as buildUpdateIsolatedMarginAction,wM as buildTopUpIsolatedOnlyMarginAction,yM as buildTokenDelegateAction,XH as buildSendAssetAction,TM as buildScheduleCancelAction,zM as buildOrderAction,KM as buildModifyAction,VM as buildCancelByCloidAction,FM as buildCancelAction,EM as buildBatchModifyAction,bM as buildApproveBuilderFeeAction,AM as buildApproveAgentAction,x as HYPERCORE_USDC_TOKEN_ID};
1
+ import"../../chunk-qsbf0z90.js";import{q as we}from"../../chunk-1ma8fv42.js";import"../../chunk-s1528ghz.js";import"../../chunk-k50sjysj.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{ga as t}from"../chunk-xbdjxeqd.js";import{AssetValue as W,Chain as o,CosmosChains as x,EVMChains as c,FeeOption as k,SwapKitError as v,UTXOChains as b}from"@swapkit/helpers";async function E(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:i}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:s}=await import("./cosmos/index.js"),{validateHyperCoreAddress:T}=await import("./hypercore/index.js"),{validateSolanaAddress:p}=await import("./solana/index.js"),{validateStarknetAddress:C}=await import("./starknet/index.js"),{validateSuiAddress:h}=await import("./sui/index.js"),{validateTonAddress:u}=await import("./ton/index.js"),{getUTXOAddressValidator:d}=await import("./utxo/index.js"),{validateNearAddress:f}=await import("./near/index.js"),{validateRadixAddress:g}=await import("./radix/index.js"),{validateRippleAddress:w}=await import("./ripple/index.js"),{validateTronAddress:S}=await import("./tron/index.js"),{validateStellarAddress:P}=await import("./stellar/index.js");return function({address:n,chain:A}){return l(A).with(...c,()=>e(n)).with(...b,(m)=>{return d(m)(n)}).with(...x,(m)=>{return s(m)(n)}).with(o.Aleo,()=>r(n)).with(o.Aptos,()=>i(n)).with(o.Radix,()=>g(n)).with(o.Hype,()=>T(n)).with(o.Near,()=>f(n)).with(o.Ripple,()=>w(n)).with(o.Solana,()=>p(n)).with(o.Stellar,()=>P(n)).with(o.Starknet,()=>C(n)).with(o.Sui,()=>h(n)).with(o.Ton,()=>u(n)).with(o.Tron,()=>S(n)).with(o.Cardano,()=>a(n)).otherwise(()=>!1)}}function U(l){return async function(i){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let s=await y(a),T=await s.createTransaction(i),p="feeOptionKey"in i?i.feeOptionKey:k.Fast;return s.estimateTransactionFee({...T,feeOption:p})}).with(o.Bitcoin,o.BitcoinCash,o.Dogecoin,o.Dash,o.Litecoin,o.Solana,o.Ripple,o.Tron,o.Near,o.Cardano,o.Hype,async(a)=>{return(await y(a)).estimateTransactionFee(i)}).with(o.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(i)}).with(o.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(i)}).with(o.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(i)}).with(o.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(o.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(i)}).with(o.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(i)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(i)}).otherwise(async()=>W.from({chain:l}))}}async function y(l,r){let{match:i}=await import("ts-pattern");return i(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-zhn86hw6.js");return await e(l,r)}).with(...b,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(o.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(o.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(o.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(o.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(o.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(o.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(o.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(o.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(o.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(o.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(o.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(o.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(o.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new v("toolbox_not_supported",{chain:l})})}export{y as getToolbox,U as getFeeEstimator,E as getAddressValidator};
1
+ import{ga as t}from"../chunk-k50sjysj.js";import{AssetValue as W,Chain as o,CosmosChains as x,EVMChains as c,FeeOption as k,SwapKitError as v,UTXOChains as b}from"@swapkit/helpers";async function E(){let{match:l}=await import("ts-pattern"),{validateAleoAddress:r}=await import("./aleo/index.js"),{validateAptosAddress:i}=await import("./aptos/index.js"),{validateEVMAddress:e}=await import("./evm/index.js"),{validateCardanoAddress:a}=await import("./cardano/index.js"),{getCosmosAddressValidator:s}=await import("./cosmos/index.js"),{validateHyperCoreAddress:T}=await import("./hypercore/index.js"),{validateSolanaAddress:p}=await import("./solana/index.js"),{validateStarknetAddress:C}=await import("./starknet/index.js"),{validateSuiAddress:h}=await import("./sui/index.js"),{validateTonAddress:u}=await import("./ton/index.js"),{getUTXOAddressValidator:d}=await import("./utxo/index.js"),{validateNearAddress:f}=await import("./near/index.js"),{validateRadixAddress:g}=await import("./radix/index.js"),{validateRippleAddress:w}=await import("./ripple/index.js"),{validateTronAddress:S}=await import("./tron/index.js"),{validateStellarAddress:P}=await import("./stellar/index.js");return function({address:n,chain:A}){return l(A).with(...c,()=>e(n)).with(...b,(m)=>d(m)(n)).with(...x,(m)=>s(m)(n)).with(o.Aleo,()=>r(n)).with(o.Aptos,()=>i(n)).with(o.Radix,()=>g(n)).with(o.Hype,()=>T(n)).with(o.Near,()=>f(n)).with(o.Ripple,()=>w(n)).with(o.Solana,()=>p(n)).with(o.Stellar,()=>P(n)).with(o.Starknet,()=>C(n)).with(o.Sui,()=>h(n)).with(o.Ton,()=>u(n)).with(o.Tron,()=>S(n)).with(o.Cardano,()=>a(n)).otherwise(()=>!1)}}function U(l){return async function(i){let{match:e}=await import("ts-pattern");return e(l).returnType().with(...c,async(a)=>{let s=await y(a),T=await s.createTransaction(i),p="feeOptionKey"in i?i.feeOptionKey:k.Fast;return s.estimateTransactionFee({...T,feeOption:p})}).with(o.Bitcoin,o.BitcoinCash,o.Dogecoin,o.Dash,o.Litecoin,o.Solana,o.Ripple,o.Tron,o.Near,o.Cardano,o.Hype,async(a)=>(await y(a)).estimateTransactionFee(i)).with(o.Aptos,async()=>{let{getAptosToolbox:a}=await import("./aptos/index.js");return a().estimateTransactionFee(i)}).with(o.Aleo,async()=>{let{getAleoToolbox:a}=await import("./aleo/index.js");return a().estimateTransactionFee(i)}).with(o.Starknet,async()=>{let{getStarknetToolbox:a}=await import("./starknet/index.js");return(await a()).estimateTransactionFee(i)}).with(o.Stellar,async()=>{let{getStellarToolbox:a}=await import("./stellar/index.js");return a().estimateTransactionFee()}).with(o.Sui,async()=>{let{getSuiToolbox:a}=await import("./sui/index.js");return a().estimateTransactionFee(i)}).with(o.Ton,async()=>{let{getTONToolbox:a}=await import("./ton/index.js");return a().estimateTransactionFee(i)}).with(...x,async()=>{let{estimateTransactionFee:a}=await import("./cosmos/index.js");return a(i)}).otherwise(async()=>W.from({chain:l}))}}async function y(l,r){let{match:i}=await import("ts-pattern");return i(l).returnType().with(...c,async()=>{let{getEvmToolboxAsync:e}=await import("../chunk-z8n8qjs5.js");return await e(l,r)}).with(...b,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(o.Aleo,async()=>{let{getAleoToolbox:e}=await import("./aleo/index.js");return e(r)}).with(o.Aptos,async()=>{let{getAptosToolbox:e}=await import("./aptos/index.js");return e(r)}).with(o.Hype,async()=>{let{getHyperCoreToolbox:e}=await import("./hypercore/index.js");return e(r)}).with(o.Radix,async()=>{let{getRadixToolbox:e}=await import("./radix/index.js");return e(r)}).with(o.Ripple,async()=>{let{getRippleToolbox:e}=await import("./ripple/index.js");return e(r)}).with(o.Solana,async()=>{let{getSolanaToolbox:e}=await import("./solana/index.js");return e(r)}).with(o.Stellar,async()=>{let{getStellarToolbox:e}=await import("./stellar/index.js");return e(r)}).with(o.Starknet,async()=>{let{getStarknetToolbox:e}=await import("./starknet/index.js");return e(r)}).with(o.Sui,async()=>{let{getSuiToolbox:e}=await import("./sui/index.js");return e(r)}).with(o.Tron,async()=>{let{getTronToolbox:e}=await import("./tron/index.js");return e(r)}).with(o.Near,async()=>{let{getNearToolbox:e}=await import("./near/index.js");return e(r)}).with(o.Cardano,async()=>{let{getCardanoToolbox:e}=await import("./cardano/index.js");return e(r)}).with(o.Ton,async()=>{let{getTONToolbox:e}=await import("./ton/index.js");return e(r)}).otherwise(()=>{throw new v("toolbox_not_supported",{chain:l})})}export{E as getAddressValidator,U as getFeeEstimator,y as getToolbox};
@@ -1 +1 @@
1
- import{fa as qE}from"../../chunk-nvfkjbyq.js";import{ga as Z}from"../../chunk-xbdjxeqd.js";import{Chain as bE,derivationPathToString as KE,SwapKitError as OE}from"@swapkit/helpers";function K(N){return N.length>=2&&N.length<=64&&/^(([a-z\d]+[-_])*[a-z\d]+\.)*([a-z\d]+[-_])*[a-z\d]+$/.test(N)}async function u(N){if(N.derivationPath&&(N.derivationPath[3]||N.derivationPath[4]))throw new OE("toolbox_derivation_slot_unsupported",{chain:bE.Near,derivationPath:N.derivationPath});let{KeyPair:M}=await import("@near-js/crypto"),T=N.derivationPath?KE(N.derivationPath.slice(0,3)):`m/44'/397'/${N.index??0}'`,{parseSeedPhrase:R}=await import("near-seed-phrase"),{secretKey:W}=R(N.phrase,T),q=M.fromString(W);return NE(q)}async function _E(N){let{KeyPair:M}=await import("@near-js/crypto"),T=M.fromString(N);return NE(T)}async function NE(N){let{KeyPairSigner:M}=await import("@near-js/signers");class T extends M{#E;constructor(R){super(R);this.#E=R}getAddress(){let R=this.#E.getPublicKey(),W=Buffer.from(R.data).toString("hex");return Promise.resolve(W)}}return new T(N)}async function l(N,M){let R=(await N.query({account_id:M,finality:"final",request_type:"view_access_key_list"})).keys.find((y)=>y.access_key.permission==="FullAccess");if(!R)throw new OE("toolbox_near_no_public_key_found");let{PublicKey:W}=await import("@near-js/crypto"),q=W.fromString(R.public_key);return{nonce:R.access_key.nonce||0,publicKey:q}}var J={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 CE(N){return"recipient"in N&&"amount"in N&&!("contractId"in N)}function xE(N){return"contractId"in N&&"methodName"in N}function LE(N){return"actions"in N}function ME(N){return"newAccountId"in N}function TE(N){return"contractCode"in N}function RE(N){return"customEstimator"in N}function YE(N){let M=0;for(let T of N)switch(T.enum){case"transfer":M+=Number(J.SIMPLE_TRANSFER);break;case"functionCall":M+=Number(J.CONTRACT_CALL);break;case"createAccount":M+=Number(J.ACCOUNT_CREATION);break;case"deployContract":M+=Number(J.CONTRACT_DEPLOYMENT);break;case"addKey":M+=Number(J.ACCESS_KEY_ADDITION);break;case"deleteKey":M+=Number(J.ACCESS_KEY_DELETION);break;case"stake":M+=Number(J.STAKE);break;default:M+=Number(J.CONTRACT_CALL)}return M.toString()}function QE(N){if(N==="ft_transfer"||N==="ft_transfer_call")return J.TOKEN_TRANSFER;if(N==="storage_deposit")return J.STORAGE_DEPOSIT;return J.CONTRACT_CALL}function lE(N){return(BigInt(N)*BigInt(1000000000000)).toString()}function gE(N){return(BigInt(N)/BigInt(1000000000000)).toString()}async function XE({account:N,contractId:M,viewMethods:T,changeMethods:R}){let{Contract:W}=await import("@near-js/accounts");return new W(N,M,{changeMethods:R,useLocalViewExecution:!0,viewMethods:T})}import{AssetValue as ZE,Chain as G,getRPCUrl as yE,SwapKitError as Q}from"@swapkit/helpers";import{match as $E,P as JE}from"ts-pattern";var WE=1250000000000000000000n,jE=150000000000000n,SE=150000000000000n,PE=250000000000000n,hE=250000000000000n,mE=500n,g=10000n;function rE(N){let M;async function T(){if(M)return M;return M=await $E(N).with({phrase:JE.string},async(E)=>{return await u(E)}).with({signer:JE.any},({signer:E})=>E).otherwise(()=>{return}),M}async function R(){let{JsonRpcProvider:E}=await import("@near-js/providers"),O=await yE(G.Near);return new E({url:O})}async function W(E){let{Account:O}=await import("@near-js/accounts"),_=await R(),C=await T(),x=E||await q();return new O(x,_,C)}async function q(){let E=await T();if(!E)throw new Q("toolbox_near_no_signer");return await E.getAddress()}async function p(E,O){return(O||await R()).callFunction(E.contractId,"storage_balance_of",{account_id:E.accountId},{finality:"final"})}async function y(E,O){try{let _=await O.callFunction(E,"storage_balance_bounds",{},{finality:"final"});return _?.min?BigInt(_.min):WE}catch{return WE}}function S(E){return(E*(g+mE)+g-1n)/g}function d(E,O){return BigInt(E)*BigInt(O.runtime_config.storage_amount_per_byte)}function n(E,O){if(E<=0n)throw new Q({errorKey:"toolbox_sweep_amount_too_low",info:O});return E}async function P(E){return await(E||await R()).experimental_protocolConfig({finality:"final"})}async function UE(E,O,_){let x=await(_||await R()).callFunction(E,"ft_balance_of",{account_id:O},{finality:"final"});return BigInt(x||"0")}async function zE(E){if(!await T())throw new Q("toolbox_near_no_signer");let{assetValue:_,recipient:C,memo:x,sweep:L}=E,Y=await q(),X=await o({assetValue:_,memo:x,recipient:C,sender:Y,sweep:L});return r(X)}async function BE({assetValue:E,attachedDeposit:O,memo:_,provider:C,recipient:x,sender:L,sweep:Y}){let X=E.address;if(!X)throw new Q("toolbox_near_missing_contract_address");let $=await p({accountId:x,contractId:X},C),j=$?0n:await y(X,C),U=$?PE:SE,z=BigInt(O||"1"),F=E.getBaseValue("bigint");if(Y){let[I,f,H,D]=await Promise.all([UE(X,L,C),C.viewAccount(L,{finality:"final"}),P(C),v(C)]);F=n(I,{asset:E.toString(),balance:I.toString()});let V=d(f.storage_usage,H),A=f.amount-V,b=j,EE=(U+($?0n:jE))*S(D)+b+z;if(A<EE)throw new Q("toolbox_sweep_amount_too_low",{asset:E.toString(),availableNear:A.toString(),reason:"Insufficient NEAR to cover token transfer gas and storage deposit",requiredNear:EE.toString()})}let B=[];if(!$)B.push(await k({args:{account_id:x},attachedDeposit:j.toString(),gas:jE.toString(),methodName:"storage_deposit"}));return B.push(await k({args:{amount:F.toString(),memo:_||null,receiver_id:x},attachedDeposit:z.toString(),gas:U.toString(),methodName:"ft_transfer"})),c({actions:B,receiverId:X,sender:L})}async function IE({assetValue:E,attachedDeposit:O,memo:_,provider:C,recipient:x,sender:L,sweep:Y}){let X=E.getBaseValue("bigint");if(Y){let[H,D]=await Promise.all([C.viewAccount(L,{finality:"final"}),P(C)]),V=await a({assetValue:E,memo:_,recipient:x,sweep:Y},D),A=d(H.storage_usage,D),b=0n;if(_&&O){let e=await v(C);b=hE*S(e)+BigInt(O)}X=n(H.amount-V.getBaseValue("bigint")-A-b,{asset:E.toString(),balance:H.amount.toString(),fee:V.getBaseValue("bigint").toString(),storageStakeReserve:A.toString()})}let[{publicKey:$,nonce:j},U,{actionCreators:z,createTransaction:F},{baseDecode:B}]=await Promise.all([l(C,L),C.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),I=[z.transfer(X)];if(_&&O)I.push(z.functionCall("memo",{memo:_},BigInt("250000000000000"),BigInt(O)));let f=B(U.header.hash);return F(L,$,x,j+1,I,f)}async function o({recipient:E,assetValue:O,memo:_,attachedDeposit:C,sender:x,functionCall:L,sweep:Y}){if(!K(E))throw new Q("toolbox_near_invalid_address",{recipient:E});if(!K(x))throw new Q("toolbox_near_invalid_address",{sender:x});if(L)return i({...L,sender:x});if(Y&&!await T())throw new Q("toolbox_near_no_signer");let X=await R(),$={assetValue:O,attachedDeposit:C,memo:_,provider:X,recipient:E,sender:x,sweep:Y};return O.isGasAsset?IE($):BE($)}function FE(E){let O=E.encode();return Buffer.from(O).toString("base64")}async function i({args:E,attachedDeposit:O,contractId:_,gas:C,methodName:x,sender:L}){let Y=await k({args:E,attachedDeposit:O,gas:C,methodName:x});return c({actions:[Y],receiverId:_,sender:L})}async function c({actions:E,receiverId:O,sender:_}){let C=await R(),[{publicKey:x,nonce:L},Y,{createTransaction:X},{baseDecode:$}]=await Promise.all([l(C,_),C.block({finality:"final"}),import("@near-js/transactions"),import("@near-js/utils")]),j=$(Y.header.hash);return X(_,x,O,L+1,E,j)}async function k(E){let{actionCreators:O}=await import("@near-js/transactions");return O.functionCall(E.methodName,Buffer.from(JSON.stringify(E.args)),BigInt(E.gas),BigInt(E.attachedDeposit))}async function t(E){let O=await T();if(!O)throw new Q("toolbox_near_no_signer");await fE(E);let[_,C]=await O.signTransaction(E);return C}async function fE(E){let O=E.publicKey;if(O.toString?.().startsWith("ed25519:")||O.toString?.().startsWith("secp256k1:"))return;let{KeyType:_,PublicKey:C}=await import("@near-js/crypto"),x=O.data||O.ed25519Key?.data,L=O.secp256k1Key?.data;if(x){E.publicKey=new C({data:Uint8Array.from(x),keyType:_.ED25519});return}if(L)E.publicKey=new C({data:Uint8Array.from(L),keyType:_.SECP256K1})}function h(E){if(typeof E==="string")return E;if(Array.isArray(E))return E.map(h).find(Boolean);if(!(E&&typeof E==="object"))return;let O=E;return O.transaction?.hash||O.transaction_outcome?.id}function m(E){return E instanceof Error?E.message:String(E)}async function s(E){let _=await(await R()).sendTransaction(E),C=h(_);if(!C)throw new Q("toolbox_near_transfer_failed",{result:_});return C}async function r(E){let O=await T();if(!O)throw new Q("toolbox_near_no_signer");let _;try{_=await t(E)}catch(C){let x;try{x=O.signAndSendTransaction?await O.signAndSendTransaction({actions:E.actions,receiverId:E.receiverId,signerId:E.signerId}):await O.signAndSendTransactions?.({transactions:[E]})}catch(Y){throw new Q({errorKey:"toolbox_near_sign_transaction_failed",info:{directSignError:m(C),signAndSendError:m(Y)}},Y)}let L=h(x);if(L)return L;throw C}return s(_)}async function a(E,O){let _=await T();if("assetValue"in E){if(E.sweep&&!_)throw new Q("toolbox_near_no_signer");try{let[x,L]=await Promise.all([v(),O?Promise.resolve(O):P()]),{runtime_config:Y}=L,{execution:X,send_sir:$}=Y.transaction_costs.action_receipt_creation_config,{execution:j,send_sir:U}=Y.transaction_costs.action_creation_config.transfer_cost,z=BigInt(U)+BigInt(j),F=BigInt($)+BigInt(X),B=z+F,I=E.sweep?S(x):x,f=B*I;return ZE.from({chain:G.Near,value:f})}catch(x){throw new Q({errorKey:"toolbox_fee_estimation_failed",info:{chain:G.Near,message:m(x)}},x)}}let C=_?await W():void 0;return w(E,C)}async function v(E){let _=await(E||await R()).gasPrice(null);return BigInt(_.gas_price)}async function HE(E,O,_){if(!await T())throw new Q("toolbox_near_no_signer");let x=await W(),{formatNearAmount:L}=await import("@near-js/utils"),{PublicKey:Y}=await import("@near-js/crypto"),X=L(_)||"0";return(await x.createAccount(E,Y.fromString(O),BigInt(X))).transaction.hash}async function AE(E){let O=await T();try{if(!O)throw new Q("toolbox_near_no_signer");let{actionCreators:_}=await import("@near-js/transactions"),{contractId:C,methodName:x,args:L,deposit:Y}=E,X=await W(),$=await w({args:L||{},contractId:C,methodName:x}),j=_.functionCall(x,L||{},$.getBaseValue("bigint"),BigInt(Y||"1"));return(await X.signAndSendTransaction({actions:[j],receiverId:C})).transaction_outcome.id}catch(_){throw new Q("toolbox_near_transfer_failed",{error:_})}}async function GE(E){let O=await W();return XE({account:O,changeMethods:E.changeMethods,contractId:E.contractId,viewMethods:E.viewMethods})}async function kE(E){if(!await T())throw new Q("toolbox_near_no_signer");if(E.actions.length===0)throw new Q("toolbox_near_empty_batch");return(await(await W()).signAndSendTransaction({actions:E.actions,receiverId:E.receiverId})).transaction.hash}async function w(E,O){let _=await $E(E).when(CE,()=>J.SIMPLE_TRANSFER).when(xE,(x)=>QE(x.methodName)).when(LE,(x)=>YE(x.actions)).when(ME,()=>J.ACCOUNT_CREATION).when(TE,()=>J.CONTRACT_DEPLOYMENT).when(RE,(x)=>{if(!O)throw new Q("toolbox_near_no_account");return x.customEstimator(O)}).otherwise(()=>{throw new Q("toolbox_near_invalid_gas_params")}),C=BigInt(_)*BigInt(1000000000000);return ZE.from({chain:G.Near,value:C})}function wE(E,O){return console.warn("NEAR toolbox: estimateGas is deprecated, use estimateGasLimit instead"),w(E,O)}async function DE(){let E=await R();try{return(await E.gasPrice(null)).gas_price||"100000000"}catch{return"100000000"}}async function VE(){let E=await T();return E?(await E.getPublicKey()).toString():""}return{broadcastTransaction:s,callFunction:AE,createAction:k,createContract:GE,createContractFunctionCall:i,createSubAccount:HE,createTransaction:o,estimateGas:wE,estimateGasLimit:w,estimateTransactionFee:a,executeBatchTransaction:kE,getAddress:q,getBalance:qE(G.Near),getGasPrice:DE,getNearProvider:R,getPublicKey:VE,getSignerFromPhrase:u,getSignerFromPrivateKey:_E,serializeTransaction:FE,signAndBroadcastTransaction:r,signTransaction:t,transfer:zE,validateAddress:K}}export{K as validateNearAddress,lE as tgasToGas,CE as isSimpleTransfer,RE as isCustomEstimator,TE as isContractDeployment,xE as isContractCall,LE as isBatchTransaction,ME as isAccountCreation,rE as getNearToolbox,_E as getNearSignerFromPrivateKey,u as getNearSignerFromPhrase,l as getFullAccessPublicKey,QE as getContractMethodGas,gE as gasToTGas,YE as estimateBatchGas,XE as createNearContract,J as GAS_COSTS};
1
+ import{fa as wt}from"../../chunk-s1528ghz.js";import{ga as l}from"../../chunk-k50sjysj.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 +1 @@
1
- import{ga as Y}from"../../chunk-xbdjxeqd.js";import{AssetValue as Z,Chain as X,SKConfig as $,SwapKitError as q}from"@swapkit/helpers";function G(H){return H.startsWith("account_rdx1")&&H.length===66}async function v({address:H,networkApi:L}){let J=!0,U,M=[],j=await I(L);while(J){let O={address:H,at_ledger_state:{state_version:j},cursor:U,limit_per_page:100},K=await L.state.innerClient.entityFungiblesPage({stateEntityFungiblesPageRequest:O});if(M=M.concat(K.items),K.next_cursor)U=K.next_cursor;else J=!1}return M}async function x({resources:H,networkApi:L}){let J=[],U=50,M=[];for(let j=0;j<H.length;j+=50)M.push(H.slice(j,j+50));for(let j of M){let O=j.map((z)=>z.resource_address),K=await L.state.getEntityDetailsVaultAggregated(O),V=new Map;for(let z of K)if(z.details!==void 0){let Q=z.metadata?.items.find((_)=>_.key==="symbol"),W=Q?.value.typed.type==="String"?Q.value.typed.value:"?";if(z.details.type==="FungibleResource")V.set(z.address,{decimals:z.details.divisibility,symbol:W})}for(let z of j)if(z.aggregation_level==="Global"){let Q=V.get(z.resource_address)||{decimals:0,symbol:"?"},W=Z.from({asset:Q.symbol!==X.Radix?`${X.Radix}.${Q.symbol}-${z.resource_address}`:"XRD.XRD",value:z.amount});J.push(W)}}return J}async function I(H){return(await H.status.getCurrent()).ledger_state.state_version}function T({dappConfig:H}={}){let L=H||$.get("integrations").radix,J;async function U(){if(J)return J;let{GatewayApiClient:j}=await import("@radixdlt/babylon-gateway-api-sdk"),{RadixDappToolkit:O}=await import("@radixdlt/radix-dapp-toolkit"),K=O({...L,networkId:L.network?.networkId||1});return J=j.initialize(K.gatewayApi.clientConfig),J}async function M(j){let O=await U(),K=await v({address:j,networkApi:O}),V=await x({networkApi:O,resources:K});if(!V.some((Q)=>Q.isGasAsset))return[Z.from({chain:X.Radix}),...V];return V}return{getAddress:()=>"",getBalance:M,getNetworkApi:U,signAndBroadcast:()=>{throw new q("toolbox_radix_method_not_supported",{method:"signAndBroadcast"})},validateAddress:G}}export{G as validateRadixAddress,T as getRadixToolbox};
1
+ import{ga as p}from"../../chunk-k50sjysj.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};