@swapkit/toolboxes 6.2.0 → 6.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- package/dist/src/lightspark/index.js +1 -0
- package/dist/src/starknet/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/types/cardano/helpers.d.ts +15 -0
- package/dist/types/cardano/index.d.ts +1 -0
- package/dist/types/lightspark/__tests__/vendorMissing.probe.d.ts +1 -0
- package/dist/types/lightspark/helpers.d.ts +13 -0
- package/dist/types/lightspark/index.d.ts +3 -0
- package/dist/types/lightspark/invoiceAssert.d.ts +18 -0
- package/dist/types/lightspark/toolbox.d.ts +13 -0
- package/dist/types/lightspark/types.d.ts +196 -0
- package/dist/types/starknet/types.d.ts +1 -0
- package/dist/types/stellar/index.d.ts +1 -1
- package/dist/types/stellar/toolbox.d.ts +2 -2
- package/dist/types/stellar/types.d.ts +5 -1
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#373](https://github.com/swapkit/sdk/pull/373) [`218e46d`](https://github.com/swapkit/sdk/commit/218e46d12d423e0420143ec410f0a4c8d102ab8d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Add a standalone Lightning toolbox backed by Lightspark at `@swapkit/toolboxes/lightspark`, re-exported from `@swapkit/server`. It ships with no `Chain` enum member and no core or wallet wiring.
|
|
8
|
+
- [#449](https://github.com/swapkit/sdk/pull/449) [`e105e04`](https://github.com/swapkit/sdk/commit/e105e0417e77c486406706ecf1c0ed12c77c4375) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The Starknet toolbox uses a wallet-provided account only to sign and send. Network reads and fee estimates go through the configured Starknet RPC, so wallets that bundle an older starknet.js (such as OKX Wallet) no longer fail with `getClassHashAt` of undefined or an "Invalid block id" error.
|
|
9
|
+
- [#373](https://github.com/swapkit/sdk/pull/373) [`218e46d`](https://github.com/swapkit/sdk/commit/218e46d12d423e0420143ec410f0a4c8d102ab8d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Add the `toolbox_lightspark_*` block (91301 to 91313) to `SwapKitError.ErrorCode` for the new Lightning toolbox: `toolbox_lightspark_missing_credentials`, `toolbox_lightspark_invalid_invoice`, `toolbox_lightspark_invoice_amount_mismatch`, `toolbox_lightspark_invoice_destination_mismatch`, `toolbox_lightspark_invoice_expired`, `toolbox_lightspark_invoice_already_settled`, `toolbox_lightspark_fee_limit_exceeded`, `toolbox_lightspark_invalid_params`, `toolbox_lightspark_api_error`, `toolbox_lightspark_invalid_amount`, `toolbox_lightspark_invalid_destination`, `toolbox_lightspark_network_mismatch` and `toolbox_lightspark_signing_key_unavailable`. An unloadable node signing key is reported as `toolbox_lightspark_signing_key_unavailable`, distinct from `toolbox_lightspark_missing_credentials`, so an integrator branching on the code can tell an unloaded key from an absent credential. (via @swapkit/helpers@6.2.0)
|
|
10
|
+
- [#447](https://github.com/swapkit/sdk/pull/447) [`b827853`](https://github.com/swapkit/sdk/commit/b827853cd1bfa68a9bd733843b3740f10ecab359) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.2.0)
|
|
11
|
+
|
|
12
|
+
## 6.3.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- [#444](https://github.com/swapkit/sdk/pull/444) [`d9f486d`](https://github.com/swapkit/sdk/commit/d9f486d8197c13523934e6524bdcd9e3371fdebb) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Export Cardano transaction helpers from `@swapkit/toolboxes/cardano` so hardware and browser wallets can reuse them, and sign keystore transactions over the body exactly as received instead of a re-encoded copy. `decodeCardanoWitnessSet` turns the signatures a CIP-30 wallet returns into the list `addCardanoVkeyWitnesses` accepts.
|
|
17
|
+
- [#439](https://github.com/swapkit/sdk/pull/439) [`92e68f2`](https://github.com/swapkit/sdk/commit/92e68f28a36915bf35fa3b9ddb4d249f035a522c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Allow the Stellar toolbox to use an external signer, so hardware wallets can sign Stellar transactions without exposing a seed phrase.
|
|
18
|
+
- [#440](https://github.com/swapkit/sdk/pull/440) [`ab0cc3d`](https://github.com/swapkit/sdk/commit/ab0cc3d80439fd1541616bfc0cdf8e8798c06590) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Keep THORChain and Maya balances loading when the account holds a denom `AssetValue` cannot parse. Secured assets such as `btc-btc` threw inside `getBalance`, which rejected the whole call and left RUNE and every other balance of the chain empty. Those denoms are now skipped and the rest are returned.
|
|
19
|
+
- [#445](https://github.com/swapkit/sdk/pull/445) [`0e9f9ee`](https://github.com/swapkit/sdk/commit/0e9f9ee3e9c6769ded65394d5aef2e3704c7e7a7) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - TON now uses Toncenter (`https://toncenter.com/api/v2/jsonRPC`) as its default RPC and goes through the same health-checked `rpcUrls` fallback as other chains. Orbs node discovery is only used when every configured TON RPC fails, so an Orbs outage no longer breaks TON addresses, fees or transfers. The TON RPC health check now calls `getMasterchainInfo`; the previous `getAddressInformation` call with an empty address was rejected by every node.
|
|
20
|
+
- [#447](https://github.com/swapkit/sdk/pull/447) [`b827853`](https://github.com/swapkit/sdk/commit/b827853cd1bfa68a9bd733843b3740f10ecab359) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.1.2)
|
|
21
|
+
- [#443](https://github.com/swapkit/sdk/pull/443) [`81b8303`](https://github.com/swapkit/sdk/commit/81b83032429f8e2bd496335d252563dd4a69a60f) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Solana's default derivation path is now `m/44'/501'/0'/0'` (four hardened levels) instead of a five-level BIP44 shape. Keystore and passkey already derived this path by trimming the default, so their addresses do not change. `getSolanaToolbox({ phrase })` without an explicit `derivationPath` now derives the same address as the keystore, Phantom and Trezor Suite, which moves the address for anyone relying on that fallback. Hardware wallets that read `NetworkDerivationPath[Chain.Solana]` now receive a path the device firmware accepts. (via @swapkit/helpers@6.1.2)
|
|
22
|
+
|
|
3
23
|
## 6.2.0
|
|
4
24
|
|
|
5
25
|
### Minor Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ja as
|
|
1
|
+
import{ja as C}from"../../chunk-exyqap7m.js";import{hex as W}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";var V=0,it=258;function w(t){return new st("toolbox_cardano_sign_transaction_failed",{message:t})}async function q(t){let{Decoder:e}=await import("@stricahq/cbors"),n=Buffer.from(W.decode(t)),{value:s}=e.decode(n);if(!Array.isArray(s)||s.length!==4)throw w("Invalid Cardano transaction");let[a,i]=s;if(!(a instanceof Map)||!(i instanceof Map))throw w("Invalid Cardano transaction");return{body:a,bytes:n,witnessSet:i}}async function G(t){let{crypto:e}=await import("@stricahq/typhonjs"),{body:n,bytes:s}=await q(t),[a,i]=n.getByteSpan();return{body:n,bodyHash:e.hash32(s.subarray(a,i)).toString("hex")}}async function Y(t,e){let{Encoder:n}=await import("@stricahq/cbors"),{bytes:s,witnessSet:a}=await q(t),i=a.get(V)??[];if(!Array.isArray(i))throw w("Unsupported Cardano witness set");let r=e.map(({publicKey:l,signature:p})=>[Buffer.from(l),Buffer.from(p)]);a.set(V,[...i,...r]);let[c,d]=a.getByteSpan();return Buffer.concat([s.subarray(0,c),n.encode(a),s.subarray(d)]).toString("hex")}async function Pt(t){let{CborTag:e,Decoder:n}=await import("@stricahq/cbors"),{value:s}=n.decode(Buffer.from(W.decode(t)));if(!(s instanceof Map))throw w("Invalid Cardano witness set");if([...s.keys()].some((r)=>r!==V))throw w("Unsupported Cardano witness set");let a=s.get(V),i=a instanceof e&&a.tag===it?a.value:a;if(!Array.isArray(i)||i.length===0)throw w("Cardano witness set has no signatures");return i.map((r)=>{let[c,d]=Array.isArray(r)?r:[];if(!(c instanceof Uint8Array&&d instanceof Uint8Array))throw w("Invalid Cardano witness");if(c.length!==32||d.length!==64)throw w("Invalid Cardano witness");return{publicKey:Uint8Array.from(c),signature:Uint8Array.from(d)}})}async function Tt(t){let{utils:e}=await import("@stricahq/typhonjs");try{return e.getAddressFromHex(Buffer.from(t)).getBech32()}catch(n){throw w(`Invalid Cardano address: ${String(n)}`)}}async function xt(t){let{crypto:e}=await import("@stricahq/typhonjs");return e.hash28(Buffer.from(t))}import{bech32 as ct}from"@scure/base";import{mnemonicToEntropy as ut}from"@scure/bip39";import{wordlist as dt}from"@scure/bip39/wordlists/english.js";import{AssetValue as B,Chain as _,getChainConfig as lt,SwapKitError as g}from"@swapkit/helpers";import f from"bignumber.js";var J="mainnet3YT7XK6NidLPlkHxxyBB5V0WzXUOTIJS",Q="https://cardano-mainnet.blockfrost.io/api/v0",H=2147483648;async function O(t,e){let n=await fetch(`${Q}${t}`,{...e,headers:{project_id:J,...e?.headers}});if(!n.ok)throw Error(`Blockfrost API error: ${n.status} ${n.statusText}`);return n.json()}async function Z(t){try{return await O(`/addresses/${t}/utxos`)}catch{return[]}}async function pt(){return(await O("/blocks/latest")).slot}async function mt(){let t=await O("/epochs/latest/parameters"),e={PlutusScriptV1:t.cost_models.PlutusV1?Object.values(t.cost_models.PlutusV1):[],PlutusScriptV2:t.cost_models.PlutusV2?Object.values(t.cost_models.PlutusV2):[],PlutusScriptV3:t.cost_models.PlutusV3?Object.values(t.cost_models.PlutusV3):[]};return{collateralPercent:new f(t.collateral_percent),languageView:e,maxValueSize:Number.parseInt(t.max_val_size,10),minFeeA:new f(t.min_fee_a),minFeeB:new f(t.min_fee_b),minFeeRefScriptCostPerByte:new f(15),priceMem:new f(t.price_mem),priceSteps:new f(t.price_step),stakeKeyDeposit:new f(2000000),utxoCostPerByte:new f(t.coins_per_utxo_size)}}async function X(t){let e=await fetch(`${Q}/tx/submit`,{body:Buffer.from(t,"hex"),headers:{"Content-Type":"application/cbor",project_id:J},method:"POST"});if(!e.ok){let n=await e.text();throw Error(`Transaction submission failed: ${n}`)}return e.json()}function ft(t,e){return t.map((n)=>{let s=n.amount.find((r)=>r.unit==="lovelace"),a=s?new f(s.quantity):new f(0),i=n.amount.filter((r)=>r.unit!=="lovelace").map((r)=>({amount:new f(r.quantity),assetName:r.unit.slice(56),policyId:r.unit.slice(0,56)}));return{address:e,amount:a,index:n.output_index,tokens:i,txId:n.tx_hash}})}function yt({TransactionConstructor:t,auxiliaryData:e,bufferedParams:n,currentSlot:s,inputs:a,recipientAddress:i}){let r=a.reduce((o,u)=>o.plus(u.amount),new f(0));if(!r.isPositive())throw new g({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString()}});let c=new t({protocolParams:n});for(let o of a)c.addInput(o);if(c.addOutput({address:i,amount:r,tokens:[]}),c.setTTL(s+3600),e)c.setAuxiliaryData(e);c.setFee(c.calculateFee());let d=c.getFee(),l=r.minus(d),p={address:i,amount:l,tokens:[]},b=c.calculateMinUtxoAmountBabbage(p);if(!l.isPositive()||l.lt(b))throw new g({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString(),fee:d.toString(),minimumOutput:b.toString()}});return new t({protocolParams:n}).paymentTransaction({auxiliaryData:e,changeAddress:i,inputs:a,outputs:[p],ttl:s+3600})}async function gt(t){try{let e=await Z(t),n=0n,s=new Map;for(let r of e){if(!r.amount||!Array.isArray(r.amount))continue;for(let c of r.amount){let{unit:d,quantity:l}=c;if(d==="lovelace")n+=BigInt(l);else{let p=s.get(d)||0n;s.set(d,p+BigInt(l))}}}let a=[],{baseDecimal:i}=lt(_.Cardano);if(n>0n)a.push(B.from({chain:_.Cardano,fromBaseDecimal:i,value:n.toString()}));for(let[r,c]of s)a.push(B.from({asset:`${_.Cardano}.${r}`,value:c.toString()}));if(a.length===0)return[B.from({chain:_.Cardano})];return a}catch(e){let n=e instanceof Error?e.message:String(e);return console.error(`Cardano balance fetch error: ${n}`),[B.from({chain:_.Cardano})]}}function ht(t){if(!t||typeof t!=="string")return!1;try{let e=ct.decode(t,120);return e.prefix==="addr"||e.prefix==="addr_test"}catch{return!1}}async function wt(t,e=0,n=0){let{Bip32PrivateKey:s}=await import("@stricahq/bip32ed25519"),{types:a,address:i,crypto:r}=await import("@stricahq/typhonjs"),c=ut(t,dt),l=(await s.fromEntropy(Buffer.from(Array.from(c)))).derive(H+1852).derive(H+1815).derive(H+e),p=l.derive(0).derive(n),b=p.toBip32PublicKey().toPublicKey().toBytes(),k=r.hash28(b),u=l.derive(2).derive(0).toBip32PublicKey().toPublicKey().toBytes(),m=r.hash28(u),P={hash:k,type:a.HashType.ADDRESS},T={hash:m,type:a.HashType.ADDRESS},v=new i.BaseAddress(a.NetworkId.MAINNET,P,T).getBech32(),K=p.toPrivateKey();return{getAddress:()=>v,publicKey:b,publicKeyHash:k,signTransaction:async(S)=>{try{let{bodyHash:A}=await G(S),I=K.sign(Buffer.from(A,"hex"));return await Y(S,[{publicKey:b,signature:I}])}catch(A){if(A instanceof g)throw A;throw new g("toolbox_cardano_sign_transaction_failed",{message:String(A)})}}}}function Vt(t){let e,n,s;async function a(){if(!s)s=await mt();return s}async function i(){if(e!==void 0)return e;if(t&&"phrase"in t&&t.phrase){let{derivationPath:o}=t;if(o&&(o.length!==5||o[3]!==0||o[4]===void 0))throw new g("toolbox_derivation_slot_unsupported",{chain:_.Cardano,derivationPath:o});let u=o?.[2]??0,m=o?.[4]??t.index??0;return e=await wt(t.phrase,u,m),e}if(t&&"signer"in t&&t.signer)return e=t.signer,e;return}async function r(){if(n)return n;let o=await i();if(!o)return"";if("getAddress"in o)return n=await o.getAddress(),n;return""}async function c(o){let u=o||await r();if(!u)throw new g("core_wallet_connection_not_found");return gt(u)}async function d(o){if(o)try{let{tx:T}=await l(o),x=T.getFee();return B.from({chain:_.Cardano,fromBaseDecimal:6,value:x.toString()})}catch{}let u=await a(),m=400,P=u.minFeeB.plus(u.minFeeA.times(m));return B.from({chain:_.Cardano,fromBaseDecimal:6,value:P.toString()})}async function l({sender:o="",recipient:u,assetValue:m,memo:P,pureLovelaceOnly:T=!1,sweep:x=!1}){let{Transaction:v,utils:K}=await import("@stricahq/typhonjs"),S=o||await r();if(!S)throw new g("core_wallet_connection_not_found");let[A,I,D]=await Promise.all([Z(S),pt(),a()]);if(x&&!m.isGasAsset)throw new g({errorKey:"toolbox_not_supported",info:{asset:m.toString(),chain:_.Cardano,feature:"token_sweep"}});let U=x&&m.isGasAsset,tt=T||U,et=A.filter((y)=>tt?y.amount.some((h)=>h.unit==="lovelace")&&y.amount.every((h)=>h.unit==="lovelace"):y.amount.some((h)=>h.unit==="lovelace")).sort((y,h)=>{let z=y.amount.some((F)=>F.unit!=="lovelace"),ot=h.amount.some((F)=>F.unit!=="lovelace");if(z===ot)return 0;return z?1:-1}),M=K.getAddressFromString(S),R=K.getAddressFromString(u),L=ft(et,M),E;if(P){let y=new Map;y.set("msg",[P]),E={metadata:[{data:y,label:674}]}}let j={...D,minFeeB:D.minFeeB.plus(D.minFeeA.times(4))};if(U){let y=yt({auxiliaryData:E,bufferedParams:j,currentSlot:I,inputs:L,recipientAddress:R,TransactionConstructor:v}),{payload:h}=y.buildTransaction();return{tx:y,unsignedTx:h}}let nt=new f(m.getBaseValue("string")),rt=[{address:R,amount:nt,tokens:[]}],N=new v({protocolParams:j}).paymentTransaction({auxiliaryData:E,changeAddress:M,inputs:L,outputs:rt,ttl:I+3600}),{payload:at}=N.buildTransaction();return{tx:N,unsignedTx:at}}async function p(o){let u=await i();if(!u||!("signTransaction"in u))throw new g("core_wallet_connection_not_found");return u.signTransaction(o)}async function b({recipient:o,assetValue:u,memo:m,sweep:P}){let T=await i();if(!T||!("signTransaction"in T))throw new g("core_wallet_connection_not_found");let{unsignedTx:x}=await l({assetValue:u,memo:m,recipient:o,sender:await r(),sweep:P}),v=await p(x);return await X(v)}async function k(o){let u=await p(o);return await X(u)}return{createTransaction:l,estimateTransactionFee:d,getAddress:r,getBalance:c,signAndBroadcastTransaction:k,signTransaction:p,transfer:b,validateAddress:ht}}export{Y as addCardanoVkeyWitnesses,G as decodeCardanoTransaction,Pt as decodeCardanoWitnessSet,Tt as getCardanoAddressFromBytes,xt as getCardanoPublicKeyHash,Vt as getCardanoToolbox,ht as validateCardanoAddress};
|
package/dist/src/cosmos/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-exyqap7m.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},At={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return wt;case g.Noble:return At;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let A=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),w=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,w),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:A,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:A,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:A,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,A=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((w)=>({amount:w.amount,denom:w.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,A,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,A){let S=A??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let A=await s(c),S=await e.signWithRegistry(c,a,p,h,A),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,A=c||h?await _(await pt(a)):void 0,S=h&&A?await Mt({client:A,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,w=U(r.symbol),C=r;if(c){if(!A)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await A.getAllBalances(i),denom:w,feeAmount:mn(b.amount,w)})}let T={amount:[{amount:C.getBaseValue("string"),denom:w}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),A=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?A:R(A),a):A;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),A=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[A],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as wn}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as An,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function A(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:w=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[w],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let y=await Sn(i)(m),b=await Promise.all(y.filter(({denom:w})=>w&&!w.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&w.split("-").length>2)).map(({denom:w,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(w.includes("/")||w.includes("˜"))?`${i}.${w}`:w;return In(T,C)}));if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:A,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:An.fromBigInt(BigInt(t),n),fast:An.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:An.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=wn.decode(n);return wn.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function we(i){return B.encode(i)}function Ae(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,A=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(A,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:we(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),A=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:A,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),w=F(i,r),C=await L(l,y,{aminoTypes:w,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:w,signingClient:C}=await p(),T=(await w.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function A(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:w}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=w?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),w=(await y.getAccounts())?.[0]?.address;if(!w)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(w,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:A,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:Ae(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,wt as DEFAULT_KUJI_FEE_MAINNET,At as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
|
|
1
|
+
import"../../chunk-exyqap7m.js";import{base64 as z,bech32 as Y}from"@scure/base";import{SwapKitError as st}from"@swapkit/helpers";function X(i){return z.encode(Uint8Array.from(Y.fromWords(Y.decode(i).words)))}function Q(i,o="thor"){return Y.encode(o,Y.toWords(z.decode(i)))}function ve(i){return z.encode(i)}function De(i){if(!i.match(/^[a-zA-Z0-9+/]*={0,2}$/))throw new st("toolbox_cosmos_invalid_params",{error:"Invalid base64 string format"});return z.decode(i)}import{encodeMessage as Ft,encodeTxBody as It}from"@swapkit/cosmos-signer";import{AssetValue as Rt,Chain as en,getChainConfig as Kn,getRPCUrl as yn,SwapKitError as gn}from"@swapkit/helpers";import{base64 as ln}from"@scure/base";import{broadcastTx as Z,getAccount as Dn,getBalances as ct,createTendermintRpc as at,defaultEncoders as ut,encodeAuthInfo as Pn,encodeMessage as lt,encodePubkey as ft,encodeTxBody as dt,encodeTxRaw as vn,makeStdSignDoc as mt}from"@swapkit/cosmos-signer";import{AssetValue as fn,Chain as g,getChainConfig as D,getRPCUrl as pt,RequestClient as yt,SKConfig as gt,SwapKitError as P,SwapKitNumber as dn}from"@swapkit/helpers";var Mn="FACTORY/KUJIRA1QK00H5ATUTPSV900X202PXX42NPJR9THG58DNQPA72F2P7M2LUASE444A7/UUSK",ht="FACTORY/KUJIRA1YGFXN0ER40KLCNCK8THLTUPRDXLCK6WVNPKF2K/UYUM",bt={amount:[{amount:"500",denom:"uatom"}],gas:"200000"},At={amount:[{amount:"1000",denom:"ukuji"}],gas:"200000"},wt={amount:[{amount:"1000",denom:"uusdc"}],gas:"200000"};function M(i){switch(i){case g.Maya:return{amount:[],gas:"10000000000"};case g.THORChain:return{amount:[],gas:"500000000"};case g.Kujira:return At;case g.Noble:return wt;default:return bt}}async function nn(i){let o=gt.get("thornodeUrls"),r=i===g.Maya,t=`${o[i]}/${r?"mayachain":"thorchain"}/constants`,e=D(i).baseDecimal;try{let{int_64_values:{NativeTransactionFee:s}}=await yt.get(t);if(!Number.isInteger(s)||s<=0)throw new P("toolbox_cosmos_invalid_fee",{nativeFee:s.toString()});return dn.fromBigInt(BigInt(s),e)}catch{let s=r?10000000000n:2000000n;return dn.fromBigInt(s,e)}}var U=(i,o=!1)=>{if(o)return i.toLowerCase();switch(i){case"uUSK":case"USK":return Mn;case"uYUM":case"YUM":return ht;case"uKUJI":case"KUJI":return"ukuji";case"ATOM":case"uATOM":return"uatom";case"uUSDC":case"USDC":case"NOBLE":return"uusdc";default:return i}},tn=({symbol:i,chain:o})=>{if(o===g.Maya)return(i.toUpperCase()!=="CACAO"?i:`${g.Maya}.${i}`).toUpperCase();if(o===g.THORChain)return(["RUNE","TCY","RUJI"].includes(i.toUpperCase())?`${g.THORChain}.${i}`:i).toUpperCase();return U(i,!1)},St=()=>typeof window<"u"?{}:{referer:"https://sdk.swapkit.dev",referrer:"https://sdk.swapkit.dev"};function _n(i){return at(i,{headers:St()})}function Un(i){return{amount:i.amount,denom:i.denom}}function Ct(i,o){if(!i)return null;if("toAmino"in i&&typeof i.toAmino==="function")return null;let n=i[o];return n?{aminoType:n.aminoType,toAmino:n.toAmino}:null}async function _(i){let o=_n(i);return{async broadcastTx(r){let n=await Z(o,r,"sync");if(n.code!==0)throw new P("core_swap_transaction_error",{code:n.code,message:n.log});return{code:n.code,rawLog:n.log,transactionHash:n.hash}},async getAccount(r){let n=await Dn(o,r);if(!n)return null;return{accountNumber:Number(n.accountNumber),address:n.address,pubkey:n.pubKey?{type:n.pubKey.typeUrl,value:n.pubKey.key}:null,sequence:Number(n.sequence)}},async getAllBalances(r){return(await ct(o,r)).map((t)=>({amount:t.amount,denom:t.denom}))}}}function Nn(i,o={}){let r=Ot(i);async function n(t,e,s,c,a){let h=(await i.getAccounts()).find((b)=>b.address===t);if(!h)throw new P("toolbox_cosmos_signer_not_defined");let w=vt({memo:c,messages:e,registry:o.registry}),S=ft({type:"tendermint/PubKeySecp256k1",value:ln.encode(h.pubkey)});if(r){let b=e.map((E)=>Pt(E,o.aminoTypes)),A=mt({accountNumber:a.accountNumber,chainId:a.chainId,fee:Tt(s),memo:c,msgs:b,sequence:a.sequence}),C=await i.signAmino(t,A),T=Pn({fee:kt(C.signed.fee,s),signerInfos:[{mode:"amino",pubkey:S,sequence:BigInt(C.signed.sequence)}]}),k=ln.decode(C.signature.signature);return{authInfoBytes:T,bodyBytes:w,signatures:[k]}}let m=Pn({fee:xt(s),signerInfos:[{mode:"direct",pubkey:S,sequence:BigInt(a.sequence)}]}),l=await i.signDirect(t,{accountNumber:a.accountNumber,authInfoBytes:m,bodyBytes:w,chainId:a.chainId}),y=ln.decode(l.signature.signature);return{authInfoBytes:m,bodyBytes:w,signatures:[y]}}return{signWithRegistry:n}}function Ot(i){return typeof i.signAmino==="function"}function Tt(i){return{amount:i.amount.map((o)=>({amount:o.amount,denom:o.denom})),gas:i.gas,...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function xt(i){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter?{granter:i.granter}:{},...i.payer?{payer:i.payer}:{}}}function kt(i,o){return{amount:i.amount.map(Un),gasLimit:BigInt(i.gas),...i.granter??o.granter?{granter:i.granter??o.granter}:{},...i.payer??o.payer?{payer:i.payer??o.payer}:{}}}function Pt(i,o){if(o&&"toAmino"in o&&typeof o.toAmino==="function")return o.toAmino(i);let r=Ct(o,i.typeUrl);if(!r){if(i.typeUrl==="/cosmos.bank.v1beta1.MsgSend"){let n=i.value;return{type:"cosmos-sdk/MsgSend",value:{amount:n.amount,from_address:n.fromAddress,to_address:n.toAddress}}}throw new P("toolbox_cosmos_invalid_params",{error:`No amino converter for ${i.typeUrl}`})}return{type:r.aminoType,value:r.toAmino(i.value)}}function vt(i){let{memo:o,messages:r,registry:n}=i;if(n&&"encode"in n&&typeof n.encode==="function")return n.encode({typeUrl:"/cosmos.tx.v1beta1.TxBody",value:{memo:o,messages:r}});let t={...ut,...n??{}},e=r.map((s)=>lt(s,t));return dt({memo:o,messages:e})}async function L(i,o,r={}){let n=typeof r==="string"?{}:r,t=_n(i),e=Nn(o,n);async function s(c,a){let p=await Dn(t,c);if(!p)throw new P("toolbox_cosmos_account_not_found",{sender:c});let h=a?.chainId??(await t.status()).chainId;return{accountNumber:a?.accountNumber??p.accountNumber,chainId:h,sequence:a?.sequence??p.sequence}}return{async broadcastTx(c){let a=await Z(t,c,"sync");if(a.code!==0)throw new P("core_swap_transaction_error",{code:a.code,message:a.log});return{code:a.code,rawLog:a.log,transactionHash:a.hash}},async sendTokens(c,a,p,h,w=""){let S=[{typeUrl:"/cosmos.bank.v1beta1.MsgSend",value:{amount:p.map((A)=>({amount:A.amount,denom:A.denom})),fromAddress:c,toAddress:a}}],m=await s(c),l=await e.signWithRegistry(c,S,h,w,m),y=vn({authInfoBytes:l.authInfoBytes,bodyBytes:l.bodyBytes,signatures:l.signatures}),b=await Z(t,y,"sync");if(b.code!==0)throw new P("core_swap_transaction_error",{code:b.code,message:b.log});return{code:b.code,rawLog:b.log,transactionHash:b.hash}},async sign(c,a,p,h,w){let S=w??await s(c);return e.signWithRegistry(c,a,p,h,S)},async signAndBroadcast(c,a,p,h=""){let w=await s(c),S=await e.signWithRegistry(c,a,p,h,w),m=vn({authInfoBytes:S.authInfoBytes,bodyBytes:S.bodyBytes,signatures:S.signatures}),l=await Z(t,m,"sync");return{code:l.code,rawLog:l.log,transactionHash:l.hash}}}}async function Bn(i,o){let r=Nn(i,o??{});return{sign(n,t,e,s,c){if(!c)throw new P("toolbox_cosmos_invalid_params",{error:"createOfflineStargateClient.sign requires signerData"});return r.signWithRegistry(n,t,e,s,c)}}}var Dt=(i)=>{switch(i){case g.Maya:case g.THORChain:return"/types.MsgSend";case g.Cosmos:case g.Kujira:case g.Noble:return"/cosmos.bank.v1beta1.MsgSend";default:throw new P("toolbox_cosmos_not_supported",{chain:i})}};async function Mt({client:i,sender:o}){let r=await i.getAccount(o);if(!r)throw new P("toolbox_cosmos_account_not_found",{sender:o});return r}async function Fn({sender:i,recipient:o,assetValue:r,memo:n="",feeRate:t,sequence:e,accountNumber:s,sweep:c}){let{chain:a,chainId:p}=r,h=s===void 0||e===void 0,w=c||h?await _(await pt(a)):void 0,S=h&&w?await Mt({client:w,sender:i}):void 0,m=fn.from({chain:a}),l=U(m.symbol),y=M(a),b=l&&t?{amount:[{amount:t.toString(),denom:l}],gas:y.gas}:y,A=U(r.symbol),C=r;if(c){if(!w)throw new P("toolbox_cosmos_account_not_found",{sender:i});C=W({assetValue:r,balances:await w.getAllBalances(i),denom:A,feeAmount:mn(b.amount,A)})}let T={amount:[{amount:C.getBaseValue("string"),denom:A}],fromAddress:i,toAddress:o};return{accountNumber:s??Number(S?.accountNumber),chainId:p,fee:b,memo:n,msgs:[{typeUrl:Dt(a),value:T}],sequence:e??Number(S?.sequence)}}function mn(i,o){let r=o.toLowerCase();return i.reduce((n,t)=>t.denom.toLowerCase()===r?n+BigInt(t.amount):n,0n)}function W({assetValue:i,balances:o,denom:r,feeAmount:n=0n}){let t=r.toLowerCase(),e=o.find(({denom:a})=>a.toLowerCase()===t),s=BigInt(e?.amount??"0"),c=s-n;if(c<=0n)throw new P("toolbox_sweep_amount_too_low",{asset:i.toString(),balance:s.toString(),fee:n.toString()});return i.set(dn.fromBigInt(c,i.decimal))}var _t={atom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},cacao:{chain:g.Maya,decimals:10},kuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},maya:{asset:`${g.Maya}.${g.Maya}`,decimals:4},rune:{chain:g.THORChain,decimals:D(g.THORChain).baseDecimal},tcy:{asset:"THOR.TCY",decimals:D(g.THORChain).baseDecimal},uatom:{chain:g.Cosmos,decimals:D(g.Cosmos).baseDecimal},ukuji:{chain:g.Kujira,decimals:D(g.Kujira).baseDecimal},usdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},uusdc:{chain:g.Noble,decimals:D(g.Noble).baseDecimal},"x/kuji":{asset:"THOR.KUJI",decimals:D(g.THORChain).baseDecimal},[Mn.toLowerCase()]:{asset:`${g.Kujira}.USK`,decimals:D(g.Kujira).baseDecimal}},In=(i,o)=>{let r=_t[i.toLowerCase()];if(!r)return fn.from({asset:i,fromBaseDecimal:8,value:o});let{chain:n,asset:t,decimals:e}=r,s=n?{chain:n}:{asset:t};return fn.from({...s,fromBaseDecimal:e,value:o})};import{defaultEncoders as Ut}from"@swapkit/cosmos-signer";import{Chain as Rn}from"@swapkit/helpers";import O from"protobufjs/minimal.js";var d=O.Reader,v=O.Writer,f=O.util,u=O.roots.default||(O.roots.default={});u.common=(()=>{let i={};return i.Asset=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.chain="",o.prototype.symbol="",o.prototype.ticker="",o.prototype.synth=!1,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(10).string(n.chain);if(n.symbol!=null&&Object.hasOwnProperty.call(n,"symbol"))t.uint32(18).string(n.symbol);if(n.ticker!=null&&Object.hasOwnProperty.call(n,"ticker"))t.uint32(26).string(n.ticker);if(n.synth!=null&&Object.hasOwnProperty.call(n,"synth"))t.uint32(32).bool(n.synth);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Asset;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.chain=n.string();break;case 2:s.symbol=n.string();break;case 3:s.ticker=n.string();break;case 4:s.synth=n.bool();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.symbol!=null&&n.hasOwnProperty("symbol")){if(!f.isString(n.symbol))return"symbol: string expected"}if(n.ticker!=null&&n.hasOwnProperty("ticker")){if(!f.isString(n.ticker))return"ticker: string expected"}if(n.synth!=null&&n.hasOwnProperty("synth")){if(typeof n.synth!=="boolean")return"synth: boolean expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Asset)return n;let t=new u.common.Asset;if(n.chain!=null)t.chain=String(n.chain);if(n.symbol!=null)t.symbol=String(n.symbol);if(n.ticker!=null)t.ticker=String(n.ticker);if(n.synth!=null)t.synth=Boolean(n.synth);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.chain="",e.symbol="",e.ticker="",e.synth=!1;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.symbol!=null&&n.hasOwnProperty("symbol"))e.symbol=n.symbol;if(n.ticker!=null&&n.hasOwnProperty("ticker"))e.ticker=n.ticker;if(n.synth!=null&&n.hasOwnProperty("synth"))e.synth=n.synth;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Coin=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.asset=null,o.prototype.amount="",o.prototype.decimals=f.Long?f.Long.fromBits(0,0,!1):0,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.asset!=null&&Object.hasOwnProperty.call(n,"asset"))u.common.Asset.encode(n.asset,t.uint32(10).fork()).ldelim();if(n.amount!=null&&Object.hasOwnProperty.call(n,"amount"))t.uint32(18).string(n.amount);if(n.decimals!=null&&Object.hasOwnProperty.call(n,"decimals"))t.uint32(24).int64(n.decimals);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Coin;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.asset=u.common.Asset.decode(n,n.uint32());break;case 2:s.amount=n.string();break;case 3:s.decimals=n.int64();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.asset!=null&&n.hasOwnProperty("asset")){let t=u.common.Asset.verify(n.asset);if(t)return"asset."+t}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!f.isString(n.amount))return"amount: string expected"}if(n.decimals!=null&&n.hasOwnProperty("decimals")){if(!f.isInteger(n.decimals)&&!(n.decimals&&f.isInteger(n.decimals.low)&&f.isInteger(n.decimals.high)))return"decimals: integer|Long expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Coin)return n;let t=new u.common.Coin;if(n.asset!=null){if(typeof n.asset!=="object")throw TypeError(".common.Coin.asset: object expected");t.asset=u.common.Asset.fromObject(n.asset)}if(n.amount!=null)t.amount=String(n.amount);if(n.decimals!=null){if(f.Long)(t.decimals=f.Long.fromValue(n.decimals)).unsigned=!1;else if(typeof n.decimals==="string")t.decimals=Number.parseInt(n.decimals,10);else if(typeof n.decimals==="number")t.decimals=n.decimals;else if(typeof n.decimals==="object")t.decimals=new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber()}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)if(e.asset=null,e.amount="",f.Long){let s=new f.Long(0,0,!1);e.decimals=t.longs===String?s.toString():t.longs===Number?s.toNumber():s}else e.decimals=t.longs===String?"0":0;if(n.asset!=null&&n.hasOwnProperty("asset"))e.asset=u.common.Asset.toObject(n.asset,t);if(n.amount!=null&&n.hasOwnProperty("amount"))e.amount=n.amount;if(n.decimals!=null&&n.hasOwnProperty("decimals"))if(typeof n.decimals==="number")e.decimals=t.longs===String?String(n.decimals):n.decimals;else e.decimals=t.longs===String?f.Long.prototype.toString.call(n.decimals):t.longs===Number?new f.LongBits(n.decimals.low>>>0,n.decimals.high>>>0).toNumber():n.decimals;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.PubKeySet=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.secp256k1="",o.prototype.ed25519="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.secp256k1!=null&&Object.hasOwnProperty.call(n,"secp256k1"))t.uint32(10).string(n.secp256k1);if(n.ed25519!=null&&Object.hasOwnProperty.call(n,"ed25519"))t.uint32(18).string(n.ed25519);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.PubKeySet;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.secp256k1=n.string();break;case 2:s.ed25519=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1")){if(!f.isString(n.secp256k1))return"secp256k1: string expected"}if(n.ed25519!=null&&n.hasOwnProperty("ed25519")){if(!f.isString(n.ed25519))return"ed25519: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.PubKeySet)return n;let t=new u.common.PubKeySet;if(n.secp256k1!=null)t.secp256k1=String(n.secp256k1);if(n.ed25519!=null)t.ed25519=String(n.ed25519);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.secp256k1="",e.ed25519="";if(n.secp256k1!=null&&n.hasOwnProperty("secp256k1"))e.secp256k1=n.secp256k1;if(n.ed25519!=null&&n.hasOwnProperty("ed25519"))e.ed25519=n.ed25519;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Tx=(()=>{function o(r){if(this.coins=[],this.gas=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.id="",o.prototype.chain="",o.prototype.fromAddress="",o.prototype.toAddress="",o.prototype.coins=f.emptyArray,o.prototype.gas=f.emptyArray,o.prototype.memo="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.id!=null&&Object.hasOwnProperty.call(n,"id"))t.uint32(10).string(n.id);if(n.chain!=null&&Object.hasOwnProperty.call(n,"chain"))t.uint32(18).string(n.chain);if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(26).string(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(34).string(n.toAddress);if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(42).fork()).ldelim();if(n.gas?.length)for(let e=0;e<n.gas.length;++e)u.common.Coin.encode(n.gas[e],t.uint32(50).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(58).string(n.memo);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Tx;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.id=n.string();break;case 2:s.chain=n.string();break;case 3:s.fromAddress=n.string();break;case 4:s.toAddress=n.string();break;case 5:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 6:if(!s.gas?.length)s.gas=[];s.gas.push(u.common.Coin.decode(n,n.uint32()));break;case 7:s.memo=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.id!=null&&n.hasOwnProperty("id")){if(!f.isString(n.id))return"id: string expected"}if(n.chain!=null&&n.hasOwnProperty("chain")){if(!f.isString(n.chain))return"chain: string expected"}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!f.isString(n.fromAddress))return"fromAddress: string expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!f.isString(n.toAddress))return"toAddress: string expected"}if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.gas!=null&&n.hasOwnProperty("gas")){if(!Array.isArray(n.gas))return"gas: array expected";for(let t=0;t<n.gas.length;++t){let e=u.common.Coin.verify(n.gas[t]);if(e)return"gas."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Tx)return n;let t=new u.common.Tx;if(n.id!=null)t.id=String(n.id);if(n.chain!=null)t.chain=String(n.chain);if(n.fromAddress!=null)t.fromAddress=String(n.fromAddress);if(n.toAddress!=null)t.toAddress=String(n.toAddress);if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Tx.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Tx.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.gas){if(!Array.isArray(n.gas))throw TypeError(".common.Tx.gas: array expected");t.gas=[];for(let e=0;e<n.gas.length;++e){if(typeof n.gas[e]!=="object")throw TypeError(".common.Tx.gas: object expected");t.gas[e]=u.common.Coin.fromObject(n.gas[e])}}if(n.memo!=null)t.memo=String(n.memo);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[],e.gas=[];if(t.defaults)e.id="",e.chain="",e.fromAddress="",e.toAddress="",e.memo="";if(n.id!=null&&n.hasOwnProperty("id"))e.id=n.id;if(n.chain!=null&&n.hasOwnProperty("chain"))e.chain=n.chain;if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=n.toAddress;if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.gas?.length){e.gas=[];for(let s=0;s<n.gas.length;++s)e.gas[s]=u.common.Coin.toObject(n.gas[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.Fee=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.poolDeduct="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.poolDeduct!=null&&Object.hasOwnProperty.call(n,"poolDeduct"))t.uint32(18).string(n.poolDeduct);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.Fee;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.poolDeduct=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct")){if(!f.isString(n.poolDeduct))return"poolDeduct: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.Fee)return n;let t=new u.common.Fee;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".common.Fee.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".common.Fee.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.poolDeduct!=null)t.poolDeduct=String(n.poolDeduct);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults)e.poolDeduct="";if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.poolDeduct!=null&&n.hasOwnProperty("poolDeduct"))e.poolDeduct=n.poolDeduct;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.ProtoUint=(()=>{function o(r){if(r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.value="",o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.value!=null&&Object.hasOwnProperty.call(n,"value"))t.uint32(10).string(n.value);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.common.ProtoUint;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.value=n.string();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.value!=null&&n.hasOwnProperty("value")){if(!f.isString(n.value))return"value: string expected"}return null},o.fromObject=function(n){if(n instanceof u.common.ProtoUint)return n;let t=new u.common.ProtoUint;if(n.value!=null)t.value=String(n.value);return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.defaults)e.value="";if(n.value!=null&&n.hasOwnProperty("value"))e.value=n.value;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.types=(()=>{let i={};return i.MsgDeposit=(()=>{function o(r){if(this.coins=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.coins=f.emptyArray,o.prototype.memo="",o.prototype.signer=f.newBuffer([]),o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.coins?.length)for(let e=0;e<n.coins.length;++e)u.common.Coin.encode(n.coins[e],t.uint32(10).fork()).ldelim();if(n.memo!=null&&Object.hasOwnProperty.call(n,"memo"))t.uint32(18).string(n.memo);if(n.signer!=null&&Object.hasOwnProperty.call(n,"signer"))t.uint32(26).bytes(n.signer);return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgDeposit;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:if(!s.coins?.length)s.coins=[];s.coins.push(u.common.Coin.decode(n,n.uint32()));break;case 2:s.memo=n.string();break;case 3:s.signer=n.bytes();break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.coins!=null&&n.hasOwnProperty("coins")){if(!Array.isArray(n.coins))return"coins: array expected";for(let t=0;t<n.coins.length;++t){let e=u.common.Coin.verify(n.coins[t]);if(e)return"coins."+e}}if(n.memo!=null&&n.hasOwnProperty("memo")){if(!f.isString(n.memo))return"memo: string expected"}if(n.signer!=null&&n.hasOwnProperty("signer")){if(!(n.signer&&typeof n.signer.length==="number"||f.isString(n.signer)))return"signer: buffer expected"}return null},o.fromObject=function(n){if(n instanceof u.types.MsgDeposit)return n;let t=new u.types.MsgDeposit;if(n.coins){if(!Array.isArray(n.coins))throw TypeError(".types.MsgDeposit.coins: array expected");t.coins=[];for(let e=0;e<n.coins.length;++e){if(typeof n.coins[e]!=="object")throw TypeError(".types.MsgDeposit.coins: object expected");t.coins[e]=u.common.Coin.fromObject(n.coins[e])}}if(n.memo!=null)t.memo=String(n.memo);if(n.signer!=null){if(typeof n.signer==="string")f.base64.decode(n.signer,t.signer=f.newBuffer(f.base64.length(n.signer)),0);else if(n.signer.length)t.signer=n.signer}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.coins=[];if(t.defaults){if(e.memo="",t.bytes===String)e.signer="";else if(e.signer=[],t.bytes!==Array)e.signer=f.newBuffer(e.signer)}if(n.coins?.length){e.coins=[];for(let s=0;s<n.coins.length;++s)e.coins[s]=u.common.Coin.toObject(n.coins[s],t)}if(n.memo!=null&&n.hasOwnProperty("memo"))e.memo=n.memo;if(n.signer!=null&&n.hasOwnProperty("signer"))e.signer=t.bytes===String?f.base64.encode(n.signer,0,n.signer.length):t.bytes===Array?Array.prototype.slice.call(n.signer):n.signer;return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i.MsgSend=(()=>{function o(r){if(this.amount=[],r){for(let n=Object.keys(r),t=0;t<n.length;++t)if(r[n[t]]!=null)this[n[t]]=r[n[t]]}}return o.prototype.fromAddress=f.newBuffer([]),o.prototype.toAddress=f.newBuffer([]),o.prototype.amount=f.emptyArray,o.create=function(n){return new o(n)},o.encode=function(n,t){if(!t)t=v.create();if(n.fromAddress!=null&&Object.hasOwnProperty.call(n,"fromAddress"))t.uint32(10).bytes(n.fromAddress);if(n.toAddress!=null&&Object.hasOwnProperty.call(n,"toAddress"))t.uint32(18).bytes(n.toAddress);if(n.amount?.length)for(let e=0;e<n.amount.length;++e)u.cosmos.base.v1beta1.Coin.encode(n.amount[e],t.uint32(26).fork()).ldelim();return t},o.encodeDelimited=function(n,t){return this.encode(n,t).ldelim()},o.decode=function(n,t){if(!(n instanceof d))n=d.create(n);let e=t===void 0?n.len:n.pos+t,s=new u.types.MsgSend;while(n.pos<e){let c=n.uint32();switch(c>>>3){case 1:s.fromAddress=n.bytes();break;case 2:s.toAddress=n.bytes();break;case 3:if(!s.amount?.length)s.amount=[];s.amount.push(u.cosmos.base.v1beta1.Coin.decode(n,n.uint32()));break;default:n.skipType(c&7);break}}return s},o.decodeDelimited=function(n){if(!(n instanceof d))n=new d(n);return this.decode(n,n.uint32())},o.verify=function(n){if(typeof n!=="object"||n===null)return"object expected";if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress")){if(!(n.fromAddress&&typeof n.fromAddress.length==="number"||f.isString(n.fromAddress)))return"fromAddress: buffer expected"}if(n.toAddress!=null&&n.hasOwnProperty("toAddress")){if(!(n.toAddress&&typeof n.toAddress.length==="number"||f.isString(n.toAddress)))return"toAddress: buffer expected"}if(n.amount!=null&&n.hasOwnProperty("amount")){if(!Array.isArray(n.amount))return"amount: array expected";for(let t=0;t<n.amount.length;++t){let e=u.cosmos.base.v1beta1.Coin.verify(n.amount[t]);if(e)return"amount."+e}}return null},o.fromObject=function(n){if(n instanceof u.types.MsgSend)return n;let t=new u.types.MsgSend;if(n.fromAddress!=null){if(typeof n.fromAddress==="string")f.base64.decode(n.fromAddress,t.fromAddress=f.newBuffer(f.base64.length(n.fromAddress)),0);else if(n.fromAddress.length)t.fromAddress=n.fromAddress}if(n.toAddress!=null){if(typeof n.toAddress==="string")f.base64.decode(n.toAddress,t.toAddress=f.newBuffer(f.base64.length(n.toAddress)),0);else if(n.toAddress.length)t.toAddress=n.toAddress}if(n.amount){if(!Array.isArray(n.amount))throw TypeError(".types.MsgSend.amount: array expected");t.amount=[];for(let e=0;e<n.amount.length;++e){if(typeof n.amount[e]!=="object")throw TypeError(".types.MsgSend.amount: object expected");t.amount[e]=u.cosmos.base.v1beta1.Coin.fromObject(n.amount[e])}}return t},o.toObject=function(n,t){if(!t)t={};let e={};if(t.arrays||t.defaults)e.amount=[];if(t.defaults){if(t.bytes===String)e.fromAddress="";else if(e.fromAddress=[],t.bytes!==Array)e.fromAddress=f.newBuffer(e.fromAddress);if(t.bytes===String)e.toAddress="";else if(e.toAddress=[],t.bytes!==Array)e.toAddress=f.newBuffer(e.toAddress)}if(n.fromAddress!=null&&n.hasOwnProperty("fromAddress"))e.fromAddress=t.bytes===String?f.base64.encode(n.fromAddress,0,n.fromAddress.length):t.bytes===Array?Array.prototype.slice.call(n.fromAddress):n.fromAddress;if(n.toAddress!=null&&n.hasOwnProperty("toAddress"))e.toAddress=t.bytes===String?f.base64.encode(n.toAddress,0,n.toAddress.length):t.bytes===Array?Array.prototype.slice.call(n.toAddress):n.toAddress;if(n.amount?.length){e.amount=[];for(let s=0;s<n.amount.length;++s)e.amount[s]=u.cosmos.base.v1beta1.Coin.toObject(n.amount[s],t)}return e},o.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},o})(),i})();u.cosmos=(()=>{let i={};return i.base=(()=>{let o={};return o.v1beta1=(()=>{let r={};return r.Coin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.Coin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.Coin)return e;let s=new u.cosmos.base.v1beta1.Coin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecCoin=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.denom="",n.prototype.amount="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.denom!=null&&Object.hasOwnProperty.call(e,"denom"))s.uint32(10).string(e.denom);if(e.amount!=null&&Object.hasOwnProperty.call(e,"amount"))s.uint32(18).string(e.amount);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecCoin;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.denom=e.string();break;case 2:a.amount=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.denom!=null&&e.hasOwnProperty("denom")){if(!f.isString(e.denom))return"denom: string expected"}if(e.amount!=null&&e.hasOwnProperty("amount")){if(!f.isString(e.amount))return"amount: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecCoin)return e;let s=new u.cosmos.base.v1beta1.DecCoin;if(e.denom!=null)s.denom=String(e.denom);if(e.amount!=null)s.amount=String(e.amount);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.denom="",c.amount="";if(e.denom!=null&&e.hasOwnProperty("denom"))c.denom=e.denom;if(e.amount!=null&&e.hasOwnProperty("amount"))c.amount=e.amount;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.IntProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.int="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.int!=null&&Object.hasOwnProperty.call(e,"int"))s.uint32(10).string(e.int);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.IntProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.int=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.int!=null&&e.hasOwnProperty("int")){if(!f.isString(e.int))return"int: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.IntProto)return e;let s=new u.cosmos.base.v1beta1.IntProto;if(e.int!=null)s.int=String(e.int);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.int="";if(e.int!=null&&e.hasOwnProperty("int"))c.int=e.int;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r.DecProto=(()=>{function n(t){if(t){for(let e=Object.keys(t),s=0;s<e.length;++s)if(t[e[s]]!=null)this[e[s]]=t[e[s]]}}return n.prototype.dec="",n.create=function(e){return new n(e)},n.encode=function(e,s){if(!s)s=v.create();if(e.dec!=null&&Object.hasOwnProperty.call(e,"dec"))s.uint32(10).string(e.dec);return s},n.encodeDelimited=function(e,s){return this.encode(e,s).ldelim()},n.decode=function(e,s){if(!(e instanceof d))e=d.create(e);let c=s===void 0?e.len:e.pos+s,a=new u.cosmos.base.v1beta1.DecProto;while(e.pos<c){let p=e.uint32();switch(p>>>3){case 1:a.dec=e.string();break;default:e.skipType(p&7);break}}return a},n.decodeDelimited=function(e){if(!(e instanceof d))e=new d(e);return this.decode(e,e.uint32())},n.verify=function(e){if(typeof e!=="object"||e===null)return"object expected";if(e.dec!=null&&e.hasOwnProperty("dec")){if(!f.isString(e.dec))return"dec: string expected"}return null},n.fromObject=function(e){if(e instanceof u.cosmos.base.v1beta1.DecProto)return e;let s=new u.cosmos.base.v1beta1.DecProto;if(e.dec!=null)s.dec=String(e.dec);return s},n.toObject=function(e,s){if(!s)s={};let c={};if(s.defaults)c.dec="";if(e.dec!=null&&e.hasOwnProperty("dec"))c.dec=e.dec;return c},n.prototype.toJSON=function(){return this.constructor.toObject(this,O.util.toJSONOptions)},n})(),r})(),o})(),i})();function pn(i){if(i instanceof Uint8Array)return i;if(typeof i==="string")return Uint8Array.from(globalThis.atob(i),(r)=>r.charCodeAt(0));throw TypeError("address must be Uint8Array or base64 string")}var Nt=(i)=>{let o=i;return u.types.MsgSend.encode({amount:o.amount,fromAddress:pn(o.fromAddress),toAddress:pn(o.toAddress)}).finish()},Bt=(i)=>{let o=i;return u.types.MsgDeposit.encode({coins:o.coins.map((r)=>({amount:r.amount,asset:r.asset})),memo:o.memo,signer:pn(o.signer)}).finish()};function j(){return{...Ut,"/types.MsgDeposit":Bt,"/types.MsgSend":Nt}}function F(i,o=i===Rn.THORChain?"thor":"maya"){let r=i===Rn.THORChain?"thorchain":"mayachain",n={"/types.MsgDeposit":{aminoType:`${r}/MsgDeposit`,fromAmino:({signer:t,...e})=>({...e,signer:X(t)}),toAmino:({signer:t,...e})=>({...e,signer:typeof t==="string"?Q(t,o):t})},"/types.MsgSend":{aminoType:`${r}/MsgSend`,fromAmino:({from_address:t,to_address:e,...s})=>({...s,fromAddress:X(t),toAddress:X(e)}),toAmino:({fromAddress:t,toAddress:e,...s})=>({...s,from_address:typeof t==="string"?Q(t,o):t,to_address:typeof e==="string"?Q(e,o):e})}};return Object.assign(n,{fromAmino(t){let e=Object.entries(n).find(([,a])=>a.aminoType===t.type);if(!e)throw TypeError(`No converter for amino type ${t.type}`);let[s,c]=e;return{typeUrl:s,value:c.fromAmino(t.value)}},toAmino(t){let e=n[t.typeUrl];if(!e)throw TypeError(`No converter for type URL ${t.typeUrl}`);return{type:e.aminoType,value:e.toAmino(t.value)}}})}var qe=M(en.THORChain).gas,Ve=M(en.Maya).gas,Ln=({sender:i,recipient:o,assetValue:r})=>({type:`${r.chain===en.Maya?"mayachain":"thorchain"}/MsgSend`,value:{amount:[{amount:r.getBaseValue("string"),denom:U(r.symbol,!0)}],from_address:i,to_address:o}}),jn=({sender:i,assetValue:o,memo:r=""})=>({type:`${o.chain===en.Maya?"mayachain":"thorchain"}/MsgDeposit`,value:{coins:[{amount:o.getBaseValue("string"),asset:tn(o)}],memo:r,signer:i}}),hn=({sender:i,recipient:o,assetValue:r,memo:n})=>!o?jn({assetValue:r,memo:n,sender:i}):Ln({assetValue:r,recipient:o,sender:i});function En(i,o){for(let r of["/types.MsgDeposit","/types.MsgSend"]){let n=i[r];if(n.aminoType===o)return{fromAmino:n.fromAmino,typeUrl:r}}return null}var I=(i,o)=>{let r=F(o),n=En(r,i.type);if(!n)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${i.type}`});return{typeUrl:n.typeUrl,value:n.fromAmino(i.value)}},Hn=async({rpcUrl:i,sender:o})=>{let n=await(await _(i)).getAccount(o);if(!n)throw new gn("toolbox_cosmos_account_not_found",{sender:o});return n};async function Jn(i){let{assetValue:o,recipient:r,memo:n,sender:t,asSignable:e,asAminoMessage:s,sequence:c,accountNumber:a}=i,p=i.sweep?await bn({assetValue:o,sender:t}):o;if(r)return Kt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,recipient:r,sender:t,sequence:c});return Lt({accountNumber:a,asAminoMessage:s,asSignable:e,assetValue:p,memo:n,sender:t,sequence:c})}async function bn({assetValue:i,sender:o}){let r=i.chain,n=await yn(r),e=await(await _(n)).getAllBalances(o),s=i.isGasAsset?(await nn(r)).getBaseValue("bigint"):0n;return W({assetValue:i,balances:e,denom:U(i.symbol,!0),feeAmount:s})}async function Kt({sender:i,recipient:o,assetValue:r,memo:n="",asSignable:t=!0,asAminoMessage:e=!1,sequence:s,accountNumber:c}){let a=r.chain,p=c!==void 0&&s!==void 0?void 0:await Hn({rpcUrl:await yn(a),sender:i}),{chainId:h}=Kn(a),w=Ln({assetValue:r,recipient:o,sender:i}),S=t?I(e?w:R(w),a):w;return{accountNumber:c??Number(p?.accountNumber),chainId:h,fee:M(a),memo:n,msgs:[S],sequence:s??Number(p?.sequence)}}async function Lt({sender:i,assetValue:o,memo:r="",asSignable:n=!0,asAminoMessage:t=!1,sequence:e,accountNumber:s}){let c=o.chain,a=s!==void 0&&e!==void 0?void 0:await Hn({rpcUrl:await yn(c),sender:i}),{chainId:p}=Kn(c),h=jn({assetValue:o,memo:r,sender:i}),w=n?I(t?h:R(h),c):h;return{accountNumber:s??Number(a?.accountNumber),chainId:p,fee:M(c),memo:r,msgs:[w],sequence:e??Number(a?.sequence)}}function R(i){if(i.type==="thorchain/MsgSend"||i.type==="mayachain/MsgSend")return i;return{...i,value:{...i.value,coins:i.value.coins.map((o)=>{let r=Rt.from({asset:o.asset}),n=(r.isSynthetic?r.symbol.split("/")?.[1]:r.symbol)?.toUpperCase(),t=(r.isSynthetic?r.symbol.split("/")?.[0]:r.chain)?.toUpperCase();return{...o,asset:{chain:t,symbol:n,synth:r.isSynthetic,ticker:r.ticker}}})}}}function on({chain:i,memo:o,msgs:r}){let n=j(),t=F(i),s=r.map((c)=>{let a=En(t,c.type);if(!a)throw new gn("toolbox_cosmos_invalid_params",{error:`No converter for amino type ${c.type}`});return{typeUrl:a.typeUrl,value:a.fromAmino(c.value)}}).map((c)=>Ft(c,n));return It({memo:o,messages:s})}import{Chain as V,SwapKitError as Te}from"@swapkit/helpers";import{secp256k1 as jt}from"@noble/curves/secp256k1.js";import{base64 as Cn,bech32 as An}from"@scure/base";import{HDKey as Et}from"@scure/bip32";import{verifySignature as Ht,createWalletFromMnemonic as Jt,createWalletFromPrivateKey as $t,mnemonicToSeed as Wt,signDirect as qt}from"@swapkit/cosmos-signer";import{AssetValue as On,applyFeeMultiplier as $n,Chain as x,CosmosChainPrefixes as zn,DerivationPath as Vt,derivationPathToString as Wn,FeeOption as Tn,getChainConfig as Gt,getRPCUrl as q,NetworkDerivationPath as Yt,SwapKitError as N,SwapKitNumber as wn,updateDerivationPath as zt}from"@swapkit/helpers";import{SwapKitApi as Xn}from"@swapkit/helpers/api";import{PubKey as Xt}from"cosmjs-types/cosmos/crypto/secp256k1/keys";import{match as Qt,P as qn}from"ts-pattern";async function Qn(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function Zn(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{getAccounts:()=>Promise.resolve(o),async signDirect(r,n){if(r!==i.address)throw new N("toolbox_cosmos_signer_not_defined");let t=await qt(i.privateKey,i.publicKey,{accountNumber:n.accountNumber,authInfoBytes:n.authInfoBytes,bodyBytes:n.bodyBytes,chainId:n.chainId});return{signature:t.signature,signed:{accountNumber:t.signed.accountNumber,authInfoBytes:t.signed.authInfoBytes,bodyBytes:t.signed.bodyBytes,chainId:t.signed.chainId}}}}}async function Vn({phrase:i,prefix:o,...r}){let n="derivationPath"in r?r.derivationPath:`${Vt[r.chain]}/${r.index??0}`,t=await Jt({hdPath:n,mnemonic:i,prefix:o??""});return Zn(t)}async function Zt({privateKey:i,prefix:o}){let r=$t({prefix:o,privateKey:i});return Zn(r)}var Gn={[x.Cosmos]:1000,[x.Kujira]:1000,[x.Noble]:1000,[x.THORChain]:5000000,[x.Maya]:5000000,[x.Harbor]:5000000};function ne(i){return async function({signature:r,message:n,address:t}){let e=await i(t);if(!e?.pubkey)throw new N("toolbox_cosmos_verify_signature_no_pubkey");let s=e.pubkey.type==="/cosmos.crypto.secp256k1.PubKey"?Xt.decode(e.pubkey.value).key:e.pubkey.value;return Ht(Cn.decode(n),Cn.decode(r),s)}}function rn({chain:i,...o}){let r=zn[i],n="index"in o?o.index||0:0,t=Wn("derivationPath"in o&&o.derivationPath?o.derivationPath:zt(Yt[i],{index:n})),e;async function s(){if(e)return e;return e=await Qt(o).with({phrase:qn.string},({phrase:m})=>Vn({derivationPath:t,phrase:m,prefix:r})).with({signer:qn.any},({signer:m})=>m).otherwise(()=>{return}),e}async function c(m){let l=await q(i);return(await _(l)).getAccount(m)}async function a(){let m=await s(),[l]=await m?.getAccounts()||[];return l?.address}async function p(){let m=await s(),[l]=await m?.getAccounts()||[];if(!l?.pubkey)throw new N("toolbox_cosmos_signer_not_defined");return Cn.encode(l?.pubkey)}async function h(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");return(await L(b,l)).sign(y,m.msgs,m.fee,m.memo,{accountNumber:BigInt(m.accountNumber),chainId:m.chainId,sequence:m.sequence})}async function w(m){let l=await s(),y=await a(),b=await q(i);if(!(l&&y))throw new N("toolbox_cosmos_signer_not_defined");let C=await(await L(b,l)).signAndBroadcast(y,m.msgs,m.fee,m.memo);if(C.code!==0)throw new N("core_swap_transaction_error",{code:C.code,message:C.rawLog});return C.transactionHash}async function S({recipient:m,assetValue:l,memo:y="",feeRate:b,feeOptionKey:A=Tn.Fast,sweep:C}){let T=await s(),k=await a();if(!(T&&k))throw new N("toolbox_cosmos_signer_not_defined");let E=await q(i),sn=On.from({chain:i}),H=tn(sn),G=te(b||(await Yn(i,Gn[i]))[A],H,i),cn=await L(E,T),J=U(l.symbol),an=[{amount:(C?W({assetValue:l,balances:await Sn(i)(k),denom:J,feeAmount:mn(G.amount,J)}):l).getBaseValue("string"),denom:J}],{transactionHash:un}=await cn.sendTokens(k,m,an,G,y);return un}return{createPrivateKeyFromPhrase:ie(t),createTransaction:Fn,fetchFeeRateFromSwapKit:Qn,getAccount:c,getAddress:a,getBalance:async(m,l)=>{let b=(await Sn(i)(m)).filter(({denom:A})=>A&&!A.includes("IBC/")&&!([x.THORChain,x.Maya].includes(i)&&A.split("-").length>2)).flatMap(({denom:A,amount:C})=>{let T=[x.THORChain,x.Maya].includes(i)&&(A.includes("/")||A.includes("˜"))?`${i}.${A}`:A;try{return[In(T,C)]}catch{return[]}});if(b.length===0)return[On.from({chain:i})];return b},getBalanceAsDenoms:Sn(i),getFees:()=>Yn(i,Gn[i]),getPubKey:p,getSignerFromPhrase:({phrase:m,derivationPath:l})=>Vn({derivationPath:Wn(l),index:n,phrase:m,prefix:r}),getSignerFromPrivateKey:(m)=>Zt({prefix:r,privateKey:m}),signAndBroadcastTransaction:w,signTransaction:h,transfer:S,validateAddress:oe(i),verifySignature:ne(c)}}async function lo(i,o){try{let n=(await Xn.getGasRate()).find((t)=>t.chainId===i)?.value;return n?Number.parseFloat(n):o}catch{return o}}function fo({assetValue:{chain:i}}){return On.from({chain:i,value:ee(i)})}async function Yn(i,o){let{chainId:r,baseDecimal:n}=Gt(i),t=await Qn(r,o);return{average:wn.fromBigInt(BigInt(t),n),fast:wn.fromBigInt(BigInt($n(t,Tn.Fast,!0)),n),fastest:wn.fromBigInt(BigInt($n(t,Tn.Fastest,!0)),n)}}function te(i,o,r){return{amount:[{amount:typeof i==="number"?i.toString():i.getBaseValue("string"),denom:o}],gas:M(r).gas}}function ee(i){return{[x.Cosmos]:0.007,[x.Kujira]:0.02,[x.Noble]:0.01,[x.THORChain]:0.02,[x.Maya]:0.02,[x.Harbor]:0.02}[i]||0}function oe(i){let o=zn[i];return function(n){if(!n.startsWith(o))return!1;try{let{prefix:t,words:e}=An.decode(n);return An.encode(t,e)===n.toLocaleLowerCase()}catch{return!1}}}function Sn(i){return async function(r){let n=await q(i);return(await(await _(n)).getAllBalances(r)).map((c)=>({...c,denom:c.denom.includes("/")?c.denom.toUpperCase():c.denom}))}}function ie(i){return async function(r){let n=await Wt(r),e=Et.fromMasterSeed(n).derive(i);if(!e.privateKey)throw new N("toolbox_cosmos_invalid_params",{error:"HDKey derivation produced no private key"});return jt.getPublicKey(e.privateKey,!0),Uint8Array.from(e.privateKey)}}import{secp256k1 as re}from"@noble/curves/secp256k1.js";import{base64 as B}from"@scure/base";import{buildMultisignedTx as se,createMultisigThresholdPubkey as ce,signAmino as ae,createWalletFromMnemonic as ue,encodeTxRaw as le,multisigPubkeyToAddress as fe,singlePubkeyToAddress as tt}from"@swapkit/cosmos-signer";import{CosmosChainPrefixes as de,derivationPathToString as me,FeeOption as xn,getRPCUrl as et,NetworkDerivationPath as pe,SwapKitError as K,updateDerivationPath as ye}from"@swapkit/helpers";import{match as ge,P as nt}from"ts-pattern";function he(i){let o=[{address:i.address,algo:"secp256k1",pubkey:i.publicKey}];return{accounts:o,getAccounts:()=>Promise.resolve(o),async signAmino(r,n){if(r!==i.address)throw new K("toolbox_cosmos_signer_not_defined");let t=await ae(i.privateKey,i.publicKey,{signDoc:n});return{signature:t.signature,signed:t.signed}}}}function be({prefix:i,derivationPath:o}){return async function(n,t=0){let e=await ue({hdPath:`${o}/${t}`,mnemonic:n,prefix:i});return he(e)}}function Ae(i){return B.encode(i)}function we(i,o){return async function({wallet:n,tx:t}){let{msgs:e,accountNumber:s,sequence:c,chainId:a,fee:p,memo:h}=typeof t==="string"?JSON.parse(t):t,w=(await n.getAccounts())?.[0]?.address||"",S=F(i,o),m=j(),l=await Bn(n,{aminoTypes:S,registry:m}),y=[];for(let C of e){let T=I(C,i);y.push(T)}let{signatures:[b]}=await l.sign(w,y,p,h,{accountNumber:BigInt(s),chainId:a,sequence:c});return{bodyBytes:on({chain:i,memo:h,msgs:e.map(R)}),signature:Ae(b)}}}function ot(i){if(i.length!==33||i[0]!==2&&i[0]!==3)throw new K("toolbox_cosmos_invalid_params",{error:"Invalid compressed secp256k1 pubkey (must be 33 bytes starting with 0x02 or 0x03)"});return{type:"tendermint/PubKeySecp256k1",value:B.encode(i)}}function Se({prefix:i,chain:o}){return async function(n,t,e,s,c){let a=await et(o),{sequence:p,fee:h}=JSON.parse(n),w=it(e,s),S=t.map((y)=>[tt(ot(B.decode(y.pubKey)),i),B.decode(y.signature)]),m=await _(a),{transactionHash:l}=await m.broadcastTx(se({bodyBytes:c,fee:{amount:h.amount,gasLimit:BigInt(h.gas),...h.payer?{payer:h.payer}:{},...h.granter?{granter:h.granter}:{}},multisigPubkey:w,prefix:i,sequence:p,signatures:new Map(S)}));return l}}function it(i,o,r=!0){return ce(i.map((n)=>ot(B.decode(n))),o,r)}function Ce(i){return B.decode(i)}function Oe({privateKey:i,message:o}){let r=re.sign(B.decode(o),i,{lowS:!0,prehash:!1});return Promise.resolve(B.encode(r))}function rt({chain:i,...o}){let r=de[i],n="index"in o?o.index||0:0,t="derivationPath"in o&&o.derivationPath?o.derivationPath:ye(pe[i],{index:n}),e=rn({chain:i,...o}),s=M(i),c;function a(){return c??=ge(o).with({phrase:nt.string},({phrase:l})=>e.getSignerFromPhrase({derivationPath:t,phrase:l})).with({signer:nt.any},({signer:l})=>Promise.resolve(l)).otherwise(()=>Promise.resolve(void 0)),c}async function p(){let l=await et(i),y=await a();if(!y)throw new K("toolbox_cosmos_no_signer");let b=j(),A=F(i,r),C=await L(l,y,{aminoTypes:A,registry:b});return{signer:y,signingClient:C}}async function h({fee:l,memo:y,msgs:b}){let{signer:A,signingClient:C}=await p(),T=(await A.getAccounts())?.[0]?.address;if(!T)throw new K("toolbox_cosmos_signer_not_defined");let k=await C.signAndBroadcast(T,b,l,y);if(k.code!==0)throw new K("core_swap_transaction_error",{code:k.code,message:k.rawLog});return k.transactionHash}async function w(){let l=await nn(i);return{[xn.Average]:l,[xn.Fast]:l,[xn.Fastest]:l}}async function S({assetValue:l,memo:y="",recipient:b,sweep:A}){let{signer:C,signingClient:T}=await p(),k=(await C.getAccounts())?.[0]?.address;if(!k)throw new K("toolbox_cosmos_no_signer");let E="signAmino"in C,sn=A?await bn({assetValue:l,sender:k}):l,H=hn({assetValue:sn,memo:y,recipient:b,sender:k});if(E){let J=I(H,i),{signatures:kn,authInfoBytes:an}=await T.sign(k,[J],s,y),un=le({authInfoBytes:an,bodyBytes:on({chain:i,memo:y,msgs:[H].map(R)}),signatures:kn});return(await T.broadcastTx(un)).transactionHash}let G=R(H),cn=I(G,i);return h({fee:s,memo:y,msgs:[cn]})}async function m(l){let{signer:y,signingClient:b}=await p(),A=(await y.getAccounts())?.[0]?.address;if(!A)throw new K("toolbox_cosmos_signer_not_defined");return b.sign(A,l.msgs,l.fee,l.memo,{accountNumber:BigInt(l.accountNumber),chainId:l.chainId,sequence:l.sequence})}return{...e,broadcastMultisigTx:Se({chain:i,prefix:r}),buildAminoMsg:hn,buildEncodedTxBody:on,convertToSignable:I,createDefaultAminoTypes:()=>F(i,r),createDefaultRegistry:j,createMultisig:it,createTransaction:Jn,deposit:S,getFees:w,importSignature:Ce,parseAminoMessageForDirectSigning:R,pubkeyToAddress:(l)=>{if(l.type==="tendermint/PubKeyMultisigThreshold")return fe(l,r);return tt(l,r)},secp256k1HdWalletFromMnemonic:be({derivationPath:me(t),prefix:r}),signAndBroadcastTransaction:h,signMultisigTx:we(i,r),signTransaction:m,signWithPrivateKey:Oe,transfer:S}}var ko=(i,o)=>{switch(i){case V.Cosmos:case V.Kujira:case V.Noble:return rn({chain:i,...o});case V.Maya:case V.THORChain:return rt({chain:i,...o});default:throw new Te("toolbox_cosmos_not_supported",{chain:i})}};export{bt as DEFAULT_COSMOS_FEE_MAINNET,At as DEFAULT_KUJI_FEE_MAINNET,wt as DEFAULT_NOBLE_FEE_MAINNET,Ve as MAYA_GAS_VALUE,qe as THORCHAIN_GAS_VALUE,Mn as USK_KUJIRA_FACTORY_DENOM,ht as YUM_KUJIRA_FACTORY_DENOM,Q as base64ToBech32,X as bech32ToBase64,hn as buildAminoMsg,Lt as buildDepositTx,on as buildEncodedTxBody,Kt as buildTransferTx,I as convertToSignable,Fn as cosmosCreateTransaction,rn as createCosmosToolbox,F as createDefaultAminoTypes,j as createDefaultRegistry,Bn as createOfflineStargateClient,L as createSigningStargateClient,_ as createStargateClient,rt as createThorchainToolbox,Jn as createTransaction,jn as depositMsgAmino,fo as estimateTransactionFee,Qn as fetchFeeRateFromSwapKit,De as fromBase64,In as getAssetFromDenom,oe as getCosmosAddressValidator,ko as getCosmosToolbox,M as getDefaultChainFee,tn as getDenomWithChain,mn as getFeeAmountForDenom,lo as getFeeRateFromSwapKit,U as getMsgSendDenom,Vn as getSignerFromPhrase,Zt as getSignerFromPrivateKey,W as getSweepAssetValue,nn as getThorchainNativeFee,R as parseAminoMessageForDirectSigning,bn as resolveThorchainSweepAssetValue,ve as toBase64,Ln as transferMsgAmino,ne as verifySignature};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{ja as Kt}from"../../chunk-exyqap7m.js";import{SwapKitError as y}from"@swapkit/helpers";import{SwapKitError as D}from"@swapkit/helpers";var T=1000n,x=100000000n*T,Tt=BigInt(Number.MAX_SAFE_INTEGER),bt=10000n,vt=16n,ot=5n*T,Et=/^\d+$/,At=/^0[23][0-9a-fA-F]{64}$/,Mt=/^[0-9a-fA-F]{64}$/,xt=new Map([["BITCOIN",x],["MILLIBITCOIN",x/1000n],["MICROBITCOIN",x/1000000n],["NANOBITCOIN",x/1000000000n],["MILLISATOSHI",1n],["SATOSHI",T]]),Ct=(t,e)=>(t+e-1n)/e;function I(t,e){if(typeof t!=="string"||!Et.test(t))throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,value:t}});return BigInt(t)}function S(t,e){if(t<0n||t>Tt)throw new D({errorKey:"toolbox_lightspark_invalid_amount",info:{context:e,msats:t.toString()}});return Number(t)}function L(t){if(!t)return;let{originalUnit:e,originalValue:d}=t,p=xt.get(e);if(p===void 0||!Number.isSafeInteger(d)||d<0)return;return BigInt(d)*p}function b(t){let e=L(t);if(e===void 0)throw new D({errorKey:"toolbox_lightspark_api_error",info:{originalUnit:t?.originalUnit,originalValue:t?.originalValue,reason:t?"unsupported currency amount":"missing currency amount"}});return e}function at(t){let e=Ct(t*vt,bt*T)*T;if(e<ot)return ot;return e}function B(t){return t==="SUCCESS"||t==="FAILED"?t:"PENDING"}function v(t){return B(t)!=="PENDING"}function C(t){return typeof t==="string"&&At.test(t)}function H(t){return typeof t==="string"&&Mt.test(t)}function U(t){return new Promise((e)=>setTimeout(e,t))}function V(t){return typeof t==="object"&&t!==null&&"code"in t&&typeof t.code==="string"?t.code:void 0}function q(t){return t instanceof Error?t.message:void 0}var K=60000,X=600000,Ht=new Set(["MAINNET","REGTEST","SIGNET","TESTNET"]);function rt({decoded:t,expectedDestinationPublicKey:e,expectedNetwork:d,nowMs:p,skewToleranceMs:f}){if(!Number.isFinite(f)||f<0||f>X)throw new y({errorKey:"toolbox_lightspark_invalid_params",info:{expirySkewToleranceMs:f,maxExpirySkewToleranceMs:X,operation:"payInvoice"}});if(!H(t.paymentHash)||t.paymentHash!==t.paymentHash.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{paymentHash:t.paymentHash,reason:"missing or malformed payment hash"}});if(!Ht.has(t.network)||t.network!==d)throw new y({errorKey:"toolbox_lightspark_network_mismatch",info:{expectedNetwork:d,invoiceNetwork:t.network,paymentHash:t.paymentHash}});if(e!==void 0){if(!C(e))throw new y({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:e,paymentHash:t.paymentHash}});if(t.destinationPublicKey?.toLowerCase()!==e.toLowerCase())throw new y({errorKey:"toolbox_lightspark_invoice_destination_mismatch",info:{expectedDestinationPublicKey:e,invoiceDestinationPublicKey:t.destinationPublicKey,paymentHash:t.paymentHash}})}let _=Date.parse(t.expiresAt);if(Number.isNaN(_))throw new y({errorKey:"toolbox_lightspark_invalid_invoice",info:{expiresAt:t.expiresAt,paymentHash:t.paymentHash,reason:"unparseable expiry"}});if(p>_+f)throw new y({errorKey:"toolbox_lightspark_invoice_expired",info:{expiresAt:t.expiresAt,expirySkewToleranceMs:f,nowMs:p,paymentHash:t.paymentHash}})}function st({amountMsats:t,invoiceAmountMsats:e,paymentHash:d}){let p=t===void 0?void 0:I(t,"payInvoice amountMsats");if(e>0n){if(p!==void 0&&p!==e)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:e.toString(),paymentHash:d,requestedAmountMsats:t}});return{payAmountMsats:e,zeroAmountInvoice:!1}}if(p===void 0)throw new y({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{invoiceAmountMsats:"0",paymentHash:d,reason:"zero-amount invoice requires an explicit amountMsats"}});if(p===0n)throw new y({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"payInvoice amountMsats",paymentHash:d,reason:"amountMsats must be positive"}});return{payAmountMsats:p,zeroAmountInvoice:!0}}import{SwapKitError as c}from"@swapkit/helpers";var ct=60,ut=10,W=3000,Rt=K;function R(t){let e=L(t.amount),d=L(t.fees);return{...e===void 0?{}:{amountMsats:e.toString()},...d===void 0?{}:{feePaidMsats:d.toString()},failureReason:t.failureReason??void 0,paymentHash:t.transactionHash??void 0,preimage:t.paymentPreimage??void 0,status:B(t.status),transactionId:t.id}}function Y(t){return t.find((e)=>e.status==="SUCCESS")??t.find((e)=>!v(e.status))}function Ot(t){if(t.status==="CLOSED")return!0;let e=t.amountPaid?.originalValue;if(e===void 0||e===null)return!1;return typeof e==="number"?e>0:!0}function Ft({paymentHash:t,prior:e,requestedAmountMsats:d}){let p=L(e.amount);if(p===d)return;throw new c({errorKey:"toolbox_lightspark_invoice_amount_mismatch",info:{operation:"payInvoice",paymentHash:t,...p===void 0?{}:{priorAmountMsats:p.toString()},priorTransactionId:e.id,reason:p===void 0?"a prior payment for this zero-amount invoice is denominated in a unit this toolbox cannot read, so it cannot be shown to match":"a prior payment for this zero-amount invoice used a different amount",requestedAmountMsats:d.toString()}})}async function dt({context:t,estimate:e,info:d,maximumFeesMsats:p,payAmountMsats:f}){let _=p!==void 0?I(p,t):at(f),P;try{P=L(await e())}catch{}if(P!==void 0&&P>_)throw new c({errorKey:"toolbox_lightspark_fee_limit_exceeded",info:{...d,estimatedFeeMsats:P.toString(),maximumFeesMsats:_.toString()}});return _}function Gt(t){let{nodeId:e}=t;if(!e||!(t.client||t.clientId&&t.clientSecret))throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClient:!!t.client,hasClientId:!!t.clientId,hasClientSecret:!!t.clientSecret,hasNodeId:!!e}});let d,p,f;async function _(n){try{return await import("@lightsparkdev/lightspark-sdk")}catch(i){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:n,reason:"@lightsparkdev/lightspark-sdk could not be loaded; install the optional peer dependency or inject a client"}},i)}}async function P(){if(t.client)return t.client;let{clientId:n,clientSecret:i}=t;if(!n||!i)throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{hasClientId:!!n,hasClientSecret:!!i,hasNodeId:!!e}});let{AccountTokenAuthProvider:o,LightsparkClient:s}=await _("createClient");return new s(new o(n,i),t.apiUrl||void 0)}function k(){return d??=P().catch((n)=>{throw d=void 0,n}),d}function z(n,i){let o=V(n);return new c({errorKey:"toolbox_lightspark_signing_key_unavailable",info:{nodeId:e,operation:i,reason:"the node signing key could not be loaded",...o===void 0?{}:{vendorErrorCode:o}}})}function Q(n){let{signingKey:i}=t;if(!i)return Promise.resolve();return f??=n.loadNodeKey(e,{key:i}).catch((o)=>{throw f=void 0,z(o,"loadNodeKey")}),f}function j(n){if(t.signingKey||t.client)return;throw new c({errorKey:"toolbox_lightspark_missing_credentials",info:{operation:n,reason:"signingKey is required to send payments"}})}async function J(n){let i;if(n.getNodeById)i=await n.getNodeById(e);else if(n.executeRawQuery){let{getLightsparkNodeQuery:o}=await _("getNode");i=await n.executeRawQuery(o(e))}else throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"the injected client implements neither getNodeById nor executeRawQuery"}});if(!i)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getNode",reason:"node not found"}});return p=i,i}async function Z(n){return p??await J(n)}async function tt({client:n,attempts:i,intervalMs:o,initial:s}){let a=s;if(v(a.status))return a;for(let r=0;r<i;r++){await U(o);try{let u=await n.getTransaction(s.id);if(u){if(a=u,v(u.status))return u}}catch{}}return a}async function pt(n,i){try{let o=await n.outgoingPaymentsForPaymentHash(i),s=Y(o);if(s)return{attemptSeq:0,existing:s};let a=await n.invoiceForPaymentHash(i);if(a&&Ot(a))throw new c({errorKey:"toolbox_lightspark_invoice_already_settled",info:{invoiceStatus:a.status,paymentHash:i}});return{attemptSeq:o.filter((r)=>r.status==="FAILED").length,existing:void 0}}catch(o){if(o instanceof c)throw o;throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"payInvoice preflight",paymentHash:i}},o)}}async function mt(n,i){try{return Y(await n.outgoingPaymentsForPaymentHash(i,["SUCCESS","PENDING"]))}catch{return}}async function ht(n,{paymentHash:i,transactionId:o}){if(o){let a=await n.getTransaction(o)??void 0;if(a)return{found:a,hashVerified:!1}}if(!i)return{found:void 0,hashVerified:!1};let s=await n.outgoingPaymentsForPaymentHash(i);return{found:Y(s)??s[s.length-1],hashVerified:!0}}async function lt(n,i,o,s){let a=!1,r,u=!1;for(let h=0;h<o;h++){if(h>0)await U(s);try{let m=await ht(n,i);if(u=!0,m.found){if(r=m.found,a=m.hashVerified,v(m.found.status))break}}catch{u=!1}}return{hashVerified:a,last:r,lookupSucceeded:u}}function O(n,i){let{timeoutSecs:o,attempts:s,intervalMs:a}=i;if(o!==void 0&&!(Number.isInteger(o)&&o>0)||s!==void 0&&!(Number.isInteger(s)&&s>=0)||a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:n,...i}})}function et(n,i){if(n instanceof c)throw n;let o=V(n);if(o==="SigningException")throw z(n,i);return o==="PaymentError"?"FAILED":"UNKNOWN"}async function ft(){let n=await k(),i=await J(n),o=i.balances?.availableToSendBalance??i.localBalance;if(!o)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"getBalance",reason:"node reports no spendable balance"}});return{spendableMsats:b(o).toString(),...i.remoteBalance?{inboundCapacityMsats:b(i.remoteBalance).toString()}:{}}}async function nt(n){if(!n||typeof n!=="string")throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{reason:"empty invoice"}});let i=await k(),o;try{o=await i.decodeInvoice(n)}catch(s){throw new c({errorKey:"toolbox_lightspark_api_error",info:{operation:"decodeInvoice"}},s)}if(!o?.paymentHash)throw new c({errorKey:"toolbox_lightspark_invalid_invoice",info:{operation:"decodeInvoice",reason:"decoded invoice has no payment hash"}});return{amountMsats:b(o.amount).toString(),createdAt:o.createdAt,destinationPublicKey:o.destination?.publicKey??void 0,expiresAt:o.expiresAt,memo:o.memo??void 0,network:o.bitcoinNetwork,paymentHash:o.paymentHash}}async function gt({amountMsats:n,memo:i,expirySecs:o}){let s=I(n,"createInvoice"),r=await(await k()).createInvoiceWithDetails(e,S(s,"createInvoice"),i??"",void 0,o);if(!(r?.data?.encodedPaymentRequest&&r.data.paymentHash))throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createInvoice",reason:"invoice creation returned no invoice"}});return{amountMsats:b(r.data.amount).toString(),createdAt:r.data.createdAt,encodedInvoice:r.data.encodedPaymentRequest,expiresAt:r.data.expiresAt,paymentHash:r.data.paymentHash}}async function yt({amountMsats:n,memo:i}){let o=I(n,"createTestModeInvoice"),s=S(o,"createTestModeInvoice"),a=await k(),r;try{r=await a.createTestModeInvoice(e,s,i)}catch(u){throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice"}},u)}if(!r)throw new c({errorKey:"toolbox_lightspark_api_error",info:{nodeId:e,operation:"createTestModeInvoice",reason:"test mode invoices require regtest credentials"}});return{encodedInvoice:r}}async function _t({invoice:n,amountMsats:i,maximumFeesMsats:o,destinationPublicKey:s,timeoutSecs:a=ct,attempts:r=ut,intervalMs:u=W,expirySkewToleranceMs:h=K}){j("payInvoice"),O("payInvoice",{attempts:r,intervalMs:u,timeoutSecs:a});let m=await k(),l=await nt(n),F=await Z(m);rt({decoded:l,expectedDestinationPublicKey:s,expectedNetwork:F.bitcoinNetwork,nowMs:Date.now(),skewToleranceMs:h});let{payAmountMsats:g,zeroAmountInvoice:w}=st({amountMsats:i,invoiceAmountMsats:I(l.amountMsats,"payInvoice"),paymentHash:l.paymentHash}),E=w?S(g,"payInvoice"):void 0,{attemptSeq:A,existing:G}=await pt(m,l.paymentHash);if(G){if(w)Ft({paymentHash:l.paymentHash,prior:G,requestedAmountMsats:g});return{...R(G),paymentHash:l.paymentHash,replayedPriorPayment:!0}}let St=await dt({context:"payInvoice maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForInvoice(e,n,E),info:{paymentHash:l.paymentHash},maximumFeesMsats:o,payAmountMsats:g});await Q(m);let Lt=S(St,"payInvoice maximumFeesMsats"),Pt=`${l.paymentHash}:${A}`,M;try{M=await m.payInvoice(e,n,Lt,a,E,Pt)}catch(it){if(et(it,"payInvoice")==="FAILED")return{failureReason:q(it),paymentHash:l.paymentHash,status:"FAILED"};M=await mt(m,l.paymentHash)}if(!M)return{paymentHash:l.paymentHash,status:"PENDING"};let Nt=await tt({attempts:r,client:m,initial:M,intervalMs:u}),N={...R(Nt),paymentHash:l.paymentHash};if(w&&N.status!=="FAILED"&&N.amountMsats!==g.toString())return{...N,reconciliationRequired:{reason:N.amountMsats===void 0?"AMOUNT_UNVERIFIABLE":"AMOUNT_MISMATCH",requestedAmountMsats:g.toString()},status:"PENDING"};return N}async function kt({destinationPublicKey:n,amountMsats:i,maximumFeesMsats:o,timeoutSecs:s=ct,attempts:a=ut,intervalMs:r=W}){if(j("sendPayment"),O("sendPayment",{attempts:a,intervalMs:r,timeoutSecs:s}),!C(n))throw new c({errorKey:"toolbox_lightspark_invalid_destination",info:{destinationPublicKey:n}});let u=I(i,"sendPayment");if(u===0n)throw new c({errorKey:"toolbox_lightspark_invalid_amount",info:{context:"sendPayment",reason:"amountMsats must be positive"}});let h=S(u,"sendPayment"),m=await k(),l=await dt({context:"sendPayment maximumFeesMsats",estimate:()=>m.getLightningFeeEstimateForNode(e,n,h),info:{destinationPublicKey:n},maximumFeesMsats:o,payAmountMsats:u}),F=S(l,"sendPayment maximumFeesMsats");await Q(m);let g={amountMsats:u.toString(),destinationPublicKey:n,sentAfter:new Date(Date.now()-Rt).toISOString()},w;try{w=await m.sendPayment(e,n,s,h,F)}catch(A){if(et(A,"sendPayment")==="FAILED")return{...g,failureReason:q(A),status:"FAILED"};return{...g,status:"PENDING"}}if(!w)return{...g,status:"PENDING"};let E=await tt({attempts:a,client:m,initial:w,intervalMs:r});return{...g,...R(E)}}async function It({transactionId:n,paymentHash:i,attempts:o=1,intervalMs:s=W}){if(!n&&!i)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",reason:"transactionId or paymentHash is required"}});O("getTransactionStatus",{attempts:o,intervalMs:s});let a=i?.toLowerCase();if(a!==void 0&&!H(a))throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:i,reason:"malformed payment hash"}});let r=await k(),{hashVerified:u,last:h,lookupSucceeded:m}=await lt(r,{paymentHash:a,transactionId:n},o,s);if(!h)return{paymentHash:a,status:m?"NOT_FOUND":"UNKNOWN",transactionId:n};if(a&&!u&&h.transactionHash!==a)throw new c({errorKey:"toolbox_lightspark_invalid_params",info:{operation:"getTransactionStatus",paymentHash:a,reason:h.transactionHash?"paymentHash does not match the transaction":"transaction carries no payment hash to verify against",transactionHash:h.transactionHash??void 0,transactionId:h.id}});return{...R(h),paymentHash:a??h.transactionHash??void 0}}async function wt({numTransactions:n,afterDate:i}={}){let o=await k(),s=await Z(o);return(await o.getRecentTransactions(e,n,s.bitcoinNetwork,i)).map((r)=>{let u=L(r.amount);return{...u===void 0?{}:{amountMsats:u.toString()},createdAt:r.createdAt,destinationId:r.destinationId??void 0,id:r.id,resolvedAt:r.resolvedAt??void 0,status:r.status,transactionHash:r.transactionHash??void 0,typename:r.typename}})}return{createInvoice:gt,createTestModeInvoice:yt,decodeInvoice:nt,getBalance:ft,getTransactionStatus:It,listTransactions:wt,payInvoice:_t,sendPayment:kt}}export{X as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MAX_MS,K as LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS,Gt as getLightsparkToolbox};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as
|
|
1
|
+
import{ia as z}from"../../chunk-xdkdc1f0.js";import{ja as f}from"../../chunk-exyqap7m.js";import{AssetValue as x,Chain as H,DerivationPath as I,derivationPathToString as et,getChainConfig as N,getRPCUrl as W,NetworkDerivationPath as at,SwapKitError as i,updateDerivationPath as nt}from"@swapkit/helpers";import{match as M,P}from"ts-pattern";var D="0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d",j="0x049d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",U="0x01a736d6ed154502257f02b1ccdf4d9d1089f80811cd6acad48e6b6a9d1f2003";function K(o){if(!o)return!1;return/^0x[0-9a-fA-F]{1,64}$/.test(o)}async function E({phrase:o,derivationPath:c=I.STRK}){let{HDKey:_}=await import("@scure/bip32"),{mnemonicToSeedSync:v}=await import("@scure/bip39"),{ec:u,hash:p,encode:d,CallData:k}=await import("starknet"),w=v(o),S=_.fromMasterSeed(w).derive(c);if(!S.privateKey)throw new i("toolbox_starknet_no_signer");let C=d.addHexPrefix(Buffer.from(S.privateKey).toString("hex")),y=u.starkCurve.grindKey(C),g=d.addHexPrefix(y),m=u.starkCurve.getStarkKey(g),F=k.compile([m,0]);return{address:p.calculateContractAddressFromHash(m,U,F,0),privateKey:g,publicKey:m}}async function Z({phrase:o,derivationPath:c=I.STRK}){let{Account:_,RpcProvider:v}=await import("starknet"),{privateKey:u,address:p}=await E({derivationPath:c,phrase:o}),d=await W(H.Starknet),k=new v({nodeUrl:d});return new _({address:p,provider:k,signer:u})}function rt(o){let c=H.Starknet,_=o&&"index"in o?o.index||0:0,v=et(o&&"derivationPath"in o&&o.derivationPath?o.derivationPath:nt(at[c],{index:_})),u,p,d,k=Boolean(o&&"walletDeploysAccount"in o&&o.walletDeploysAccount);async function w(){if(p)return p;let{RpcProvider:e}=await import("starknet"),t=await W(c);return p=new e({nodeUrl:t}),p}async function A(e){let t=await w(),a=e||await g();if(!a)return!1;try{return await t.getClassHashAt(a),!0}catch(n){if(n instanceof Error&&n.message.includes("Contract not found"))return!1;let r=n;if(r?.code===20||r?.code===19)return!1;throw n}}async function S(){let{CallData:e,hash:t}=await import("starknet"),a=await w(),n=await y();if(!n)throw new i("toolbox_starknet_no_signer");if(!d)throw new i({errorKey:"toolbox_starknet_account_not_deployed",info:{message:"Cannot deploy account: public key not available. Use phrase-based wallet initialization."}});if(await A())return n.address;let s=e.compile([d,0]);if(t.calculateContractAddressFromHash(d,U,s,0).toLowerCase()!==n.address.toLowerCase())throw new i({errorKey:"toolbox_starknet_account_not_deployed",info:{message:"Address mismatch during deployment verification"}});let h={addressSalt:d,classHash:U,constructorCalldata:s},{transaction_hash:T}=await n.deployAccount(h);return await a.waitForTransaction(T),T}async function C(){if(k)return;if(!await A()){if(!d)throw new i({errorKey:"toolbox_starknet_account_not_deployed",info:{message:"Starknet account is not deployed and cannot be auto-deployed without public key. Use phrase-based wallet initialization."}});await S()}}async function y(){if(u)return u;return u=await M(o).with({phrase:P.string},async({phrase:e})=>{let{Account:t}=await import("starknet"),{privateKey:a,address:n,publicKey:r}=await E({derivationPath:v,phrase:e});d=r;let s=await w();return new t({address:n,provider:s,signer:a})}).with({address:P.string,privateKey:P.string},async({privateKey:e,address:t})=>{let{Account:a}=await import("starknet"),n=await w();return new a({address:t,provider:n,signer:e})}).with({signer:P.instanceOf(Object)},({signer:e})=>e).otherwise(()=>{return}),u}async function g(){return(await y())?.address??""}async function m(e,t){let a=await w(),{uint256:n,CallData:r}=await import("starknet"),[s="0",l="0"]=await a.callContract({calldata:r.compile({account:e}),contractAddress:t,entrypoint:"balanceOf"});return n.uint256ToBN({high:l,low:s})}async function F(e){let{baseDecimal:t}=N(c),a=[],n=[D,j];for(let r of n)try{let s=await m(e,r);M(r).with(D,()=>{a.push(x.from({chain:c,fromBaseDecimal:t,value:s}))}).with(j,()=>{if(s>0n)a.push(x.from({asset:`${c}.ETH-${r}`,fromBaseDecimal:t,value:s}))}).otherwise(()=>{})}catch{}return a}async function R(e){let t=e||await g();if(t){let{Account:a}=await import("starknet"),n=await w();return new a({address:t,provider:n,signer:"0x0"})}throw new i({errorKey:"toolbox_starknet_fee_estimation_failed",info:{message:"Estimating fee needs a valid sender address or signer"}})}async function q(e,t){try{let a=await R(t),{overall_fee:n}=await a.estimateInvokeFee(e,{skipValidate:!0});if(n<=0n)throw new i({errorKey:"toolbox_starknet_fee_estimation_failed",info:{message:"Sweep fee estimation returned a non-positive fee",sender:t}});return n}catch(a){throw new i({errorKey:"toolbox_starknet_fee_estimation_failed",info:{message:"Unable to estimate the sweep fee. Verify RPC availability and that the sender account is deployed.",sender:t}},a)}}async function O(e,t){let a=await L(e),n=t.isGasAsset?a.find(({isGasAsset:r})=>r):a.find(({address:r})=>r?.toLowerCase()===t.address?.toLowerCase());if(n)return n.getBaseValue("bigint");if(t.isGasAsset)return m(e,D);if(t.address)return m(e,t.address);return 0n}async function B({recipient:e,assetValue:t,sender:a,sweep:n}){let{CallData:r,uint256:s}=await import("starknet");if(!K(e))throw new i("core_transaction_invalid_recipient_address",{address:e});let l=t.isGasAsset?D:t.address;if(!l)throw new i("toolbox_starknet_invalid_address",{address:l,assetValue:t});let h=t.getBaseValue("bigint");if(n){let b=a??await g();if(!K(b))throw new i("core_transaction_invalid_sender_address",{address:b});if(t.isGasAsset){let V=[{calldata:r.compile([e,s.bnToUint256(1n)]),contractAddress:l,entrypoint:"transfer"}],tt=await q(V,b);h=await O(b,t)-tt}else h=await O(b,t);if(h<=0n)throw new i({errorKey:"toolbox_sweep_amount_too_low",info:{amount:h.toString(),asset:t.toString()}})}let T=s.bnToUint256(h);return[{calldata:r.compile([e,T]),contractAddress:l,entrypoint:"transfer"}]}async function J({recipient:e,assetValue:t,sender:a}){let{baseDecimal:n}=N(H.Starknet);try{let r=await B({assetValue:t,recipient:e}),l=await(await R(a)).estimateInvokeFee(r,{skipValidate:!0});if(l?.overall_fee)return x.from({chain:c,fromBaseDecimal:n,value:l.overall_fee})}catch(r){throw new i("toolbox_starknet_fee_estimation_failed",r)}return x.from({chain:c,value:"0.00001"})}async function Q({recipient:e,assetValue:t,memo:a,sweep:n}){let r=await y();if(!r)throw new i("toolbox_starknet_no_signer");await C();let s=await B({assetValue:t,memo:a,recipient:e,sender:r.address,sweep:n});return(await r.execute(s)).transaction_hash}async function X(e){let t=await y();if(!t)throw new i("toolbox_starknet_no_signer");let a=await t.signMessage(e);return Array.isArray(a)?a:[a.r.toString(),a.s.toString()]}async function G(e){let t=await y();if(!t)throw new i("toolbox_starknet_no_signer");return await C(),(await t.execute(e)).transaction_hash}function Y(e){return G(e)}async function L(e,t=!0){try{return await z(c)(e,t)}catch{return F(e)}}return{broadcastTransaction:G,createKeysForPath:Z,createTransaction:B,deployAccount:S,estimateTransactionFee:J,getAddress:g,getBalance:L,getProvider:w,isAccountDeployed:A,signAndBroadcastTransaction:Y,signMessage:X,transfer:Q,validateAddress:K}}export{E as deriveStarknetKeys,rt as getStarknetToolbox,Z as starknetCreateKeysForPath,K as validateStarknetAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ja as
|
|
1
|
+
import{ja as p}from"../../chunk-exyqap7m.js";import{AssetValue as h,Chain as c,derivationPathToString as ne,getChainConfig as L,getRPCUrl as F,SKConfig as re,SwapKitError as d}from"@swapkit/helpers";import{match as se,P as H}from"ts-pattern";var ae=/^G[A-Z2-7]{55}$/,oe=/^[A-Za-z0-9]{1,12}$/,W=2,ie=600000,k;async function j(e){if(k&&Date.now()-k.timestamp<ie)return k.value;let l=(await e.ledgers().order("desc").limit(1).call()).records[0]?.base_reserve_in_stroops;if(l===void 0)throw new d({errorKey:"toolbox_stellar_balance_error",info:{reason:"base_reserve_unavailable"}});return k={timestamp:Date.now(),value:l},l}function U(e){return h.from({chain:c.Stellar,value:e}).getBaseValue("bigint")}function le(e){let{baseDecimal:r}=L(c.Stellar);return h.from({chain:c.Stellar,fromBaseDecimal:r,value:e}).getValue("string")}function Z({balance:e,baseReserveInStroops:r,numSponsored:l,numSponsoring:w,sellingLiabilities:S,subentryCount:f}){let _=U(e),b=U(S),v=W+f+w-l,E=BigInt(v)*BigInt(r),R=_-E-b;return R>0n?R:0n}function ce({account:e,assetValue:r,baseReserveInStroops:l,fee:w}){let S=e.balances.find((b)=>b.asset_type==="native"),_=(S?Z({balance:S.balance,baseReserveInStroops:l,numSponsored:e.num_sponsored,numSponsoring:e.num_sponsoring,sellingLiabilities:S.selling_liabilities,subentryCount:e.subentry_count}):0n)-BigInt(w);if(_<=0n)throw new d({errorKey:"toolbox_sweep_amount_too_low",info:{asset:r.toString(),reason:"spendable balance does not cover the transaction fee"}});return _}function ue({baseReserveInStroops:e,sweepAmountInStroops:r}){if(r===void 0||e===void 0)return;let l=BigInt(W)*BigInt(e);if(r<l)throw new d({errorKey:"toolbox_sweep_amount_too_low",info:{amountInStroops:r,minimumStartingBalanceInStroops:l,reason:"starting balance is below the Stellar account minimum"}})}function de({account:e,assetCode:r,assetValue:l,issuer:w,sweep:S}){if(!S)return l.getValue("string");let f=e.balances.find((_)=>("asset_code"in _)&&_.asset_code===r&&_.asset_issuer===w)?.balance??"0";if(U(f)<=0n)throw new d({errorKey:"toolbox_sweep_amount_too_low",info:{asset:l.toString(),balance:f,reason:"trust-line balance is not positive"}});return f}function fe(e){if(!e)return;if(new TextEncoder().encode(e).length>28)throw new d("helpers_invalid_memo_type")}function z(e){if(!e||typeof e!=="string"||!e.startsWith("G")||e.length!==56)return!1;return ae.test(e)}function O(e){if(typeof e!=="object"||e===null)return;let r="response"in e?e.response:void 0;return typeof r?.status==="number"?r.status:void 0}function me(e){return O(e)===504}function ge(e){return e.hash?.().toString("hex")}function Se(e){return[...new Set([e,...re.get("rpcUrls")[c.Stellar]])].filter(Boolean)}async function q(e){if(!z(e))return!1;try{let{StrKey:r}=await import("@stellar/stellar-sdk");return r.isValidEd25519PublicKey(e)}catch{return!1}}async function V(e){let{address:r,ticker:l}=e,w=r?await q(r):!1;if(e.chain!==c.Stellar||e.isGasAsset||!oe.test(l)||!r||!w)throw new d({errorKey:"helpers_invalid_asset_identifier",info:{identifier:e.toString()}});return{assetCode:l,issuer:r}}function we(e={}){let r;async function l(t){if(e.derivationPath&&(e.derivationPath[3]||e.derivationPath[4]))throw new d("toolbox_derivation_slot_unsupported",{chain:c.Stellar,derivationPath:e.derivationPath});let n=e.index??0;if(!e.derivationPath&&(!Number.isInteger(n)||n<0))throw new d("toolbox_derivation_slot_unsupported",{chain:c.Stellar,index:n});let o=e.derivationPath?ne(e.derivationPath.slice(0,3)):`m/44'/148'/${n}'`,{HDKey:s}=await import("micro-key-producer/slip10.js"),{mnemonicToSeedSync:a}=await import("@scure/bip39"),{Keypair:i}=await import("@stellar/stellar-sdk"),m=s.fromMasterSeed(a(t)).derive(o,!0),u=i.fromRawEd25519Seed(Buffer.from(m.privateKey));return{getAddress:()=>u.publicKey(),signTransaction:(g)=>(g.sign(u),g)}}async function w(){if(r)return r;return r=await se(e).with({phrase:H.string.minLength(1)},({phrase:t})=>l(t)).with({signer:H.not(H.nullish)},({signer:t})=>t).otherwise(()=>{return}),r}async function S(){let t=await w();if(!t)throw new d("toolbox_stellar_no_signer");return t}async function f(t){let{Horizon:n}=await import("@stellar/stellar-sdk"),o=t||await F(c.Stellar);return new n.Server(o)}async function _(t,n){for(let o of n)try{return(await(await f(o)).transactions().transaction(t).call()).hash||t}catch{}return}async function b(t,n){let o=await F(c.Stellar),s=Se(o),a=ge(t),i;for(let m of s)try{let u=await f(m),{hash:g}=await u.submitTransaction(t);return g}catch(u){if(i=u,!me(u))break;let g=a?await _(a,s):void 0;if(g)return g}throw new d(n,i)}async function v(){let t=await w();return t?t.getAddress():""}async function E(t){let n=t||await v();if(!n)throw new d("toolbox_stellar_account_not_found");let o=await f(),[s,a]=await Promise.allSettled([o.loadAccount(n),j(o)]);if(s.status==="rejected"){let i=s.reason;if(O(i)===404)return[h.from({chain:c.Stellar,value:0})];throw i}if(a.status==="rejected")throw a.reason;return s.value.balances.map((i)=>{if(i.asset_type==="native"){let g=Z({balance:i.balance,baseReserveInStroops:a.value,numSponsored:s.value.num_sponsored,numSponsoring:s.value.num_sponsoring,sellingLiabilities:i.selling_liabilities,subentryCount:s.value.subentry_count}),{baseDecimal:B}=L(c.Stellar);return h.from({chain:c.Stellar,fromBaseDecimal:B,value:g})}let m="asset_code"in i?i.asset_code:"",u="asset_issuer"in i?i.asset_issuer:"";return h.from({asset:`${c.Stellar}.${m}-${u}`,asyncTokenLookup:!1,value:i.balance})})}async function R({address:t,assetValue:n}){if(n.chain!==c.Stellar)throw new d({errorKey:"toolbox_stellar_trustline_asset_invalid",info:{asset:n.toString()}});if(n.isGasAsset)return!0;if(!n.address)throw new d({errorKey:"toolbox_stellar_trustline_asset_invalid",info:{asset:n.toString(),reason:"missing issuer"}});let o=await f(),s;try{s=await o.loadAccount(t)}catch(a){if(O(a)===404)return!1;throw a}return s.balances.some((a)=>("asset_code"in a)&&a.asset_code===n.ticker&&a.asset_issuer===n.address)}async function M({recipient:t,assetValue:n,memo:o,sender:s,sweep:a}){if(fe(o),!await q(t))throw new d("core_transaction_invalid_recipient_address");let m=s||await v();if(!m)throw new d("toolbox_stellar_no_signer");let{Asset:u,Memo:g,Networks:B,Operation:y,TransactionBuilder:D}=await import("@stellar/stellar-sdk"),T=await f(),[P,x,K]=await Promise.all([T.fetchBaseFee(),T.loadAccount(m),a&&n.isGasAsset?j(T):Promise.resolve(void 0)]),C=new D(x,{fee:String(P),networkPassphrase:B.PUBLIC});if(n.isGasAsset){let A=a&&K!==void 0?ce({account:x,assetValue:n,baseReserveInStroops:K,fee:P}):void 0,I=A===void 0?n.getValue("string"):le(A);try{await T.loadAccount(t),C.addOperation(y.payment({amount:I,asset:u.native(),destination:t}))}catch{ue({baseReserveInStroops:K,sweepAmountInStroops:A}),C.addOperation(y.createAccount({destination:t,startingBalance:I}))}}else{let{assetCode:A,issuer:I}=await V(n),te=de({account:x,assetCode:A,assetValue:n,issuer:I,sweep:a});C.addOperation(y.payment({amount:te,asset:new u(A,I),destination:t}))}if(o)C.addMemo(g.text(o));return C.setTimeout(30).build()}async function N({assetValue:t,limit:n,sender:o}){let s=o||await v();if(!s)throw new d("toolbox_stellar_no_signer");let{Asset:a,Networks:i,Operation:m,TransactionBuilder:u}=await import("@stellar/stellar-sdk"),{assetCode:g,issuer:B}=await V(t),y=await f(),[D,T]=await Promise.all([y.fetchBaseFee(),y.loadAccount(s)]),P=new a(g,B),x=n!==void 0?m.changeTrust({asset:P,limit:n}):m.changeTrust({asset:P});return new u(T,{fee:String(D),networkPassphrase:i.PUBLIC}).addOperation(x).setTimeout(30).build()}async function X(t){let n=await S(),{TransactionBuilder:o,Networks:s}=await import("@stellar/stellar-sdk");return n.signTransaction(o.fromXDR(t.toXDR(),s.PUBLIC))}function G(t){return b(t,"toolbox_stellar_broadcast_error")}async function J({recipient:t,assetValue:n,memo:o,sweep:s}){let a=await S(),i=await a.getAddress(),m=await M({assetValue:n,memo:o,recipient:t,sender:i,sweep:s}),u=await a.signTransaction(m);return b(u,"toolbox_stellar_transaction_failed")}async function Q({assetValue:t,limit:n}){let o=await S(),s=await N({assetValue:t,limit:n,sender:await o.getAddress()}),a=await o.signTransaction(s);return b(a,"toolbox_stellar_transaction_failed")}async function Y(t){let n=await X(t);return G(n)}async function ee(){let{baseDecimal:t}=L(c.Stellar);try{let s=(await(await f()).feeStats()).fee_charged.p50;return h.from({chain:c.Stellar,fromBaseDecimal:t,value:s})}catch{return h.from({chain:c.Stellar,fromBaseDecimal:t,value:"100"})}}return{broadcastTransaction:G,createTransaction:M,createTrustline:Q,createTrustlineTransaction:N,estimateTransactionFee:ee,getAddress:v,getBalance:E,hasTrustline:R,signAndBroadcastTransaction:Y,signTransaction:X,transfer:J,validateAddress:z}}export{we as getStellarToolbox,z as validateStellarAddress};
|
package/dist/src/ton/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as U}from"../../chunk-xdkdc1f0.js";import{ja as
|
|
1
|
+
import{ia as U}from"../../chunk-xdkdc1f0.js";import{ja as w}from"../../chunk-exyqap7m.js";import{AssetValue as et,Chain as g,getChainConfig as nt,getRPCUrl as ot,NetworkDerivationPath as rt,SwapKitError as d,SwapKitNumber as st}from"@swapkit/helpers";import{Address as i,beginCell as x,Cell as j,external as at,internal as it,loadStateInit as ct,SendMode as N,storeMessage as dt,toNano as L}from"@ton/core";import{match as F,P as B}from"ts-pattern";var lt=260734629,ut=L("0.01"),ft=L("0.05"),G=N.PAY_GAS_SEPARATELY+N.IGNORE_ERRORS,gt=N.CARRY_ALL_REMAINING_BALANCE+N.IGNORE_ERRORS,Tt=60000,O,v=0;async function wt(){let u=Date.now();if(O&&u-v<Tt)return O;let{getHttpEndpoint:p}=await import("@orbs-network/ton-access");return O=await p(),v=u,O}async function pt(){try{return await ot(g.Ton)}catch{return await wt()}}function Nt(u={}){let p,S,A;async function f(){if(!p){let{TonClient:t}=await import("@ton/ton"),e=u.provider??await pt();p=new t({endpoint:e})}return p}async function h(){return(await b()).address.toString()}async function C(){if(A)return A;return A=await F(u).with({phrase:B.string},async({phrase:t,derivationPath:e,index:n=0})=>{let r=rt[g.Ton],o=e?.some((a,c)=>a!==r[c]);if(n||o)throw new d("toolbox_derivation_slot_unsupported",{chain:g.Ton,derivationPath:e,index:n});let{mnemonicToWalletKey:s}=await import("@ton/crypto");return s(t.split(" "))}).with({signer:B.any},({signer:t})=>t).otherwise(()=>{return}),A}async function b(t){if(!S||t){let e=await C(),n=await f(),r=t||e;if(!r)throw new d("core_wallet_connection_not_found");let{WalletContractV4:o}=await import("@ton/ton"),s=o.create({publicKey:r.publicKey,workchain:0});S=n.open(s)}return S}let J=U(g.Ton);async function q({assetValue:t,recipient:e,memo:n,sender:r,sweep:o,jettonWalletAddress:s}){if(t.isGasAsset){if(o){let tt=r||await h(),K=await(await f()).getBalance(i.parse(tt));if(K<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:K.toString()})}let Z=n?D(n).toBoc().toString("base64"):void 0;return[{address:e,amount:t.getBaseValue("string"),payload:Z}]}let a=t.address;if(!a)throw new d({errorKey:"core_swap_contract_not_found",info:{asset:t.toString()}});let c=r??await h(),l=s?i.parse(s):await I({jettonMasterAddress:a,ownerAddress:c}),y=l.toString(),_=i.parse(e),T=i.parse(c),m=o?await H(l):t.getBaseValue("bigint");if(o&&m<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:m.toString()});let Q=n?D(n):void 0,X=V({destinationAddress:_,forwardPayload:Q,jettonAmount:m,responseAddress:T});return[{address:y,amount:ft.toString(),payload:X.toBoc().toString("base64")}]}async function M({sender:t,sweep:e,...n}){let r=e&&n.assetValue.isGasAsset?gt:G;return{messages:await q({...n,sender:t,sweep:e}),sendMode:r}}function k(t){if(!Array.isArray(t))return t;let[e]=t;return{messages:t.map(({sendMode:r,...o})=>o),sendMode:e?.sendMode??G}}function E(t){return t.map((e)=>{let n=e.payload?j.fromBase64(e.payload):void 0,r=e.stateInit?ct(j.fromBase64(e.stateInit).asSlice()):void 0,o=i.parse(e.address),s=i.isFriendly(e.address)?i.parseFriendly(e.address).isBounceable:!0;return it({body:n,bounce:s,init:r,to:o,value:BigInt(e.amount)})})}async function P(t){let e=await C(),n=await b();if(!n||!e)throw new d("core_wallet_connection_not_found");let r=await f(),{state:o}=await r.getContractState(n.address),s=o==="active",a=s?await n.getSeqno():0,{messages:c,sendMode:l}=k(t),y=n.createTransfer({messages:E(c),secretKey:e.secretKey,sendMode:l,seqno:a}),_=at({body:y,init:s?void 0:n.init,to:n.address});return x().store(dt(_)).endCell()}async function W(t){return await(await f()).sendFile(t.toBoc()),t.hash().toString("hex")}async function R(t){let e=await P(t);return W(e)}async function Y({assetValue:t,recipient:e,memo:n,sweep:r}){let o=await M({assetValue:t,memo:n,recipient:e,sweep:r});return R(o)}async function z({sender:t,...e}){let{baseDecimal:n}=nt(g.Ton),r=await F(t).with(B.string,(a)=>i.parseFriendly(a).address).otherwise(async()=>(await b()).address);if(!r)throw new d("toolbox_fee_estimation_failed",{chain:g.Ton});let o=et.from({chain:g.Ton,value:"0.01"}),s=await f();try{let a=await M({sender:t,...e}),c=await C(),l=await b();if(!l||!c)return o;let y=await l.getSeqno(),_=l.createTransfer({messages:E(a.messages),secretKey:c.secretKey,sendMode:a.sendMode,seqno:y}),{source_fees:T}=await s.estimateExternalMessageFee(r,{body:_,ignoreSignature:!0,initCode:null,initData:null}),m=T.in_fwd_fee+T.storage_fee+T.gas_fee+T.fwd_fee;return o.set(st.fromBigInt(BigInt(m),n))}catch{return o}}async function I({jettonMasterAddress:t,ownerAddress:e}){try{let n=await f(),r=i.parse(t),o=i.parse(e),{JettonMaster:s}=await import("@ton/ton");return await n.open(s.create(r)).getWalletAddress(o)}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonMasterAddress:t,ownerAddress:e}})}}async function H(t){try{let e=await f(),{JettonWallet:n}=await import("@ton/ton");return await e.open(n.create(t)).getBalance()}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonWalletAddress:t.toString()}})}}function V({jettonAmount:t,destinationAddress:e,responseAddress:n,forwardAmount:r=ut,forwardPayload:o}){let s=x().storeUint(lt,32).storeUint(0,64).storeCoins(t).storeAddress(e).storeAddress(n).storeBit(0).storeCoins(r);if(o)s.storeBit(1).storeRef(o);else s.storeBit(0);return s.endCell()}function D(t){return x().storeUint(0,32).storeStringTail(t).endCell()}return{broadcastTransaction:W,createTransaction:M,estimateTransactionFee:z,getAddress:h,getBalance:J,getJettonWalletAddress:I,sign:P,signAndBroadcastTransaction:R,transfer:Y,validateAddress:yt}}function yt(u){try{return i.parse(u),!0}catch{return!1}}export{Nt as getTONToolbox,yt as validateTonAddress};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type CardanoVkeyWitness = {
|
|
2
|
+
publicKey: Uint8Array;
|
|
3
|
+
signature: Uint8Array;
|
|
4
|
+
};
|
|
5
|
+
export declare function decodeCardanoTransaction(txHex: string): Promise<{
|
|
6
|
+
body: Map<number, unknown>;
|
|
7
|
+
bodyHash: string;
|
|
8
|
+
}>;
|
|
9
|
+
export declare function addCardanoVkeyWitnesses(txHex: string, witnesses: CardanoVkeyWitness[]): Promise<string>;
|
|
10
|
+
export declare function decodeCardanoWitnessSet(witnessSetHex: string): Promise<{
|
|
11
|
+
publicKey: Uint8Array<ArrayBuffer>;
|
|
12
|
+
signature: Uint8Array<ArrayBuffer>;
|
|
13
|
+
}[]>;
|
|
14
|
+
export declare function getCardanoAddressFromBytes(addressBytes: Uint8Array): Promise<string>;
|
|
15
|
+
export declare function getCardanoPublicKeyHash(publicKey: Uint8Array): Promise<Buffer<ArrayBufferLike>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LightsparkCurrencyAmount, LightsparkPaymentStatus } from "./types";
|
|
2
|
+
export declare function parseMsats(value: string, context: string): bigint;
|
|
3
|
+
export declare function msatsToSdkNumber(msats: bigint, context: string): number;
|
|
4
|
+
export declare function tryCurrencyAmountToMsats(amount: LightsparkCurrencyAmount | null | undefined): bigint | undefined;
|
|
5
|
+
export declare function currencyAmountToMsats(amount: LightsparkCurrencyAmount | null | undefined): bigint;
|
|
6
|
+
export declare function defaultMaximumFeesMsats(amountMsats: bigint): bigint;
|
|
7
|
+
export declare function mapPaymentStatus(status: string): LightsparkPaymentStatus;
|
|
8
|
+
export declare function isTerminalPaymentStatus(status: string): boolean;
|
|
9
|
+
export declare function isCompressedNodePublicKey(value: string): boolean;
|
|
10
|
+
export declare function isPaymentHash(value: string): boolean;
|
|
11
|
+
export declare function sleep(ms: number): Promise<void>;
|
|
12
|
+
export declare function sdkErrorCode(error: unknown): string | undefined;
|
|
13
|
+
export declare function sdkErrorMessage(error: unknown): string | undefined;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { LightsparkDecodedInvoice } from "./types";
|
|
2
|
+
export declare const LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS = 60000;
|
|
3
|
+
export declare const LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MAX_MS = 600000;
|
|
4
|
+
export declare function assertPayableLightningInvoice({ decoded, expectedDestinationPublicKey, expectedNetwork, nowMs, skewToleranceMs, }: {
|
|
5
|
+
decoded: LightsparkDecodedInvoice;
|
|
6
|
+
expectedDestinationPublicKey?: string;
|
|
7
|
+
expectedNetwork: string;
|
|
8
|
+
nowMs: number;
|
|
9
|
+
skewToleranceMs: number;
|
|
10
|
+
}): void;
|
|
11
|
+
export declare function resolveLightningPaymentAmountMsats({ amountMsats, invoiceAmountMsats, paymentHash, }: {
|
|
12
|
+
amountMsats?: string;
|
|
13
|
+
invoiceAmountMsats: bigint;
|
|
14
|
+
paymentHash: string;
|
|
15
|
+
}): {
|
|
16
|
+
payAmountMsats: bigint;
|
|
17
|
+
zeroAmountInvoice: boolean;
|
|
18
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { LightsparkBalance, LightsparkCreateInvoiceParams, LightsparkCreateInvoiceResult, LightsparkCreateTestModeInvoiceParams, LightsparkDecodedInvoice, LightsparkListTransactionsParams, LightsparkPayInvoiceParams, LightsparkPayInvoiceResult, LightsparkSendPaymentParams, LightsparkSendPaymentResult, LightsparkToolboxParams, LightsparkTrackingOutcome, LightsparkTransactionStatusParams, LightsparkTransactionSummary } from "./types";
|
|
2
|
+
export declare function getLightsparkToolbox(params: LightsparkToolboxParams): {
|
|
3
|
+
createInvoice: ({ amountMsats, memo, expirySecs, }: LightsparkCreateInvoiceParams) => Promise<LightsparkCreateInvoiceResult>;
|
|
4
|
+
createTestModeInvoice: ({ amountMsats, memo, }: LightsparkCreateTestModeInvoiceParams) => Promise<{
|
|
5
|
+
encodedInvoice: string;
|
|
6
|
+
}>;
|
|
7
|
+
decodeInvoice: (invoice: string) => Promise<LightsparkDecodedInvoice>;
|
|
8
|
+
getBalance: () => Promise<LightsparkBalance>;
|
|
9
|
+
getTransactionStatus: ({ transactionId, paymentHash: rawPaymentHash, attempts, intervalMs, }: LightsparkTransactionStatusParams) => Promise<LightsparkTrackingOutcome>;
|
|
10
|
+
listTransactions: ({ numTransactions, afterDate, }?: LightsparkListTransactionsParams) => Promise<LightsparkTransactionSummary[]>;
|
|
11
|
+
payInvoice: ({ invoice, amountMsats, maximumFeesMsats, destinationPublicKey, timeoutSecs, attempts, intervalMs, expirySkewToleranceMs, }: LightsparkPayInvoiceParams) => Promise<LightsparkPayInvoiceResult>;
|
|
12
|
+
sendPayment: ({ destinationPublicKey, amountMsats, maximumFeesMsats, timeoutSecs, attempts, intervalMs, }: LightsparkSendPaymentParams) => Promise<LightsparkSendPaymentResult>;
|
|
13
|
+
};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
export type LightsparkCurrencyAmount = {
|
|
2
|
+
originalValue: number;
|
|
3
|
+
originalUnit: string;
|
|
4
|
+
};
|
|
5
|
+
export type LightsparkSdkInvoiceData = {
|
|
6
|
+
encodedPaymentRequest: string;
|
|
7
|
+
bitcoinNetwork: string;
|
|
8
|
+
paymentHash: string;
|
|
9
|
+
amount: LightsparkCurrencyAmount;
|
|
10
|
+
createdAt: string;
|
|
11
|
+
expiresAt: string;
|
|
12
|
+
destination: {
|
|
13
|
+
publicKey?: string | null;
|
|
14
|
+
};
|
|
15
|
+
memo?: string | null;
|
|
16
|
+
};
|
|
17
|
+
export type LightsparkSdkInvoice = {
|
|
18
|
+
id: string;
|
|
19
|
+
status: string;
|
|
20
|
+
data: LightsparkSdkInvoiceData;
|
|
21
|
+
amountPaid?: LightsparkCurrencyAmount | null;
|
|
22
|
+
};
|
|
23
|
+
export type LightsparkSdkTransaction = {
|
|
24
|
+
id: string;
|
|
25
|
+
createdAt: string;
|
|
26
|
+
status: string;
|
|
27
|
+
amount: LightsparkCurrencyAmount;
|
|
28
|
+
typename: string;
|
|
29
|
+
resolvedAt?: string | null;
|
|
30
|
+
transactionHash?: string | null;
|
|
31
|
+
fees?: LightsparkCurrencyAmount | null;
|
|
32
|
+
paymentPreimage?: string | null;
|
|
33
|
+
failureReason?: string | null;
|
|
34
|
+
destinationId?: string | null;
|
|
35
|
+
};
|
|
36
|
+
export type LightsparkSdkNode = {
|
|
37
|
+
id: string;
|
|
38
|
+
bitcoinNetwork: string;
|
|
39
|
+
balances?: {
|
|
40
|
+
availableToSendBalance: LightsparkCurrencyAmount;
|
|
41
|
+
};
|
|
42
|
+
localBalance?: LightsparkCurrencyAmount;
|
|
43
|
+
remoteBalance?: LightsparkCurrencyAmount;
|
|
44
|
+
};
|
|
45
|
+
type LightsparkGraphClientMethods = {
|
|
46
|
+
decodeInvoice(encodedInvoice: string): Promise<LightsparkSdkInvoiceData>;
|
|
47
|
+
payInvoice(payerNodeId: string, encodedInvoice: string, maximumFeesMsats: number, timeoutSecs?: number, amountMsats?: number, idempotencyKey?: string): Promise<LightsparkSdkTransaction | undefined>;
|
|
48
|
+
sendPayment(payerNodeId: string, destinationPublicKey: string, timeoutSecs: number | undefined, amountMsats: number, maximumFeesMsats: number): Promise<LightsparkSdkTransaction | undefined>;
|
|
49
|
+
createInvoiceWithDetails(nodeId: string, amountMsats: number, memo: string, type?: undefined, expirySecs?: number): Promise<LightsparkSdkInvoice | undefined>;
|
|
50
|
+
createTestModeInvoice(localNodeId: string, amountMsats: number, memo?: string): Promise<string | null>;
|
|
51
|
+
getRecentTransactions(nodeId: string, numTransactions?: number, bitcoinNetwork?: string, afterDate?: string): Promise<LightsparkSdkTransaction[]>;
|
|
52
|
+
getTransaction(transactionId: string): Promise<LightsparkSdkTransaction | null | undefined>;
|
|
53
|
+
outgoingPaymentsForPaymentHash(paymentHash: string, statuses?: string[]): Promise<LightsparkSdkTransaction[]>;
|
|
54
|
+
invoiceForPaymentHash(paymentHash: string): Promise<LightsparkSdkInvoice | null>;
|
|
55
|
+
getLightningFeeEstimateForInvoice(nodeId: string, encodedPaymentRequest: string, amountMsats?: number): Promise<LightsparkCurrencyAmount>;
|
|
56
|
+
getLightningFeeEstimateForNode(nodeId: string, destinationNodePublicKey: string, amountMsats: number): Promise<LightsparkCurrencyAmount>;
|
|
57
|
+
loadNodeKey(nodeId: string, signingPrivateKeyOrAlias: {
|
|
58
|
+
key: string;
|
|
59
|
+
}): Promise<void>;
|
|
60
|
+
};
|
|
61
|
+
/** Implement getNodeById to avoid the optional vendor SDK; executeRawQuery uses its query builder. */
|
|
62
|
+
export type LightsparkGraphClient = LightsparkGraphClientMethods & ({
|
|
63
|
+
getNodeById(nodeId: string): Promise<LightsparkSdkNode | null>;
|
|
64
|
+
executeRawQuery?(query: unknown): Promise<unknown>;
|
|
65
|
+
} | {
|
|
66
|
+
getNodeById?(nodeId: string): Promise<LightsparkSdkNode | null>;
|
|
67
|
+
executeRawQuery(query: unknown): Promise<unknown>;
|
|
68
|
+
});
|
|
69
|
+
export type LightsparkToolboxParams = {
|
|
70
|
+
nodeId: string;
|
|
71
|
+
signingKey?: string;
|
|
72
|
+
apiUrl?: string;
|
|
73
|
+
} & ({
|
|
74
|
+
clientId: string;
|
|
75
|
+
clientSecret: string;
|
|
76
|
+
client?: LightsparkGraphClient;
|
|
77
|
+
} | {
|
|
78
|
+
clientId?: string;
|
|
79
|
+
clientSecret?: string;
|
|
80
|
+
client: LightsparkGraphClient;
|
|
81
|
+
});
|
|
82
|
+
export type LightsparkPaymentStatus = "PENDING" | "SUCCESS" | "FAILED";
|
|
83
|
+
export type LightsparkTrackingStatus = LightsparkPaymentStatus | "NOT_FOUND" | "UNKNOWN";
|
|
84
|
+
export type LightsparkPaymentOutcome = {
|
|
85
|
+
status: LightsparkPaymentStatus;
|
|
86
|
+
paymentHash?: string;
|
|
87
|
+
transactionId?: string;
|
|
88
|
+
amountMsats?: string;
|
|
89
|
+
feePaidMsats?: string;
|
|
90
|
+
preimage?: string;
|
|
91
|
+
failureReason?: string;
|
|
92
|
+
};
|
|
93
|
+
export type LightsparkPayInvoiceResult = LightsparkPaymentOutcome & {
|
|
94
|
+
paymentHash: string;
|
|
95
|
+
/**
|
|
96
|
+
* PENDING because an amountless payment cannot be matched to this request. Reconcile its actual
|
|
97
|
+
* amount against requestedAmountMsats before resending, even if tracking later reports SUCCESS.
|
|
98
|
+
*/
|
|
99
|
+
reconciliationRequired?: {
|
|
100
|
+
reason: "AMOUNT_MISMATCH" | "AMOUNT_UNVERIFIABLE";
|
|
101
|
+
requestedAmountMsats: string;
|
|
102
|
+
};
|
|
103
|
+
/** The result belongs to an earlier payment; this call sent nothing. */
|
|
104
|
+
replayedPriorPayment?: true;
|
|
105
|
+
};
|
|
106
|
+
export type LightsparkSendPaymentResult = LightsparkPaymentOutcome & {
|
|
107
|
+
amountMsats: string;
|
|
108
|
+
destinationPublicKey: string;
|
|
109
|
+
/**
|
|
110
|
+
* ISO-8601 send time minus LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS. Pass as afterDate to
|
|
111
|
+
* listTransactions and match createdAt, amountMsats and typename before retrying an unknown send.
|
|
112
|
+
* destinationId is an entity id, so it cannot be compared with destinationPublicKey.
|
|
113
|
+
*/
|
|
114
|
+
sentAfter: string;
|
|
115
|
+
};
|
|
116
|
+
export type LightsparkTrackingOutcome = Omit<LightsparkPaymentOutcome, "status"> & {
|
|
117
|
+
status: LightsparkTrackingStatus;
|
|
118
|
+
};
|
|
119
|
+
export type LightsparkPayInvoiceParams = {
|
|
120
|
+
invoice: string;
|
|
121
|
+
amountMsats?: string;
|
|
122
|
+
maximumFeesMsats?: string;
|
|
123
|
+
destinationPublicKey?: string;
|
|
124
|
+
timeoutSecs?: number;
|
|
125
|
+
attempts?: number;
|
|
126
|
+
intervalMs?: number;
|
|
127
|
+
/**
|
|
128
|
+
* Expiry allowance in milliseconds, from 0 to LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MAX_MS.
|
|
129
|
+
* Defaults to LIGHTNING_INVOICE_EXPIRY_SKEW_TOLERANCE_MS.
|
|
130
|
+
*/
|
|
131
|
+
expirySkewToleranceMs?: number;
|
|
132
|
+
};
|
|
133
|
+
export type LightsparkSendPaymentParams = {
|
|
134
|
+
destinationPublicKey: string;
|
|
135
|
+
amountMsats: string;
|
|
136
|
+
maximumFeesMsats?: string;
|
|
137
|
+
timeoutSecs?: number;
|
|
138
|
+
attempts?: number;
|
|
139
|
+
intervalMs?: number;
|
|
140
|
+
};
|
|
141
|
+
export type LightsparkCreateInvoiceParams = {
|
|
142
|
+
amountMsats: string;
|
|
143
|
+
memo?: string;
|
|
144
|
+
expirySecs?: number;
|
|
145
|
+
};
|
|
146
|
+
export type LightsparkCreateInvoiceResult = {
|
|
147
|
+
encodedInvoice: string;
|
|
148
|
+
paymentHash: string;
|
|
149
|
+
amountMsats: string;
|
|
150
|
+
createdAt: string;
|
|
151
|
+
expiresAt: string;
|
|
152
|
+
};
|
|
153
|
+
export type LightsparkCreateTestModeInvoiceParams = {
|
|
154
|
+
amountMsats: string;
|
|
155
|
+
memo?: string;
|
|
156
|
+
};
|
|
157
|
+
export type LightsparkDecodedInvoice = {
|
|
158
|
+
paymentHash: string;
|
|
159
|
+
amountMsats: string;
|
|
160
|
+
network: string;
|
|
161
|
+
createdAt: string;
|
|
162
|
+
expiresAt: string;
|
|
163
|
+
destinationPublicKey?: string;
|
|
164
|
+
memo?: string;
|
|
165
|
+
};
|
|
166
|
+
export type LightsparkBalance = {
|
|
167
|
+
spendableMsats: string;
|
|
168
|
+
inboundCapacityMsats?: string;
|
|
169
|
+
};
|
|
170
|
+
export type LightsparkTransactionStatusParams = {
|
|
171
|
+
transactionId?: string;
|
|
172
|
+
paymentHash?: string;
|
|
173
|
+
attempts?: number;
|
|
174
|
+
intervalMs?: number;
|
|
175
|
+
};
|
|
176
|
+
export type LightsparkListTransactionsParams = {
|
|
177
|
+
numTransactions?: number;
|
|
178
|
+
/** ISO-8601 timestamp; pass `sentAfter` from a `sendPayment` result to bound a reconciliation scan. */
|
|
179
|
+
afterDate?: string;
|
|
180
|
+
};
|
|
181
|
+
/** A listTransactions row. Vendor enum values remain strings to support future SDK versions. */
|
|
182
|
+
export type LightsparkTransactionSummary = {
|
|
183
|
+
id: string;
|
|
184
|
+
/** GraphQL type, e.g. "OutgoingPayment", "IncomingPayment" or "RoutingTransaction". */
|
|
185
|
+
typename: string;
|
|
186
|
+
/** Raw vendor status, including FUTURE_VALUE for an unrecognised status. */
|
|
187
|
+
status: string;
|
|
188
|
+
createdAt: string;
|
|
189
|
+
amountMsats?: string;
|
|
190
|
+
resolvedAt?: string;
|
|
191
|
+
/** BOLT11 payment hash for an OutgoingPayment, matching payInvoice results. */
|
|
192
|
+
transactionHash?: string;
|
|
193
|
+
/** Counterparty entity id (e.g. "GraphNode:0188..."); not a Lightning public key. */
|
|
194
|
+
destinationId?: string;
|
|
195
|
+
};
|
|
196
|
+
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { getStellarToolbox, validateStellarAddress } from "./toolbox";
|
|
2
|
-
export type { StellarCreateTransactionParams, StellarCreateTrustlineTransactionParams, StellarToolboxParams, StellarTransferParams, StellarTrustlineParams, StellarWallet, } from "./types";
|
|
2
|
+
export type { StellarCreateTransactionParams, StellarCreateTrustlineTransactionParams, StellarSigner, StellarToolboxParams, StellarTransaction, StellarTransferParams, StellarTrustlineParams, StellarWallet, } from "./types";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AssetValue } from "@swapkit/helpers";
|
|
2
|
-
import type { StellarCreateTransactionParams, StellarCreateTrustlineTransactionParams, StellarToolboxParams, StellarTransferParams, StellarTrustlineParams } from "./types";
|
|
2
|
+
import type { StellarCreateTransactionParams, StellarCreateTrustlineTransactionParams, StellarToolboxParams, StellarTransaction, StellarTransferParams, StellarTrustlineParams } from "./types";
|
|
3
3
|
export declare function _clearStellarBaseReserveCache(): void;
|
|
4
4
|
export declare function validateStellarAddress(address: string): boolean;
|
|
5
5
|
export declare function getStellarToolbox(params?: StellarToolboxParams): {
|
|
@@ -22,7 +22,7 @@ export declare function getStellarToolbox(params?: StellarToolboxParams): {
|
|
|
22
22
|
}) => Promise<string>;
|
|
23
23
|
signTransaction: (transaction: {
|
|
24
24
|
toXDR: () => string;
|
|
25
|
-
}) => Promise<
|
|
25
|
+
}) => Promise<StellarTransaction>;
|
|
26
26
|
transfer: ({ recipient, assetValue, memo, sweep }: StellarTransferParams) => Promise<string>;
|
|
27
27
|
validateAddress: typeof validateStellarAddress;
|
|
28
28
|
};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { FeeBumpTransaction, Transaction } from "@stellar/stellar-sdk";
|
|
2
|
+
import type { AssetValue, ChainSigner, DerivationPathArray, GenericCreateTransactionParams, GenericTransferParams } from "@swapkit/helpers";
|
|
2
3
|
import type { getStellarToolbox } from "./toolbox";
|
|
3
4
|
export type StellarWallet = ReturnType<typeof getStellarToolbox>;
|
|
4
5
|
export type StellarCreateTransactionParams = Omit<GenericCreateTransactionParams, "feeRate">;
|
|
@@ -10,8 +11,11 @@ export type StellarTrustlineParams = {
|
|
|
10
11
|
export type StellarCreateTrustlineTransactionParams = StellarTrustlineParams & {
|
|
11
12
|
sender?: string;
|
|
12
13
|
};
|
|
14
|
+
export type StellarTransaction = Transaction | FeeBumpTransaction;
|
|
15
|
+
export type StellarSigner = ChainSigner<StellarTransaction, StellarTransaction>;
|
|
13
16
|
export type StellarToolboxParams = {
|
|
14
17
|
phrase?: string;
|
|
15
18
|
derivationPath?: DerivationPathArray;
|
|
16
19
|
index?: number;
|
|
20
|
+
signer?: StellarSigner;
|
|
17
21
|
};
|
package/package.json
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
{
|
|
2
|
-
"dependencies": { "@swapkit/helpers": "6.
|
|
2
|
+
"dependencies": { "@swapkit/helpers": "6.2.0", "@swapkit/utxo-signer": "3.1.1" },
|
|
3
3
|
"description": "SwapKit - Toolboxes",
|
|
4
4
|
"devDependencies": {
|
|
5
5
|
"@aptos-labs/ts-sdk": "7.0.1",
|
|
6
|
+
"@lightsparkdev/lightspark-sdk": "1.9.19",
|
|
6
7
|
"@mysten/sui": "2.17.0",
|
|
7
8
|
"@near-js/accounts": "2.5.1",
|
|
8
9
|
"@near-js/crypto": "2.5.1",
|
|
@@ -60,6 +61,7 @@
|
|
|
60
61
|
"./cosmos": { "default": "./dist/src/cosmos/index.js", "types": "./dist/types/cosmos/index.d.ts" },
|
|
61
62
|
"./evm": { "default": "./dist/src/evm/index.js", "types": "./dist/types/evm/index.d.ts" },
|
|
62
63
|
"./hypercore": { "default": "./dist/src/hypercore/index.js", "types": "./dist/types/hypercore/index.d.ts" },
|
|
64
|
+
"./lightspark": { "default": "./dist/src/lightspark/index.js", "types": "./dist/types/lightspark/index.d.ts" },
|
|
63
65
|
"./near": { "default": "./dist/src/near/index.js", "types": "./dist/types/near/index.d.ts" },
|
|
64
66
|
"./radix": { "default": "./dist/src/radix/index.js", "types": "./dist/types/radix/index.d.ts" },
|
|
65
67
|
"./ripple": { "default": "./dist/src/ripple/index.js", "types": "./dist/types/ripple/index.d.ts" },
|
|
@@ -78,6 +80,7 @@
|
|
|
78
80
|
"name": "@swapkit/toolboxes",
|
|
79
81
|
"peerDependencies": {
|
|
80
82
|
"@aptos-labs/ts-sdk": "7.0.1",
|
|
83
|
+
"@lightsparkdev/lightspark-sdk": "1.9.19",
|
|
81
84
|
"@mysten/sui": "2.17.0",
|
|
82
85
|
"@near-js/accounts": "2.5.1",
|
|
83
86
|
"@near-js/crypto": "2.5.1",
|
|
@@ -121,6 +124,7 @@
|
|
|
121
124
|
"ts-pattern": "5.9.0",
|
|
122
125
|
"xrpl": "4.6.0"
|
|
123
126
|
},
|
|
127
|
+
"peerDependenciesMeta": { "@lightsparkdev/lightspark-sdk": { "optional": true } },
|
|
124
128
|
"publishConfig": { "access": "public" },
|
|
125
129
|
"repository": { "type": "git", "url": "git+https://github.com/swapkit/SwapKit.git" },
|
|
126
130
|
"scripts": {
|
|
@@ -131,5 +135,5 @@
|
|
|
131
135
|
"type-check:go": "tsgo"
|
|
132
136
|
},
|
|
133
137
|
"type": "module",
|
|
134
|
-
"version": "6.
|
|
138
|
+
"version": "6.4.0"
|
|
135
139
|
}
|