@swapkit/toolboxes 6.4.0 → 6.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/dist/chunk-2q4pxsyg.js +2 -0
- package/dist/chunk-bmj5dnhd.js +1 -0
- package/dist/{chunk-exyqap7m.js → chunk-pz8xe0qj.js} +1 -1
- package/dist/{chunk-xdkdc1f0.js → chunk-qk8kg62t.js} +1 -1
- package/dist/src/aleo/index.js +1 -1
- package/dist/src/aptos/index.js +1 -1
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- package/dist/src/evm/index.js +1 -1
- package/dist/src/hypercore/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/lightspark/index.js +1 -1
- package/dist/src/near/index.js +1 -1
- package/dist/src/radix/index.js +1 -1
- package/dist/src/ripple/index.js +1 -1
- package/dist/src/solana/index.js +1 -1
- package/dist/src/starknet/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/substrate/index.js +1 -1
- package/dist/src/sui/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/src/tron/index.js +1 -1
- package/dist/src/utxo/index.js +2 -1
- package/dist/types/evm/helpers.d.ts +4 -0
- package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -1
- package/dist/types/evm/toolbox/evm.d.ts +24 -24
- package/dist/types/evm/toolbox/op.d.ts +2 -2
- package/dist/types/evm/types.d.ts +2 -2
- package/dist/types/hypercore/payin.d.ts +0 -1
- package/dist/types/sui/__tests__/grpcClientMock.d.ts +37 -0
- package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +1 -0
- package/dist/types/utxo/helpers/index.d.ts +1 -0
- package/dist/types/utxo/helpers/messageSigning.d.ts +7 -0
- package/dist/types/utxo/toolbox/bitcoinCash.d.ts +1 -0
- package/dist/types/utxo/toolbox/utxo.d.ts +1 -0
- package/dist/types/utxo/toolbox/zcash.d.ts +1 -0
- package/package.json +2 -4
- package/dist/chunk-ncc6qmj6.js +0 -1
- package/dist/chunk-ygq25ce3.js +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The keystore can now sign Bitcoin messages (BIP-137) and declares the `btcMessage` capability for Bitcoin, so flows that need a Bitcoin signed message, like cancelling a Harbor Bitcoin limit order, work with it.
|
|
8
|
+
- [#467](https://github.com/swapkit/sdk/pull/467) [`6ddbd12`](https://github.com/swapkit/sdk/commit/6ddbd12b87af88d304aa575518970214ca4516e9) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `getTokenAddress` and `getChecksumAddressFromAsset` now use `isGasAsset`, so `MONAD.MON`, `XLAYER.OKB` and `GNO.xDAI` resolve to the native asset address instead of returning `null` or throwing. Identifiers that repeat the chain name on a chain whose gas asset has another ticker, such as `ARB.ARB` or `BSC.BSC`, no longer resolve to the native asset address. `ContractAddress[Chain.Optimism]` is now the zero address, like every EVM chain except Polygon, so `OP.ETH` resolves to the zero address instead of the OP token contract (`0x4200000000000000000000000000000000000042`). `OP.OP` without an address still resolves to the OP token contract. The Botanix toolbox now targets the Botanix network instead of Sonic.
|
|
9
|
+
- [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM transactions that carry only a legacy `gasPrice` are now sent as legacy transactions instead of failing on chains that support EIP-1559.
|
|
10
|
+
- [#468](https://github.com/swapkit/sdk/pull/468) [`8062907`](https://github.com/swapkit/sdk/commit/8062907e7f2dd5a7c12f436b9ee3a2b5fad66e15) Thanks [@ice-chillios](https://github.com/ice-chillios)! - The TON toolbox no longer falls back to Orbs TON Access when every configured TON RPC fails. That service no longer returns any nodes, so the fallback itself failed with an unclear error. Now the toolbox throws `helpers_chain_rpc_connection_failed`, and jetton transfers and sweeps report that error instead of `core_swap_contract_not_found`. Set a working endpoint with `SKConfig.setRpcUrl(Chain.Ton, [...])` or pass `provider` to the toolbox. The `@orbs-network/ton-access` dependency is removed.
|
|
11
|
+
- [#474](https://github.com/swapkit/sdk/pull/474) [`f107064`](https://github.com/swapkit/sdk/commit/f10706478e42440912a009b011b92b4e345104f8) Thanks [@ice-chillios](https://github.com/ice-chillios)! - The TON toolbox spaces out and retries its requests to the public Toncenter endpoint, which allows about one request per second without an API key, so TON jetton sales such as TON.USDT are much less likely to fail there. Requests to the chain's default endpoints start at least 1.1 seconds apart, through a queue shared by every toolbox in the process. Waits therefore grow with concurrent TON activity; for servers and other high-volume use, configure a custom TON RPC or a Toncenter API key, which is not spaced out. The endpoint health check is not queued. A request rejected with 429 or a gateway error (502 and above) is sent again after 1, 2 and 4 seconds. A node's 500 answer, such as a rejected message, a timeout and a network failure fail at once. A jetton lookup that the RPC does not answer is reported as `helpers_chain_rpc_connection_failed` instead of `core_swap_contract_not_found`. A toolbox looks up each jetton wallet address only once per jetton and owner.
|
|
12
|
+
- [#465](https://github.com/swapkit/sdk/pull/465) [`d03591d`](https://github.com/swapkit/sdk/commit/d03591dd257fb2735d1ce1eb72540e11082a084e) Thanks [@towanTG](https://github.com/towanTG)! - Zcash transactions keep working through the NU7 network upgrade (mainnet block 3,543,405, around 5 November 2026), which rejects version 4 transactions. From the activation block on, the Zcash toolbox builds version 5 transactions with the NU7 consensus branch id `0x77190ad9`; before it, nothing changes. If the block height can't be fetched, building a Zcash transaction now fails with `toolbox_utxo_api_error` instead of guessing the format, because a guess on the wrong side of an upgrade produces a transaction the network rejects. `@swapkit/utxo-signer` can now build, sign, parse and compute the txid of transparent version 5 transactions, including version 5 PSBTs and PCZTs, and exports `getZcashTransactionFormat` and `ZCASH_NU7_ACTIVATION_HEIGHT`. Parsing a raw Zcash transaction now keeps input txids in the right byte order, so re-serializing it no longer changes them.
|
|
13
|
+
- [#460](https://github.com/swapkit/sdk/pull/460) [`9190931`](https://github.com/swapkit/sdk/commit/9190931bb2c1f911543a22cb8ccc91e3913cfe6c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `SwapKitApi` now covers the full limit-order API: `getLimitOrderTokens`, `getLimitOrderQuote`, `buildLimitOrder`, `submitLimitOrder`, `getLimitOrders`, `getLimitOrder`, `buildLimitOrderCancel` and `submitLimitOrderCancel`, with typed responses and `LimitOrderStatus` and `LimitOrderTxType` constants. `getLimitOrderQuote` accepts an optional `providers` list to restrict the quote to those providers. Each call can be overridden through `SKConfig.endpoints`. (via @swapkit/helpers@6.4.0)
|
|
14
|
+
- [#464](https://github.com/swapkit/sdk/pull/464) [`c20cc10`](https://github.com/swapkit/sdk/commit/c20cc10b4534c7948dfe4b57f29e07f1b183f1ca) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.4.0)
|
|
15
|
+
|
|
16
|
+
## 6.4.1
|
|
17
|
+
|
|
18
|
+
### Patch Changes
|
|
19
|
+
|
|
20
|
+
- [#457](https://github.com/swapkit/sdk/pull/457) [`59568bc`](https://github.com/swapkit/sdk/commit/59568bcafbe907e7efa3a6ee0eb55a8c2500bac4) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM `signTypedData` now accepts standard EIP-712 payloads that include `EIP712Domain` in `types`, as wallets and backends produce them for `eth_signTypedData_v4`. Such payloads previously threw; callers no longer need to strip `EIP712Domain` before signing. If the declared `EIP712Domain` does not exactly match the fields of `domain` (names, types and canonical order), signing rejects with `toolbox_evm_typed_data_domain_mismatch` instead of signing a different domain. Payloads without it sign exactly as before.
|
|
21
|
+
- [#452](https://github.com/swapkit/sdk/pull/452) [`8f3ecb0`](https://github.com/swapkit/sdk/commit/8f3ecb0522e2433f38012277446fd56ba1a223c5) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - The Sui toolbox now talks to Sui over gRPC instead of JSON-RPC, which Sui's public fullnodes stopped serving. Balances, transfers, sweeps, fee estimates and swaps from Sui work again with the default RPC. A custom Sui RPC set in `rpcUrls` must now serve gRPC.
|
|
22
|
+
- [#459](https://github.com/swapkit/sdk/pull/459) [`29bda2c`](https://github.com/swapkit/sdk/commit/29bda2c7a7f69112fc9403c042cb4aee7c2010a5) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Wallets now declare all their signing capabilities per chain in one `signingSupport` map on `createWallet`: `direct` (signs the transaction the API builds for a route), `typedData` (EIP-712) and `btcMessage` (BIP-137), with the names exported as `SigningCapability`. Undeclared capabilities count as unsupported, and each connected chain wallet carries its capabilities as `signing`. Use `walletSupportsDirectSigning(wallet)` to check for direct signing; it understands wallets from both old and new connectors. (via @swapkit/helpers@6.3.0)
|
|
23
|
+
- [#462](https://github.com/swapkit/sdk/pull/462) [`adf132c`](https://github.com/swapkit/sdk/commit/adf132ce1b856153be10f132372cb4fd6cabe7d6) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - EVM wallets wrapped by `prepareNetworkSwitch` now switch to the chain's network before `signTypedData`, as they already do before sending a transaction. A refused or impossible switch fails with `helpers_failed_to_switch_network` before anything is signed. Message signing (`signMessage`) is unchanged. (via @swapkit/helpers@6.3.0)
|
|
24
|
+
- [#453](https://github.com/swapkit/sdk/pull/453) [`e8988db`](https://github.com/swapkit/sdk/commit/e8988dbd06040f6b134163e7d9cba1910b9ee711) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.3.0)
|
|
25
|
+
|
|
3
26
|
## 6.4.0
|
|
4
27
|
|
|
5
28
|
### Minor Changes
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ja as Ve}from"./chunk-qk8kg62t.js";import{ka as de}from"./chunk-pz8xe0qj.js";import{Chain as x}from"@swapkit/helpers";import{match as In}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as At,SKConfig as Mt,SwapKitError as U}from"@swapkit/helpers";import{FallbackProvider as Gt,getAddress as Ee,Interface as Ot,JsonRpcProvider as se,Network as Bt}from"ethers";import{match as _e}from"ts-pattern";function It(e){return new se(e)}async function Nn(e,t){return It(t||await At(e))}function Ce(e){let t=Mt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new U("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Bt.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Gt(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function O(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Fe(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Vt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Vt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return _e(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Me(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var ve=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Rt=(e)=>{try{return typeof e==="string"&&!!Ee(e)}catch{return!1}};function St(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};_e(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Rt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!ve(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!ve(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ge(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function Oe(e){if(!("EIP712Domain"in e.types))return e;let{EIP712Domain:t,...n}=e.types,o=Ge(e.domain);if(!(Array.isArray(t)&&t.length===o.length&&o.every(({name:r,type:i},s)=>t[s]?.name===r&&t[s]?.type===i)))throw new U({errorKey:"toolbox_evm_typed_data_domain_mismatch",info:{declared:t,expected:o}});return{...e,types:n}}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Ln({chain:e,abi:t,data:n,to:o}){let r=new Ot(t).parseTransaction({data:n});if(!r)throw new U({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,b]of r.fragment.inputs.entries())c[b.name]=le(r.args[p],b);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:Ee(o)},d=Ge(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:d,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(St(o,n),t!==void 0&&o.chainId!==t)throw new U({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as Fn,FeeOption as An,resolveDerivationPath as Mn}from"@swapkit/helpers";import{HDNodeWallet as Gn}from"ethers";import{match as On,P as ot}from"ts-pattern";var Ie=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as kt,applyFeeMultiplierToBigInt as M,Chain as j,EVMChains as Nt,FeeOption as y,isGasAsset as ke,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as K}from"@swapkit/helpers/contracts";import{BrowserProvider as Lt,Contract as Ne,getAddress as ee,getBytes as Dt,Interface as Le,isError as D,resolveAddress as zt,Transaction as pe}from"ethers";import{match as De}from"ts-pattern";function Y(e){return{getBalance:Ve(e)}}function Kn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=j.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=$e({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:tn({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:qe({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:yn({chain:e,provider:t,signer:n}),createContract:Kt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:je({provider:t,signer:n}),estimateGasLimit:on({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:dn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Fe(e),isApproved:en({chain:e,provider:t}),sendTransaction:Xe({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:an({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?async(c)=>{let{domain:l,types:u,value:d}=Oe(c);return await n.signTypedData(l,u,d)}:void 0,transfer:nn({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Ut}}function Ut(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Lt}function ge(e,t,n){return new Ne(e,Le.from(t),n)}function Kt({provider:e}){return function(n,o){return new Ne(n,Le.from(o),e)}}var Ht=["payable","nonpayable"];function qt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function Yn(e){return ee(e)}var jt=30000,Re=new WeakMap,Se=()=>{};function Wt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>jt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function ze({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Re.get(n)??new Map;Re.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=Wt(a,r,i),l=!1,u=(d)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),d)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(D(e,"NONCE_EXPIRED")||D(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function ye(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function Ue(e){return D(e,"NETWORK_ERROR")||D(e,"SERVER_ERROR")||D(e,"TIMEOUT")}function Xt(e){return Ue(e)||D(e,"UNSUPPORTED_OPERATION")}function Ke(e){return Ue(e)||ye(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function $t({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,d={...u,...t&&i!==void 0&&{gas:O(BigInt(i))},...t&&s!==void 0&&{gasPrice:O(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:O(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:O(BigInt(l))},value:O(BigInt(o||0))};return e.send("eth_sendTransaction",[d])}}function Qn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Jt=Nt.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Yt={...Jt,[j.Polygon]:"0x0000000000000000000000000000000000001010"},Qt="0x4200000000000000000000000000000000000042";function xe({chain:e,symbol:t,ticker:n},o){try{if(ke({chain:e,symbol:t}))return Yt[o];if(e===j.Optimism&&t==="OP")return Qt;return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:O(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return De(e).with(j.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:M(a,y.Average),maxPriorityFeePerGas:M(r,y.Average)},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(j.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[y.Average]:{gasPrice:r},[y.Fast]:{gasPrice:M(r,y.Fast)},[y.Fastest]:{gasPrice:M(r,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[y.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[y.Fast]:{maxFeePerGas:M(a,y.Fast),maxPriorityFeePerGas:M(r,y.Fast)},[y.Fastest]:{maxFeePerGas:M(a,y.Fastest),maxPriorityFeePerGas:M(r,y.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[y.Average]:{gasPrice:i},[y.Fast]:{gasPrice:M(i,y.Fast)},[y.Fastest]:{gasPrice:M(i,y.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Zt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let d=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:b,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await zt(u,n),{nonce:G,release:R,settle:k}=await ze({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await d[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:b,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ke(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:d=y.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let b=qt({abi:s,funcName:c});if(b&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(b){if(!n)throw new m("toolbox_evm_no_signer");return Zt({chain:o,contract:f,contractProvider:p,feeOption:d,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function qe({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:K,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function en({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await qe({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function tn({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=y.Fast,amount:c,gasLimitFallback:l,from:u,nonce:d}){let p=[i,BigInt(c||be)],b=await e?.getAddress()||u,f={abi:K,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:b}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:b,gasLimit:l?BigInt(l.toString()):void 0,nonce:d}})}}function nn({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=y.Fast,sender:d,sweep:p,...b}){let f=d||await o?.getAddress(),P=Xe({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await $e({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...b});return P({...A,feeOptionKey:u,sweep:p})}}function je({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function on({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let d=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return je({provider:e,signer:t})({abi:K,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:b,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?b(f(r)):void 0,from:s,to:a,value:d})}}function an({signer:e}){if(!e)return;return(t)=>Me(e,t)}var We=(e)=>e.type===4||(e.authorizations?.length??0)>0,rn=(e)=>!We(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),sn=(e,t=!0)=>{if(We(e))return"eip7702";if(rn(e))return"eip1559";if(e.gasPrice!=null)return"legacy";return t?"eip1559":"legacy"};function cn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:O(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:O(t.maxFeePerGas),maxPriorityFeePerGas:O(t.maxPriorityFeePerGas)}}function Xe({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=y.Fast,sweep:s,...c}){let{from:l,to:u,data:d,value:p,...b}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...b,data:d||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await ze({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=sn(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=De(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),I={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),V=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:cn(E,(await F())[i]),h;try{h=O(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(I)*11n/10n)}catch(B){throw new m("toolbox_evm_error_estimating_gas_limit",{error:B})}return{...I,gasLimit:h,...V}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let I=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:I};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(ye(w)){let h=await $t({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!Xt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let N=D(w,"UNSUPPORTED_OPERATION"),V;try{V=await o.signTransaction({...E,from:P})}catch(h){if(N)R();let B={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}try{return(await C.broadcastTransaction(V)).hash}catch(h){let B={...F,fallbackError:h};if(ye(h)){let z=pe.from(V).hash;if(z)return z}if(fe(h)){let z=pe.from(V).hash;if(z&&await He(C,z))return z;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:B},B)}if(N&&!Ke(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:B},B)}}}finally{k()}}}function L(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function un(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function ln(e){return Dt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function mn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)L(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function pn({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),d=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:b}=un((await d())[a],i),f={...l,...p,data:t,from:r,to:c},P=ln(t)*b;if(u-P<=0n)L(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(B){if(me(B))L(u,P);throw B}}let G=C*b;if(u-G<=0n)L(u,G);let _=C*11n/10n*b,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;L(u,_)}let I=w*b,F=u-I;if(F<=0n)L(u,I);let N=await mn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:I,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),V=F-N;if(V<=0n)L(u,I+N);return{...f,gasLimit:w,value:O(V)}}async function fn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:K,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function $e({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:d,feeOptionKey:p=y.Fast,gasLimit:b,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(ke(s)){let{hexlify:N,toUtf8Bytes:V}=await import("ethers"),h=d||N(V(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...b!==void 0&&{gasLimit:b},to:u,...A!==void 0&&{type:A},value:O(_)};return pn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let I=W({chain:e,provider:a}),F=P?await fn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return I({abi:K,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:b,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function yn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),d=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:K,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(d)],txOverrides:{from:l,nonce:c}})}}function dn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=y.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=kt.from({chain:n}),{gasPrice:u,maxFeePerGas:d,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(d&&p){let b=(d+p)*c;return l.set(Q.fromBigInt(b,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as H,Chain as Qe,derivationPathToString as bn,FeeOption as S,getChainConfig as gn,resolveDerivationPath as xn,SwapKitError as q}from"@swapkit/helpers";import{Contract as Pn,HDNodeWallet as Tn}from"ethers";import{match as wn,P as Ye}from"ts-pattern";var Je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var hn="0x420000000000000000000000000000000000000f";function re(e){return new Pn(hn,Je,e)}function Ze(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function et(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await et(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function vn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function tt(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function En(e){return async function(n){let o=await we(e)(n)??0n,a=await tt(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function _n(e){return async function(n){let o=re(e),a=await et(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=H(t,e),a=H(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function Cn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ze(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[S.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:S.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fast]:{gasPrice:H(i,S.Fast),l1GasPrice:H(r||0n,S.Fast),...Te({feeOption:S.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[S.Fastest]:{gasPrice:H(i,S.Fastest),l1GasPrice:H(r||0n,S.Fastest),...Te({feeOption:S.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=wn(o).with({phrase:Ye.string},({phrase:p,derivationPath:b,index:f=0})=>Tn.fromPhrase(p,void 0,bn(xn({chain:e,derivationPath:b,index:f}))).connect(n)).with({signer:Ye.any},({signer:p})=>p).otherwise(()=>{return}),r=Ze(n),i=BigInt(gn(e).chainId),s=we(n,i),c=vn(n,i),l=he(n),u=e===Qe.Optimism?Cn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:_n(n),estimateL1GasCost:s,estimateL2GasCost:tt(n),estimateOperatorFee:l,estimateTotalGasCost:En(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var nt=ie(Qe.Optimism);function at(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=An.Fast){let s=await t.createContractTxObject({abi:Ie,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var rt=v(T.Adi),it=v(T.Arbitrum),st=v(T.Arc),ct=v(T.Aurora),ut=v(T.Avalanche),lt=ie(T.Base),mt=v(T.Berachain),pt=v(T.BinanceSmartChain),ft=v(T.Botanix),yt=v(T.Core),dt=v(T.Corn),bt=v(T.Cronos),gt=v(T.Gnosis),xt=v(T.Robinhood),Pt=v(T.Hyperevm),Tt=v(T.Linea),wt=v(T.Polygon),ht=v(T.MegaETH),vt=v(T.Monad),Et=v(T.Plasma),_t=v(T.Sonic),Ct=ie(T.Unichain),Ft=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=On(o).with({phrase:ot.string},({phrase:s,derivationPath:c,index:l=0})=>Gn.fromPhrase(s,void 0,Fn(Mn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:ot.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Vn(e,t){return In(e).with(x.Adi,()=>rt(t)).with(x.Arbitrum,()=>it(t)).with(x.Arc,()=>st(t)).with(x.Aurora,()=>ct(t)).with(x.Avalanche,()=>ut(t)).with(x.Base,()=>lt(t)).with(x.Berachain,()=>mt(t)).with(x.BinanceSmartChain,()=>pt(t)).with(x.Botanix,()=>ft(t)).with(x.Core,()=>yt(t)).with(x.Corn,()=>dt(t)).with(x.Cronos,()=>bt(t)).with(x.Ethereum,()=>at(t)).with(x.Gnosis,()=>gt(t)).with(x.Hyperevm,()=>Pt(t)).with(x.Linea,()=>Tt(t)).with(x.MegaETH,()=>ht(t)).with(x.Monad,()=>vt(t)).with(x.Optimism,()=>nt(t)).with(x.Plasma,()=>Et(t)).with(x.Polygon,()=>wt(t)).with(x.Robinhood,()=>xt(t)).with(x.Sonic,()=>_t(t)).with(x.Unichain,()=>Ct(t)).with(x.XLayer,()=>Ft(t)).exhaustive()}async function To(e,t){let n={...t,provider:t?.provider||Ce(e)};return Vn(e,n)}
|
|
2
|
+
export{Y as b,Kn as c,It as d,Nn as e,Ce as f,O as g,Fe as h,Ae as i,Me as j,St as k,Ge as l,Oe as m,Ln as n,Be as o,be as p,te as q,Ut as r,ne as s,ge as t,Kt as u,qt as v,Yn as w,oe as x,Qn as y,Yt as z,xe as A,W as B,X as C,We as D,rn as E,sn as F,Pe as G,Te as H,ie as I,nt as J,at as K,rt as L,it as M,st as N,ct as O,ut as P,lt as Q,mt as R,pt as S,ft as T,yt as U,dt as V,bt as W,gt as X,xt as Y,Pt as Z,Tt as _,wt as $,ht as aa,vt as ba,Et as ca,_t as da,Ct as ea,Ft as fa,Vn as ga,To as ha};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as M,A as l,B as m,C as n,D as o,E as p,F as q,G as r,H as s,I as t,J as u,K as v,L as w,M as x,N as y,O as z,P as A,Q as B,R as C,S as D,T as E,U as F,V as G,W as H,X as I,Y as J,Z as K,_ as L,aa as N,ba as O,ca as P,da as Q,ea as R,fa as S,ga as T,ha as U,p as a,q as b,r as c,s as d,t as e,u as f,v as g,w as h,x as i,y as j,z as k}from"./chunk-2q4pxsyg.js";import"./chunk-qk8kg62t.js";import"./chunk-pz8xe0qj.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var d=((a)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
|
|
2
|
-
export{d as
|
|
2
|
+
export{d as ka};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{AssetValue as o,getChainConfig as l}from"@swapkit/helpers";import{SwapKitApi as m}from"@swapkit/helpers/api";var d=typeof process<"u"&&process.pid?process.pid.toString(36):"",i=0;function C(){function t(){let e=Date.now(),n=i||e;return i=n,e>i?e:n+1}return d+t().toString(36)}function h(t){return async function(n,r=!0){let c=await m.getChainBalance({address:n,chain:t,scamFilter:r}),{baseDecimal:p}=l(t),s=c.map(({identifier:a,value:u,decimal:f})=>new o({decimal:f||p,identifier:a,value:u}));if(!s.some((a)=>a.isGasAsset))return[o.from({chain:t}),...s];return s}}
|
|
2
|
-
export{C as
|
|
2
|
+
export{C as ia,h as ja};
|
package/dist/src/aleo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as it}from"../../chunk-xdkdc1f0.js";import{ja as x}from"../../chunk-exyqap7m.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
|
|
1
|
+
import{ja as it}from"../../chunk-qk8kg62t.js";import{ka as x}from"../../chunk-pz8xe0qj.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
|
package/dist/src/aptos/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ka as B}from"../../chunk-pz8xe0qj.js";import{AssetValue as b,Chain as A,derivationPathToString as tt,getChainConfig as v,getRPCUrlSync as W,NetworkDerivationPath as nt,SwapKitError as s}from"@swapkit/helpers";import{match as j,P as R}from"ts-pattern";var w={COIN_TYPE:"0x1::aptos_coin::AptosCoin",FUNGIBLE_ASSET_METADATA:"0x1::fungible_asset::Metadata",FUNGIBLE_STORE_TRANSFER:"0x1::primary_fungible_store::transfer",TRANSFER:"0x1::aptos_account::transfer"},st=2000,at=/^[0-9a-fA-F]+$/;function x(e){if(!e||typeof e!=="string"||!e.startsWith("0x"))return!1;let i=e.slice(2);if(i.length===0||i.length>64)return!1;return at.test(i)}function Y(e,i,d){if(e<=0n)throw new s({errorKey:"toolbox_sweep_amount_too_low",info:{amount:e.toString(),asset:i.toString(),...d}});return e}async function ot({aptos:e,assetValue:i,senderAddress:d}){let c=i.address;if(!c)throw new s("toolbox_aptos_missing_asset_type");let[y]=await e.getCurrentFungibleAssetBalances({options:{limit:1,where:{asset_type:{_eq:c},is_primary:{_eq:!0},owner_address:{_eq:d}}}});return Y(BigInt(y?.amount??0),i)}function et({derivationPath:e,provider:i,...d}={}){let c,y=tt(e||nt[A.Aptos],{allHardened:!0});async function T(){if(c)return c;return c=await j(d).with({phrase:R.string},async({phrase:n})=>{let{Ed25519Account:t}=await import("@aptos-labs/ts-sdk");return t.fromDerivationPath({mnemonic:n,path:y})}).with({signer:R.any},({signer:n})=>n).otherwise(()=>{return}),c}async function _(){let{Aptos:n,AptosConfig:t,Network:a}=await import("@aptos-labs/ts-sdk"),r=new t({clientConfig:{http2:!1},fullnode:i||W(A.Aptos),network:a.MAINNET});return new n(r)}async function S(){return(await T())?.accountAddress.toString()||""}async function G(n){let t=n||await S();if(!t)throw new s("toolbox_aptos_address_required");let{baseDecimal:a,chain:r}=v(A.Aptos);try{let u=await _(),p=await u.getAccountAPTAmount({accountAddress:t}),g=[b.from({chain:r,fromBaseDecimal:a,value:p.toString()})],f=await u.getCurrentFungibleAssetBalances({options:{where:{owner_address:{_eq:t}}}});for(let o of f){if(o.asset_type===w.COIN_TYPE||Number(o.amount)<=0)continue;let m=o.asset_type;if(m){let l=("metadata"in o&&typeof o.metadata==="object"&&o.metadata!==null?o.metadata:void 0)?.decimals??a;g.push(b.from({asset:`${A.Aptos}.APT-${m}`,fromBaseDecimal:l,value:String(o.amount)}))}}return g}catch{return[b.from({chain:r})]}}async function H(n){if(!n){let{baseDecimal:g}=v(A.Aptos),f=i||W(A.Aptos),o=await fetch(`${f}/estimate_gas_price`),{gas_estimate:m}=await o.json();return b.from({chain:A.Aptos,fromBaseDecimal:g,value:String(m)})}let t=await N(n),a=await _(),[r]=await a.transaction.simulate.simple({transaction:t});if(!r)throw new s("toolbox_aptos_transaction_creation_error");let u=BigInt(r.gas_used)*BigInt(r.gas_unit_price),{baseDecimal:p}=v(A.Aptos);return b.from({chain:A.Aptos,fromBaseDecimal:p,value:u.toString()})}async function N({recipient:n,assetValue:t,maxGasAmount:a,sender:r,accountSequenceNumber:u,gasUnitPrice:p,sweep:g}){if(!x(n))throw new s("core_transaction_invalid_recipient_address");let f=r||await S();if(!f)throw new s("toolbox_aptos_no_sender");let{AccountAddress:o}=await import("@aptos-labs/ts-sdk"),m=await _(),C=o.from(f);try{let l=t.isGasAsset?w.TRANSFER:w.FUNGIBLE_STORE_TRANSFER,z=t.address,E=(P,O)=>{let k=j({address:z,isGasAsset:t.isGasAsset}).with({isGasAsset:!0},()=>[o.from(n),P]).with({address:R.string},({address:V})=>[o.from(V),o.from(n),P]).otherwise(()=>null);if(!k)throw new s("toolbox_aptos_missing_asset_type");let q=O?.maxGasAmount??a,K=O?.gasUnitPrice??p;return m.transaction.build.simple({data:{function:l,functionArguments:k,typeArguments:t.isGasAsset?[]:[w.FUNGIBLE_ASSET_METADATA]},options:q!==void 0||K!==void 0||u!==void 0?{accountSequenceNumber:u,gasUnitPrice:K,maxGasAmount:q}:void 0,sender:C})};if(!g)return E(t.getBaseValue("bigint"));if(!t.isGasAsset){let P=await ot({aptos:m,assetValue:t,senderAddress:f});return E(P)}let U=BigInt(await m.getAccountAPTAmount({accountAddress:f})),J=await E(1n,{maxGasAmount:a??st}),[h]=await m.transaction.simulate.simple({options:{estimateMaxGasAmount:a===void 0},transaction:J});if(!h)throw new s("toolbox_aptos_transaction_creation_error");if(!h.success)throw new s({errorKey:"toolbox_aptos_transaction_creation_error",info:{vmStatus:h.vm_status}});let D=BigInt(h.gas_used),M=D>0n?(D*6n+4n)/5n:1n,L=M*BigInt(h.gas_unit_price),Z=Y(U-L,t,{balance:U.toString(),fee:L.toString()});return E(Z,{gasUnitPrice:Number(h.gas_unit_price),maxGasAmount:Number(M)})}catch(l){if(l instanceof s)throw l;throw new s("toolbox_aptos_transaction_creation_error",l)}}async function F(n){let t=await T();if(!t)throw new s("toolbox_aptos_no_signer");return(await _()).transaction.sign({signer:t,transaction:n})}async function Q({assetValue:n,maxGasAmount:t,recipient:a,sweep:r}){let u=await T();if(!u)throw new s("toolbox_aptos_no_signer");if(!x(a))throw new s("core_transaction_invalid_recipient_address");try{let p=u.accountAddress.toString(),g=await N({assetValue:n,maxGasAmount:t,recipient:a,sender:p,sweep:r});return(await(await _()).signAndSubmitTransaction({signer:u,transaction:g})).hash}catch(p){if(p instanceof s)throw p;throw new s("toolbox_aptos_transaction_creation_error",p)}}async function I({senderAuthenticator:n,transaction:t}){try{return(await(await _()).transaction.submit.simple({senderAuthenticator:n,transaction:t})).hash}catch(a){throw new s("toolbox_aptos_broadcast_error",a)}}async function X(n){let t=await F(n);return I({senderAuthenticator:t,transaction:n})}return{broadcastTransaction:I,createTransaction:N,estimateTransactionFee:H,getAddress:S,getBalance:G,signAndBroadcastTransaction:X,signTransaction:F,transfer:Q,validateAddress:x}}function rt({provider:e}){return async function({assetValue:d,recipient:c,sweep:y}){if(y)throw new s({errorKey:"toolbox_not_supported",info:{chain:A.Aptos,feature:"extension_provider_sweep",reason:"Aptos extension providers cannot query balances or simulate transactions"}});if(!x(c))throw new s("core_transaction_invalid_recipient_address");let{AccountAddress:T}=await import("@aptos-labs/ts-sdk");if(d.isGasAsset)return(await e.signAndSubmitTransaction({arguments:[T.from(c).toString(),d.getBaseValue("string")],function:w.TRANSFER,type:"entry_function_payload",type_arguments:[]})).hash;let _=d.address;if(!_)throw new s("toolbox_aptos_missing_asset_type");return(await e.signAndSubmitTransaction({arguments:[_,T.from(c).toString(),d.getBaseValue("string")],function:w.FUNGIBLE_STORE_TRANSFER,type:"entry_function_payload",type_arguments:[w.FUNGIBLE_ASSET_METADATA]})).hash}}export{rt as createAptosExtensionTransfer,et as getAptosToolbox,x as validateAptosAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ka as C}from"../../chunk-pz8xe0qj.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};
|