@swapkit/toolboxes 5.2.1 → 5.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 +23 -0
- package/dist/{chunk-xbdjxeqd.js → chunk-4428244x.js} +1 -1
- package/dist/{chunk-nvfkjbyq.js → chunk-as9fracn.js} +2 -2
- package/dist/chunk-dssawneq.js +1 -0
- package/dist/chunk-qsbf0z90.js +1 -0
- package/dist/chunk-rn33j2bm.js +2 -0
- 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/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 +1 -1
- package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +2 -2
- package/dist/types/evm/toolbox/evm.d.ts +218 -46
- package/dist/types/evm/toolbox/op.d.ts +4 -4
- package/dist/types/evm/types.d.ts +2 -1
- package/dist/types/tron/helpers/trongrid.d.ts +2 -2
- package/dist/types/tron/types.d.ts +7 -0
- package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +178 -0
- package/dist/types/utxo/helpers/bchaddrjs.d.ts +17 -1
- package/dist/types/utxo/helpers/txSize.d.ts +7 -5
- package/dist/types/utxo/index.d.ts +1 -1
- package/dist/types/utxo/toolbox/bitcoinCash.d.ts +1 -0
- package/dist/types/utxo/toolbox/index.d.ts +1 -1
- package/dist/types/utxo/toolbox/utxo.d.ts +6 -0
- package/dist/types/utxo/toolbox/validators.d.ts +2 -1
- package/dist/types/utxo/toolbox/zcash.d.ts +1 -0
- package/package.json +2 -2
- package/dist/chunk-44m22jy1.js +0 -1
- package/dist/chunk-ye1j5pz2.js +0 -2
- package/dist/chunk-zhn86hw6.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 5.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#382](https://github.com/swapkit/sdk/pull/382) [`2ef09ec`](https://github.com/swapkit/sdk/commit/2ef09ec782e61176e2576554c25cca6d8f2374de) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Add Arc (`5042`) EVM chain: chain/chainId enums, chain config, EVM toolbox wiring, and native `ARC.USDC` gas-asset handling in `isGasAsset` / `getCommonAssetInfo` / `getAssetType` / `getTokenAddress`. Arc ships with rpcUrls: [], so connectKeystore skips it and toolbox calls fail with helpers_chain_no_public_or_set_rpc_url until SKConfig.setRpcUrl(Chain.Arc, […]) is set
|
|
8
|
+
- [#385](https://github.com/swapkit/sdk/pull/385) [`c8e9da7`](https://github.com/swapkit/sdk/commit/c8e9da74d13ad5b8c533d626400feff9364420fa) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Expose the address form an address string decodes to, instead of discarding it behind a boolean. Address validation already computed the script type; new siblings surface it without changing any existing validator's return type:
|
|
9
|
+
- [#374](https://github.com/swapkit/sdk/pull/374) [`54d0f14`](https://github.com/swapkit/sdk/commit/54d0f14ec3d58e66b0036ad6c8dcfd0f823dbd2a) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `getAddressValidator` now handles the Substrate chains. Polkadot (DOT) and Chainflip (FLIP) had no arm in the chain match, so they fell through to the catch-all and every address — including valid ones — was reported as invalid. Consumers of `swapKit.validateAddress`, which is built on this validator, were affected; the server-side `validateChainAddress` already covered these chains.
|
|
10
|
+
- [#393](https://github.com/swapkit/sdk/pull/393) [`25570ca`](https://github.com/swapkit/sdk/commit/25570ca23f90b4ed104061b5561c35ab1c47f1c6) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **One table describes the UTXO script types.** `@swapkit/helpers` now exports `UTXOScriptType` (with `P2SH_P2WPKH` and `P2TR` alongside `P2PKH` and `P2WPKH`), `UTXO_SCRIPT_TYPES` (BIP43 purpose, input and output size in vBytes, witness flag per type), `UTXO_SCRIPT_TYPE_LIST`, and the path helpers `getPurposeFromPath`, `getUTXOScriptTypeForPurpose` and `getUTXOScriptTypeForPath`. Error key `toolbox_utxo_unsupported_script_type` (50315) is reserved for the toolboxes.
|
|
11
|
+
- [#391](https://github.com/swapkit/sdk/pull/391) [`cf94a27`](https://github.com/swapkit/sdk/commit/cf94a27a52ac37c78d3a72bbbe7ee3acf14c192e) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **Eight fixes to the UTXO send path**, reached today by external signers spending from legacy Bitcoin and Litecoin addresses, and by every chain without segwit.
|
|
12
|
+
- [#391](https://github.com/swapkit/sdk/pull/391) [`cf94a27`](https://github.com/swapkit/sdk/commit/cf94a27a52ac37c78d3a72bbbe7ee3acf14c192e) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **Three fixes to `createReplacementTransaction`/`bumpFee`** (Bitcoin, the only chain in `rbfSupportedChains`):
|
|
13
|
+
- [#379](https://github.com/swapkit/sdk/pull/379) [`4450ac4`](https://github.com/swapkit/sdk/commit/4450ac4200a565d5ce38a26d31f3836a3713ff75) Thanks [@ice-chillios](https://github.com/ice-chillios)! - `derivationPathToString` now accepts sliced derivation paths through the new `DerivationPathLike` (`readonly (number | undefined)[]`) type, so prefixes no longer need to be cast to `DerivationPathArray`. (via @swapkit/helpers@5.4.0)
|
|
14
|
+
- [#362](https://github.com/swapkit/sdk/pull/362) [`cbbfccd`](https://github.com/swapkit/sdk/commit/cbbfccdcbbe3e5ad3ffb531a030e2562c8e3f470) Thanks [@towanTG](https://github.com/towanTG)! - Preserve stored numeric precision across comparisons, arithmetic operands, copies, `set`, and AssetValue conversion instead of converting through display-rounded strings. Compare exact values regardless of declared asset decimals, and cap arithmetic results at 64 decimal places without mis-scaling longer inputs or turning small nonzero divisors into zero. Fix half-up display carries and explicit base-unit rescaling while preserving asset identity and destination decimals. (via @swapkit/helpers@5.4.0)
|
|
15
|
+
- [#399](https://github.com/swapkit/sdk/pull/399) [`70749e7`](https://github.com/swapkit/sdk/commit/70749e7899630daabc371a36c498f62b9da1c62f) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@5.4.0)
|
|
16
|
+
|
|
17
|
+
## 5.3.0
|
|
18
|
+
|
|
19
|
+
### Minor Changes
|
|
20
|
+
|
|
21
|
+
- [#371](https://github.com/swapkit/sdk/pull/371) [`6236419`](https://github.com/swapkit/sdk/commit/623641928563f9e0141c47395a2e1febbd182093) Thanks [@ice-chillios](https://github.com/ice-chillios)! - EVM nonce derivation now reads the "pending" transaction count and serialises allocation per chainId:address behind an expiring monotonic floor, so concurrent sends from one address no longer reuse a mined-only count and silently replace each other in the mempool. Allocations are released when a send provably never reached the wire (gas or fee estimation failure, a rejected send, a signer that cannot sign), so a failed attempt no longer strands a nonce gap; transport-ambiguous failures keep the nonce reserved until the floor expires, and a floor never expires while one of its nonces is held by an in-flight send (a signature awaiting hardware or wallet confirmation cannot have its nonce re-issued). sendTransaction and state-changing contract calls both resolve through the signer's own provider when it carries one — approve + send from a single toolbox share one floor, and the transport-failure fallback broadcast and its hash lookup go through that same provider. Caller-supplied nonces are honoured on the ERC-20 transfer and approval builder paths. The native sweep builder no longer pins a nonce into the built transaction — the OP-stack L1 fee serialisation performs its own plain "pending" read for byte-length only (build-only APIs consume no allocation) — so both `transfer` and a two-step `createTransaction`/`sendTransaction` sweep allocate through the floor on the send path. The toolbox `broadcastTransaction` no longer crashes when invoked (previously an unbound method reference).
|
|
22
|
+
- [#380](https://github.com/swapkit/sdk/pull/380) [`9e8158f`](https://github.com/swapkit/sdk/commit/9e8158f012909b540652f0047f719482628724e1) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - TRON transaction failures now carry a diagnostic payload instead of a bare error key.
|
|
23
|
+
- [#381](https://github.com/swapkit/sdk/pull/381) [`3b750ec`](https://github.com/swapkit/sdk/commit/3b750ec492b40b028f50c1adcf2347c647ad3f2f) Thanks [@ochhii1337](https://github.com/ochhii1337)! - TON's native coin is now `GRAM`, so the gas asset is `TON.GRAM` instead of `TON.TON`. (via @swapkit/helpers@5.3.0)
|
|
24
|
+
- Update generated token lists. (via @swapkit/helpers@5.3.0)
|
|
25
|
+
|
|
3
26
|
## 5.2.1
|
|
4
27
|
|
|
5
28
|
### Patch Changes
|
|
@@ -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 ha};
|
|
@@ -1,2 +1,2 @@
|
|
|
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})=>
|
|
2
|
-
export{C as
|
|
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 fa,h as ga};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{$ as N,A as m,B as n,C as o,D as p,E as q,F as r,G as s,H as t,I as u,J as v,K as w,L as x,M as y,N as z,O as A,P as B,Q as C,R as D,S as E,T as F,U as G,V as H,W as I,X as J,Y as K,Z as L,_ as M,aa as O,ba as P,ca as Q,da as R,ea as S,o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i,x as j,y as k,z as l}from"./chunk-rn33j2bm.js";import"./chunk-as9fracn.js";import"./chunk-4428244x.js";export{u as ADIToolbox,v as ARBToolbox,w as ARCToolbox,x as AURORAToolbox,y as AVAXToolbox,z as BASEToolbox,A as BERAToolbox,B as BSCToolbox,b as BaseEVMToolbox,C as BotanixToolbox,D as COREToolbox,E as CORNToolbox,F as CROToolbox,k as ContractAddress,t as ETHToolbox,G as GNOToolbox,H as HOODToolbox,I as HYPEREVMToolbox,J as LINEAToolbox,K as MATICToolbox,a as MAX_APPROVAL,L as MEGAETHToolbox,M as MONADToolbox,s as OPToolbox,N as PLASMAToolbox,O as SONICToolbox,P as UNIToolbox,Q as XLayerToolbox,e as createContract,r as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,R as getEvmToolbox,S as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,h as toChecksumAddress,c as validateEVMAddress};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e;((o)=>{o.Test="goerli";o.Main="homestead"})(e||={});export{e as a};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ga as Be}from"./chunk-as9fracn.js";import{ha as ye}from"./chunk-4428244x.js";import{Chain as P}from"@swapkit/helpers";import{match as Gn}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as ht,SKConfig as vt,SwapKitError as j}from"@swapkit/helpers";import{FallbackProvider as Et,getAddress as ve,Interface as _t,JsonRpcProvider as se,Network as Ct}from"ethers";import{match as Ee}from"ts-pattern";function At(e){return new se(e)}async function Sn(e,t){return At(t||await ht(e))}function _e(e){let t=vt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new j("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Ct.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Et(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function B(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Ce(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Ft({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 Ft({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return Ee(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 Fe(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 he=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Mt=(e)=>{try{return typeof e==="string"&&!!ve(e)}catch{return!1}};function Gt(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};Ee(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Mt(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})=>!he(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!he(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Bt(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 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 Rn({chain:e,abi:t,data:n,to:o}){let r=new _t(t).parseTransaction({data:n});if(!r)throw new j({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,y]of r.fragment.inputs.entries())c[y.name]=le(r.args[p],y);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:ve(o)},b=Bt(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:b,...i}}}function Me(e,t){if(!Array.isArray(e)||e.length===0)throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(Gt(o,n),t!==void 0&&o.chainId!==t)throw new j({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 En,FeeOption as _n,resolveDerivationPath as Cn}from"@swapkit/helpers";import{HDNodeWallet as An}from"ethers";import{match as Fn,P as Ze}from"ts-pattern";var Ge=[{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 Ot,applyFeeMultiplierToBigInt as M,Chain as O,EVMChains as It,FeeOption as d,isGasAsset as Vt,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as z}from"@swapkit/helpers/contracts";import{BrowserProvider as St,Contract as Ve,getAddress as ee,getBytes as Rt,Interface as Se,isError as U,resolveAddress as Nt,Transaction as pe}from"ethers";import{match as Re}from"ts-pattern";function Y(e){return{getBalance:Be(e)}}function Dn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=O.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=qe({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:Yt({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:Ue({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:mn({chain:e,provider:t,signer:n}),createContract:Lt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:He({provider:t,signer:n}),estimateGasLimit:Zt({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:pn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Ce(e),isApproved:Jt({chain:e,provider:t}),sendTransaction:Ke({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:en({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?({domain:c,types:l,value:u})=>n.signTypedData(c,l,u):void 0,transfer:Qt({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:kt}}function kt(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof St}function ge(e,t,n){return new Ve(e,Se.from(t),n)}function Lt({provider:e}){return function(n,o){return new Ve(n,Se.from(o),e)}}var Dt=["payable","nonpayable"];function Ut({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&&Dt.includes(n.stateMutability)}function Xn(e){return ee(e)}var Ht=30000,Oe=new WeakMap,Ie=()=>{};function zt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>Ht)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 Ne({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Ie,settle:Ie};let{chainId:o}=await n.getNetwork(),a=Oe.get(n)??new Map;Oe.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=zt(a,r,i),l=!1,u=(b)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),b)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(U(e,"NONCE_EXPIRED")||U(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function de(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function ke(e){return U(e,"NETWORK_ERROR")||U(e,"SERVER_ERROR")||U(e,"TIMEOUT")}function Kt(e){return ke(e)||U(e,"UNSUPPORTED_OPERATION")}function Le(e){return ke(e)||de(e)}function De(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function qt({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await De(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,b={...u,...t&&i!==void 0&&{gas:B(BigInt(i))},...t&&s!==void 0&&{gasPrice:B(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:B(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:B(BigInt(l))},value:B(BigInt(o||0))};return e.send("eth_sendTransaction",[b])}}function $n(e,t){let n=Pe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var jt=It.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Wt={...jt,[O.Optimism]:"0x4200000000000000000000000000000000000042",[O.Polygon]:"0x0000000000000000000000000000000000001010"},Xt=[O.Arbitrum,O.Aurora,O.Base,O.Optimism,O.Robinhood];function Pe({chain:e,symbol:t,ticker:n},o){try{let a=e===O.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===O.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Xt.includes(e)&&t==="ETH"&&n==="ETH",c=e===O.Arc&&t==="USDC"&&n==="USDC";if(i||a||r||s||c)return Wt[o];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:B(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return Re(e).with(O.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{[d.Average]:{maxFeePerGas:M(a,d.Average),maxPriorityFeePerGas:M(r,d.Average)},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(O.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{[d.Average]:{gasPrice:r},[d.Fast]:{gasPrice:M(r,d.Fast)},[d.Fastest]:{gasPrice:M(r,d.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{[d.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[d.Average]:{gasPrice:i},[d.Fast]:{gasPrice:M(i,d.Fast)},[d.Fastest]:{gasPrice:M(i,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function $t({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 b=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:y,maxPriorityFeePerGas:f,gasPrice:x},F]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await Nt(u,n),{nonce:G,release:R,settle:k}=await Ne({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await b[a](...r,{...l,gasLimit:F,gasPrice:x,maxFeePerGas:y,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(!Le(_))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:b=d.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let y=Ut({abi:s,funcName:c});if(y&&ne(p)&&n){let F=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await F({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(y){if(!n)throw new m("toolbox_evm_no_signer");return $t({chain:o,contract:f,contractProvider:p,feeOption:b,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let x=await f[c]?.(...l);return typeof x?.hash==="string"?x?.hash:x}}function Ue({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:z,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function Jt({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await Ue({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function Yt({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=d.Fast,amount:c,gasLimitFallback:l,from:u,nonce:b}){let p=[i,BigInt(c||be)],y=await e?.getAddress()||u,f={abi:z,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:y}};if(ne(n)){let F=W({chain:o,provider:n}),C=oe(n),G=await F(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:y,gasLimit:l?BigInt(l.toString()):void 0,nonce:b}})}}function Qt({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=d.Fast,sender:b,sweep:p,...y}){let f=b||await o?.getAddress(),x=Ke({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let F=await qe({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...y});return x({...F,feeOptionKey:u,sweep:p})}}function He({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 Zt({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let b=o.bigIntValue,p=o.isGasAsset?null:Pe(o,o.chain);if(p&&c)return He({provider:e,signer:t})({abi:z,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:y,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?y(f(r)):void 0,from:s,to:a,value:b})}}function en({signer:e}){if(!e)return;return(t)=>Fe(e,t)}var ze=(e)=>e.type===4||(e.authorizations?.length??0)>0,tn=(e)=>!ze(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),nn=(e,t=!0)=>{if(ze(e))return"eip7702";if(tn(e)||t)return"eip1559";return"legacy"};function on(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:B(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:B(t.maxFeePerGas),maxPriorityFeePerGas:B(t.maxPriorityFeePerGas)}}function Ke({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=d.Fast,sweep:s,...c}){let{from:l,to:u,data:b,value:p,...y}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...y,data:b||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let x=l||await o.getAddress(),{chainId:F}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await Ne({address:x,nonce:c.nonce,provider:C}),_=async()=>{let E=nn(f,a);if(E==="eip7702")Me(f.authorizations||[],F);let w=Re(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),V={...f,chainId:F,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},A=t??X({chain:e,isEIP1559Compatible:a,provider:n}),S=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:on(E,(await A())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(I){throw new m("toolbox_evm_error_estimating_gas_limit",{error:I})}return{...V,gasLimit:h,...S}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let V=c.nonce!=null?"caller":"pending",A={address:x,error:w,nonce:G,nonceSource:V};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:A},A);if(de(w)){let h=await qt({provider:C,signer:o,txObject:{...E,from:x}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:A},A)}if(!Kt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:A},A);let L=U(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:x})}catch(h){if(L)R();let I={...A,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let I={...A,fallbackError:h};if(de(h)){let H=pe.from(S).hash;if(H)return H}if(fe(h)){let H=pe.from(S).hash;if(H&&await De(C,H))return H;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:I},I)}if(L&&!Le(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}}}finally{k()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function an(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 rn(e,t){if(e>t)return e;return t}function sn(e){return Rt(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 cn({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)D(e,o+s);let l=await t({...a,value:c})??i;return M(rn(i,l),n)}async function un({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),b=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:y}=an((await b())[a],i),f={...l,...p,data:t,from:r,to:c},x=sn(t)*y;if(u-x<=0n)D(u,x);let F=(u-x)/2n,C;try{C=await s.estimateGas({...f,value:F})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(I){if(me(I))D(u,x);throw I}}let G=C*y;if(u-G<=0n)D(u,G);let _=C*11n/10n*y,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;D(u,_)}let V=w*y,A=u-V;if(A<=0n)D(u,V);let L=await cn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:V,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:A}),S=A-L;if(S<=0n)D(u,V+L);return{...f,gasLimit:w,value:B(S)}}async function ln({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:z,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 qe({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:b,feeOptionKey:p=d.Fast,gasLimit:y,sender:f,sweep:x,type:F,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(x&&(F===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(Vt(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=b||L(S(l||""));if(!x)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...y!==void 0&&{gasLimit:y},to:u,...F!==void 0&&{type:F},value:B(_)};return un({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:F}})}let w=Pe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),A=x?await ln({chain:e,contractAddress:w,from:E,provider:a}):_;if(x&&A<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:A.toString()}});return V({abi:z,contractAddress:w,funcName:"transfer",funcParams:[u,A],txOverrides:{from:E,gasLimit:y,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function mn({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}),b=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:z,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(b)],txOverrides:{from:l,nonce:c}})}}function pn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=d.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=Ot.from({chain:n}),{gasPrice:u,maxFeePerGas:b,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(b&&p){let y=(b+p)*c;return l.set(Q.fromBigInt(y,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as K,Chain as Xe,derivationPathToString as fn,FeeOption as N,getChainConfig as dn,resolveDerivationPath as yn,SwapKitError as q}from"@swapkit/helpers";import{Contract as bn,HDNodeWallet as gn}from"ethers";import{match as Pn,P as We}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 xn="0x420000000000000000000000000000000000000f";function re(e){return new bn(xn,je,e)}function $e(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function Je(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 xe(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await Je(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 Te(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 Tn(e,t){let n=xe(e,t),o=Te(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 Ye(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function wn(e){return async function(n){let o=await xe(e)(n)??0n,a=await Ye(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await Te(e)(BigInt(r.toString()));return o+a+i}}function hn(e){return async function(n){let o=re(e),a=await Je(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function vn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await $e(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[N.Average]:{gasPrice:i,l1GasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:o},[N.Fast]:{gasPrice:K(i,N.Fast),l1GasPrice:K(r||0n,N.Fast),maxFeePerGas:n,maxPriorityFeePerGas:K(o,N.Fast)},[N.Fastest]:{gasPrice:K(i,N.Fastest),l1GasPrice:K(r||0n,N.Fastest),maxFeePerGas:n,maxPriorityFeePerGas:K(o,N.Fastest)}}}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=Pn(o).with({phrase:We.string},({phrase:p,derivationPath:y,index:f=0})=>gn.fromPhrase(p,void 0,fn(yn({chain:e,derivationPath:y,index:f}))).connect(n)).with({signer:We.any},({signer:p})=>p).otherwise(()=>{return}),r=$e(n),i=BigInt(dn(e).chainId),s=xe(n,i),c=Tn(n,i),l=Te(n),u=e===Xe.Optimism?vn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:hn(n),estimateL1GasCost:s,estimateL2GasCost:Ye(n),estimateOperatorFee:l,estimateTotalGasCost:wn(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var Qe=ie(Xe.Optimism);function et(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=_n.Fast){let s=await t.createContractTxObject({abi:Ge,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var tt=v(T.Adi),nt=v(T.Arbitrum),ot=v(T.Arc),at=v(T.Aurora),rt=v(T.Avalanche),it=ie(T.Base),st=v(T.Berachain),ct=v(T.BinanceSmartChain),po=v(T.Botanix),ut=v(T.Core),lt=v(T.Corn),mt=v(T.Cronos),pt=v(T.Gnosis),ft=v(T.Robinhood),dt=v(T.Hyperevm),yt=v(T.Linea),bt=v(T.Polygon),gt=v(T.MegaETH),Pt=v(T.Monad),xt=v(T.Plasma),we=v(T.Sonic),Tt=ie(T.Unichain),wt=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=Fn(o).with({phrase:Ze.string},({phrase:s,derivationPath:c,index:l=0})=>An.fromPhrase(s,void 0,En(Cn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:Ze.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Bn(e,t){return Gn(e).with(P.Adi,()=>tt(t)).with(P.Arbitrum,()=>nt(t)).with(P.Arc,()=>ot(t)).with(P.Aurora,()=>at(t)).with(P.Avalanche,()=>rt(t)).with(P.Base,()=>it(t)).with(P.Berachain,()=>st(t)).with(P.BinanceSmartChain,()=>ct(t)).with(P.Botanix,()=>we(t)).with(P.Core,()=>ut(t)).with(P.Corn,()=>lt(t)).with(P.Cronos,()=>mt(t)).with(P.Ethereum,()=>et(t)).with(P.Gnosis,()=>pt(t)).with(P.Hyperevm,()=>dt(t)).with(P.Linea,()=>yt(t)).with(P.MegaETH,()=>gt(t)).with(P.Monad,()=>Pt(t)).with(P.Optimism,()=>Qe(t)).with(P.Plasma,()=>xt(t)).with(P.Polygon,()=>bt(t)).with(P.Robinhood,()=>ft(t)).with(P.Sonic,()=>we(t)).with(P.Unichain,()=>Tt(t)).with(P.XLayer,()=>wt(t)).exhaustive()}async function Po(e,t){let n={...t,provider:t?.provider||_e(e)};return Bn(e,n)}
|
|
2
|
+
export{Y as b,Dn as c,At as d,Sn as e,_e as f,B as g,Ce as h,Ae as i,Fe as j,Gt as k,Bt as l,Rn as m,Me as n,be as o,te as p,kt as q,ne as r,ge as s,Lt as t,Ut as u,Xn as v,oe as w,$n as x,Wt as y,Pe as z,W as A,X as B,ze as C,tn as D,nn as E,ie as F,Qe as G,et as H,tt as I,nt as J,ot as K,at as L,rt as M,it as N,st as O,ct as P,po as Q,ut as R,lt as S,mt as T,pt as U,ft as V,dt as W,yt as X,bt as Y,gt as Z,Pt as _,xt as $,we as aa,Tt as ba,wt as ca,Bn as da,Po as ea};
|
package/dist/src/aleo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fa as zJ}from"../../chunk-nvfkjbyq.js";import{ga as b}from"../../chunk-xbdjxeqd.js";import{hmac as s}from"@noble/hashes/hmac.js";import{sha512 as t}from"@noble/hashes/sha2.js";import{Chain as h,getChainConfig as BJ,SKConfig as DJ,SwapKitError as B}from"@swapkit/helpers";var kJ=/^aleo1[ac-hj-np-z02-9]{58}$/,MJ=/^[a-z0-9_]+\.aleo$/,T=/^at1[ac-hj-np-z02-9]+$/,xJ=new TextEncoder().encode("bls12_377 seed"),o=2147483648,A=1e6,f="credits.aleo",R="transfer_public",a=1e6,e=2000000;function r(J,Z){if(!M(J))return[];let Y=M(J.transaction)?J.transaction:J,W=Y.execution,z=M(Y.fee)?Y.fee.transition:void 0;return[...M(W)&&Array.isArray(W.transitions)?W.transitions:[],...M(z)?[z]:[]].flatMap((P)=>{if(!M(P)||!Array.isArray(P.outputs))return[];if(Z&&P.program!==Z)return[];return P.outputs.flatMap((O)=>M(O)&&O.type==="record"&&typeof O.value==="string"?[O.value]:[])})}function JJ(J){return J.reduce((Z,Y)=>Y.spent?Z:Z+Y.microcredits,0n)}function x(J,Z){return Z instanceof B&&Z.errorKey.startsWith("toolbox_aleo_")?Z:new B(J,Z)}function OJ(...J){let Z=J.reduce((z,U)=>z+U.length,0),Y=new Uint8Array(Z),W=0;for(let z of J)Y.set(z,W),W+=z.length;return Y}function bJ(J){let Z=new Uint8Array(4);return new DataView(Z.buffer).setUint32(0,J,!1),Z}function PJ(J){let Z=s(t,xJ,J);return{chainCode:Z.slice(32),key:Z.slice(0,32)}}function yJ(J,Z){if(!Number.isSafeInteger(Z)||Z<0||Z>=o)throw new B("toolbox_aleo_wasm_init_failed",{index:Z});let Y=Z+o,W=OJ(Uint8Array.of(0),J.key,bJ(Y)),z=s(t,J.chainCode,W);return{chainCode:z.slice(32),key:z.slice(0,32)}}function QJ(J,Z){let Y=J.split("/");if(Y.shift()!=="m"||Y.length===0)throw new B("toolbox_aleo_wasm_init_failed",{path:J});return Y.reduce((W,z)=>{if(!/^\d+'$/.test(z))throw new B("toolbox_aleo_wasm_init_failed",{path:J,segment:z});return yJ(W,Number.parseInt(z.slice(0,-1),10))},PJ(Z))}function S(J){return typeof J==="string"&&kJ.test(J)}async function ZJ(J){if(!S(J))return!1;try{let{Account:Z}=await import("@provablehq/sdk/mainnet.js");return Z.isValidAddress(J)}catch{return!1}}function VJ(J){return MJ.test(J)}function $J(J,Z){if(J===null)return 0n;if(typeof J!=="string")throw new B("toolbox_aleo_balance_error",{integerType:Z,value:J});let Y=J.match(new RegExp(`^(\\d+)${Z}$`));if(!Y?.[1])throw new B("toolbox_aleo_balance_error",{integerType:Z,value:J});return BigInt(Y[1])}function E(J){if(J.chain!==h.Aleo)throw new B("toolbox_aleo_unsupported_token",{asset:J.toString()});let Z=J.getBaseValue("bigint");if(J.isGasAsset)return{amount:`${Z}u64`,functionName:R,isTokenTransfer:!1,programName:f};if(!J.address||!VJ(J.address))throw new B("toolbox_aleo_unsupported_token",{asset:J.toString()});return{amount:`${Z}u128`,functionName:R,isTokenTransfer:!0,programName:J.address}}function K(){let J=[...new Set([...DJ.get("rpcUrls")[h.Aleo],...BJ(h.Aleo).rpcUrls])].filter(Boolean);if(J.length===0)throw new B("toolbox_aleo_no_rpc_urls");return J}function m(J){if(typeof J==="object"&&J!==null&&"status"in J&&J.status===404)return!0;return J instanceof Error&&J.message.includes("404")}function M(J){return typeof J==="object"&&J!==null}function fJ(J){if(!M(J))return!1;return[J.transaction,J.rejected].some((Z)=>{if(!M(Z)||!M(Z.execution))return!1;let{transitions:Y}=Z.execution;return Array.isArray(Y)&&Y.some((W)=>M(W)&&W.function===R&&typeof W.program==="string"&&W.program!==f)})}function KJ(J,Z){if(!M(J)||typeof J.status!=="string")throw new B("toolbox_aleo_transaction_failed",{response:J,transactionId:Z});let Y=J.status.toLowerCase();if(Y==="rejected"){let W=fJ(J)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new B(W,{transactionId:Z})}return Y==="accepted"?"accepted":"pending"}async function FJ(J){if(!T.test(J))throw new B("toolbox_aleo_transaction_failed",{transactionId:J});let Z,Y=!0;for(let W of K())try{let{AleoNetworkClient:z}=await import("@provablehq/sdk/mainnet.js"),U=await new z(W).getConfirmedTransaction(J);return KJ(U,J)}catch(z){if(z instanceof B)throw z;Z=z,Y=Y&&m(z)}if(Y)return"pending";throw x("toolbox_aleo_transaction_failed",Z)}async function g(J,{intervalMs:Z=5000,timeoutMs:Y=60000}={}){let W=Date.now();while(Date.now()-W<Y){let z=await FJ(J);if(z==="accepted")return z;await new Promise((U)=>setTimeout(U,Z))}throw new B("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:J})}import{AssetValue as _,Chain as F,derivationPathToString as wJ,NetworkDerivationPath as NJ,SwapKitError as L}from"@swapkit/helpers";async function HJ(J,Z){try{let{Account:Y}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:W}=await import("@scure/bip39"),z=wJ(Z||NJ[F.Aleo],{allHardened:!0}),{key:U}=QJ(z,W(J));return new Y({seed:U})}catch(Y){throw x("toolbox_aleo_wasm_init_failed",Y)}}function YJ(J,Z){let Y,W=()=>{return Y??=HJ(J,Z),Y};return{getAddress:async()=>(await W()).address().to_string(),signTransaction:async(z)=>{let U=await W();if(z.sender!==U.address().to_string())throw new L("toolbox_aleo_invalid_address",{address:z.sender});let P;for(let O of K())try{let{ProgramManager:y}=await import("@provablehq/sdk/mainnet.js"),N=new y(O);return N.setAccount(U),await N.buildExecutionTransaction({functionName:z.functionName,inputs:z.inputs,priorityFee:z.priorityFee/A,privateFee:!1,programName:z.programName})}catch(y){P=y}throw P}}}function _J(J={}){if("phrase"in J&&J.phrase&&"signer"in J&&J.signer)throw new L("toolbox_aleo_conflicting_signers");let Z;async function Y(){if(Z)return Z;let $="phrase"in J?J.phrase:void 0;if(!$)throw new L("toolbox_aleo_no_signer");let Q="derivationPath"in J?J.derivationPath:void 0;return Z=await HJ($,Q),Z}let W;function z(){let $="signer"in J?J.signer:void 0;if($)return $;let Q="phrase"in J?J.phrase:void 0;if(!Q)throw new L("toolbox_aleo_no_signer");return W??=YJ(Q,"derivationPath"in J?J.derivationPath:void 0),W}async function U($){let Q;for(let X of K())try{let{AleoNetworkClient:H}=await import("@provablehq/sdk/mainnet.js");return await $(new H(X))}catch(H){Q=H}throw Q}async function P($){let Q;for(let X of K())try{let{AleoNetworkClient:H}=await import("@provablehq/sdk/mainnet.js");return await new H(X).getTransitionId($),!0}catch(H){if(m(H))return!1;Q=H}throw Q}async function O(){let $=z();try{return await $.getAddress()}catch(Q){throw x("toolbox_aleo_wasm_init_failed",Q)}}async function y($){let Q=await U((X)=>X.getProgramMappingValue(f,"account",$));return $J(Q,"u64")}async function N($){try{let Q=await y($);return[_.from({chain:F.Aleo,fromBaseDecimal:6,value:Q})]}catch(Q){throw x("toolbox_aleo_balance_error",Q)}}let u=zJ(F.Aleo);async function p($,Q=!0){try{return await u($,Q)}catch{return N($)}}async function WJ(){return p(await O())}async function v({transactionIds:$}){try{let Q=await Y(),X=[];for(let H of $){if(!T.test(H))throw new L("toolbox_aleo_transaction_failed",{transactionId:H});let D=await U((j)=>j.getTransaction(H));for(let j of r(D,f)){if(!Q.ownsRecordCiphertext(j))continue;let{RecordPlaintext:G}=await import("@provablehq/sdk/mainnet.js"),q=Q.decryptRecord(j).toString(),k=G.fromString(q),w=k.microcredits();if(w===0n)continue;let C=Q.generateRecordViewKey(j).toString(),V=k.serialNumberString(Q.privateKey(),f,"credits",C);X.push({microcredits:w,plaintext:q,spent:await P(V),transactionId:H})}}return X}catch(Q){throw x("toolbox_aleo_balance_error",Q)}}async function XJ({transactionIds:$}){let Q=await v({transactionIds:$});return _.from({chain:F.Aleo,fromBaseDecimal:6,value:JJ(Q)})}async function qJ($,Q){if(!Number.isSafeInteger(Q)||Q<=0)throw new L("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:Q});let X=await Y();if(!$||$.microcredits<=BigInt(Q)*BigInt(A))throw new L("toolbox_aleo_insufficient_fee_balance",{available:$?.microcredits.toString(),required:`${Q} credits fee record`});let{ProgramManager:H,RecordPlaintext:D}=await import("@provablehq/sdk/mainnet.js"),j;for(let G of K())try{let q=new H(G);return q.setAccount(X),await q.split(Q,D.fromString($.plaintext))}catch(q){j=q}throw j}async function jJ($,Q,X){let H=await Y(),{ProgramManager:D,RecordPlaintext:j}=await import("@provablehq/sdk/mainnet.js"),G;for(let q of K())try{let k=new D(q);return k.setAccount(H),await k.buildExecutionTransaction({feeRecord:j.fromString(Q.plaintext),functionName:"transfer_private_to_public",inputs:[$.plaintext,X,`${$.microcredits}u64`],priorityFee:0,privateFee:!0,programName:f})}catch(k){G=k}throw G}async function l($,Q,X){let H;try{let j=(await Y()).address().to_string(),G=$.filter((V)=>!V.spent);if(G.length===0)throw new L("toolbox_aleo_no_unspent_records",{transactionId:X});if(G.length===1){if(H=await qJ(G[0],Q),await g(H),G=(await v({transactionIds:[H]})).filter((V)=>!V.spent),G.length<2)throw new L("toolbox_aleo_transaction_failed",{transactionId:H})}let q=[...G].sort((V,UJ)=>V.microcredits<UJ.microcredits?-1:1),k=q[0],w=q[q.length-1];if(!k||!w||k===w)throw new L("toolbox_aleo_no_unspent_records",{transactionId:X});let C=await I(await jJ(w,k,j));return await g(C),{publicBalance:_.from({chain:F.Aleo,fromBaseDecimal:6,value:await y(j)}),splitTransactionId:H,unshieldTransactionId:C}}catch(D){if(H)throw new L("toolbox_aleo_transaction_failed",{error:D,splitTransactionId:H});throw x("toolbox_aleo_transaction_failed",D)}}async function GJ($){try{if("records"in $&&$.records)return await l($.records,$.feeRecordCredits??4);let Q=await v({transactionIds:[$.transactionId]});return await l(Q,$.feeRecordCredits??4,$.transactionId)}catch(Q){throw x("toolbox_aleo_transaction_failed",Q)}}function c({assetValue:$,priorityFee:Q=0}){try{if(!Number.isSafeInteger(Q)||Q<0)throw new L("toolbox_aleo_fee_estimation_failed",{priorityFee:Q});let H=E($).isTokenTransfer?e:a;return _.from({chain:F.Aleo,fromBaseDecimal:6,value:BigInt(H)+BigInt(Q)})}catch(X){throw x("toolbox_aleo_fee_estimation_failed",X)}}async function d({assetValue:$,priorityFee:Q=0,recipient:X,sender:H}){if(!await ZJ(X))throw new L("toolbox_aleo_invalid_address",{address:X});let D=H||await O();if(!S(D))throw new L("toolbox_aleo_invalid_address",{address:D});let j=E($),G=await c({assetValue:$,priorityFee:Q,recipient:X});try{let q=await y(D);if(_.from({chain:F.Aleo,fromBaseDecimal:6,value:q}).lt(G))throw new L("toolbox_aleo_insufficient_fee_balance",{available:q.toString(),required:G.getBaseValue("string")});return{functionName:j.functionName,inputs:[X,j.amount],priorityFee:Q,programName:j.programName,sender:D}}catch(q){throw x("toolbox_aleo_transaction_failed",q)}}async function i($){try{return await z().signTransaction($)}catch(Q){throw x("toolbox_aleo_transaction_failed",Q)}}async function n($){return I(await i($))}async function I($){try{let Q=typeof $==="string"?$:$.toString(),X=await U((H)=>H.submitTransaction(Q));if(!T.test(X))throw new L("toolbox_aleo_broadcast_error",{transactionId:X});return X}catch(Q){throw x("toolbox_aleo_broadcast_error",Q)}}async function LJ($){let Q=await d({...$,sender:await O()});return n(Q)}return{broadcastTransaction:I,createSigner:YJ,createTransaction:d,estimateTransactionFee:c,getAddress:O,getBalance:u,getBalanceFromRpc:N,getBalances:WJ,getBalanceWithFallback:p,getRecords:v,getShieldedBalance:XJ,signAndBroadcastTransaction:n,signTransaction:i,transfer:LJ,unshield:GJ,validateAddress:S}}export{g as waitForAleoTransaction,VJ as validateAleoProgramId,ZJ as validateAleoAddressWithChecksum,S as validateAleoAddress,JJ as sumUnspentRecords,KJ as parseAleoTransactionStatus,$J as parseAleoMappingValue,M as isRecord,m as isNotFoundError,fJ as isAleoTokenTransferResponse,K as getConfiguredAleoUrls,E as getAleoTransferRoute,FJ as getAleoTransactionStatus,_J as getAleoToolbox,PJ as getAleoMasterSeed,x as getAleoError,r as extractAleoRecordCiphertexts,QJ as deriveAleoPath,yJ as deriveAleoChildKey,R as TRANSFER_PUBLIC_FUNCTION,f as NATIVE_PROGRAM_ID,A as MICRO_CREDITS_PER_CREDIT,o as HARDENED_OFFSET,a as ALEO_TRANSFER_PUBLIC_FEE,T as ALEO_TRANSACTION_ID_REGEX,e as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,MJ as ALEO_PROGRAM_ID_REGEX,xJ as ALEO_HD_KEY,kJ as ALEO_ADDRESS_REGEX};
|
|
1
|
+
import{ga as it}from"../../chunk-as9fracn.js";import{ha as x}from"../../chunk-4428244x.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{ha as B}from"../../chunk-4428244x.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{ha as R}from"../../chunk-4428244x.js";import{bech32 as ne}from"@scure/base";import{mnemonicToEntropy as re}from"@scure/bip39";import{wordlist as oe}from"@scure/bip39/wordlists/english.js";import{AssetValue as S,Chain as w,getChainConfig as se,SwapKitError as h}from"@swapkit/helpers";import m from"bignumber.js";var X="mainnet3YT7XK6NidLPlkHxxyBB5V0WzXUOTIJS",J="https://cardano-mainnet.blockfrost.io/api/v0",U=2147483648,W=0;async function z(e,t){let o=await fetch(`${J}${e}`,{...t,headers:{project_id:X,...t?.headers}});if(!o.ok)throw Error(`Blockfrost API error: ${o.status} ${o.statusText}`);return o.json()}async function Q(e){try{return await z(`/addresses/${e}/utxos`)}catch{return[]}}async function ae(){return(await z("/blocks/latest")).slot}async function ie(){let e=await z("/epochs/latest/parameters"),t={PlutusScriptV1:e.cost_models.PlutusV1?Object.values(e.cost_models.PlutusV1):[],PlutusScriptV2:e.cost_models.PlutusV2?Object.values(e.cost_models.PlutusV2):[],PlutusScriptV3:e.cost_models.PlutusV3?Object.values(e.cost_models.PlutusV3):[]};return{collateralPercent:new m(e.collateral_percent),languageView:t,maxValueSize:Number.parseInt(e.max_val_size,10),minFeeA:new m(e.min_fee_a),minFeeB:new m(e.min_fee_b),minFeeRefScriptCostPerByte:new m(15),priceMem:new m(e.price_mem),priceSteps:new m(e.price_step),stakeKeyDeposit:new m(2000000),utxoCostPerByte:new m(e.coins_per_utxo_size)}}async function Y(e){let t=await fetch(`${J}/tx/submit`,{body:Buffer.from(e,"hex"),headers:{"Content-Type":"application/cbor",project_id:X},method:"POST"});if(!t.ok){let o=await t.text();throw Error(`Transaction submission failed: ${o}`)}return t.json()}function ce(e,t){return e.map((o)=>{let c=o.amount.find((r)=>r.unit==="lovelace"),a=c?new m(c.quantity):new m(0),u=o.amount.filter((r)=>r.unit!=="lovelace").map((r)=>({amount:new m(r.quantity),assetName:r.unit.slice(56),policyId:r.unit.slice(0,56)}));return{address:t,amount:a,index:o.output_index,tokens:u,txId:o.tx_hash}})}function ue({TransactionConstructor:e,auxiliaryData:t,bufferedParams:o,currentSlot:c,inputs:a,recipientAddress:u}){let r=a.reduce((n,s)=>n.plus(s.amount),new m(0));if(!r.isPositive())throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString()}});let i=new e({protocolParams:o});for(let n of a)i.addInput(n);if(i.addOutput({address:u,amount:r,tokens:[]}),i.setTTL(c+3600),t)i.setAuxiliaryData(t);i.setFee(i.calculateFee());let y=i.getFee(),d=r.minus(y),p={address:u,amount:d,tokens:[]},P=i.calculateMinUtxoAmountBabbage(p);if(!d.isPositive()||d.lt(P))throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString(),fee:y.toString(),minimumOutput:P.toString()}});return new e({protocolParams:o}).paymentTransaction({auxiliaryData:t,changeAddress:u,inputs:a,outputs:[p],ttl:c+3600})}async function de(e){try{let t=await Q(e),o=0n,c=new Map;for(let r of t){if(!r.amount||!Array.isArray(r.amount))continue;for(let i of r.amount){let{unit:y,quantity:d}=i;if(y==="lovelace")o+=BigInt(d);else{let p=c.get(y)||0n;c.set(y,p+BigInt(d))}}}let a=[],{baseDecimal:u}=se(w.Cardano);if(o>0n)a.push(S.from({chain:w.Cardano,fromBaseDecimal:u,value:o.toString()}));for(let[r,i]of c)a.push(S.from({asset:`${w.Cardano}.${r}`,value:i.toString()}));if(a.length===0)return[S.from({chain:w.Cardano})];return a}catch(t){let o=t instanceof Error?t.message:String(t);return console.error(`Cardano balance fetch error: ${o}`),[S.from({chain:w.Cardano})]}}function le(e){if(!e||typeof e!=="string")return!1;try{let t=ne.decode(e,120);return t.prefix==="addr"||t.prefix==="addr_test"}catch{return!1}}async function me(e,t=0,o=0){let{Bip32PrivateKey:c}=await import("@stricahq/bip32ed25519"),{types:a,address:u,crypto:r}=await import("@stricahq/typhonjs"),i=re(e,oe),d=(await c.fromEntropy(Buffer.from(Array.from(i)))).derive(U+1852).derive(U+1815).derive(U+t),p=d.derive(0).derive(o),P=p.toBip32PublicKey().toPublicKey().toBytes(),A=r.hash28(P),s=d.derive(2).derive(0).toBip32PublicKey().toPublicKey().toBytes(),l=r.hash28(s),_={hash:A,type:a.HashType.ADDRESS},T={hash:l,type:a.HashType.ADDRESS},C=new u.BaseAddress(a.NetworkId.MAINNET,_,T).getBech32(),B=p.toPrivateKey();return{getAddress:()=>C,publicKey:P,publicKeyHash:A,signTransaction:async(k)=>{try{let b=await import("@stricahq/cbors"),I=Buffer.from(k,"hex"),K=b.Decoder.decode(I),[D,O,L,V]=K.value,F=b.Encoder.encode(D),H=r.hash32(F),E=B.sign(H),v=O instanceof Map?O:new Map,M=v.get(W)||[];M.push([P,E]),v.set(W,M);let j=[D,v,L,V];return b.Encoder.encode(j).toString("hex")}catch(b){throw new h("toolbox_cardano_sign_transaction_failed",{message:String(b)})}}}}function we(e){let t,o,c;async function a(){if(!c)c=await ie();return c}async function u(){if(t!==void 0)return t;if(e&&"phrase"in e&&e.phrase){let{derivationPath:n}=e;if(n&&(n.length!==5||n[3]!==0||n[4]===void 0))throw new h("toolbox_derivation_slot_unsupported",{chain:w.Cardano,derivationPath:n});let s=n?.[2]??0,l=n?.[4]??e.index??0;return t=await me(e.phrase,s,l),t}if(e&&"signer"in e&&e.signer)return t=e.signer,t;return}async function r(){if(o)return o;let n=await u();if(!n)return"";if("getAddress"in n)return o=await n.getAddress(),o;return""}async function i(n){let s=n||await r();if(!s)throw new h("core_wallet_connection_not_found");return de(s)}async function y(n){if(n)try{let{tx:T}=await d(n),x=T.getFee();return S.from({chain:w.Cardano,fromBaseDecimal:6,value:x.toString()})}catch{}let s=await a(),l=400,_=s.minFeeB.plus(s.minFeeA.times(l));return S.from({chain:w.Cardano,fromBaseDecimal:6,value:_.toString()})}async function d({sender:n="",recipient:s,assetValue:l,memo:_,pureLovelaceOnly:T=!1,sweep:x=!1}){let{Transaction:C,utils:B}=await import("@stricahq/typhonjs"),k=n||await r();if(!k)throw new h("core_wallet_connection_not_found");let[b,I,K]=await Promise.all([Q(k),ae(),a()]);if(x&&!l.isGasAsset)throw new h({errorKey:"toolbox_not_supported",info:{asset:l.toString(),chain:w.Cardano,feature:"token_sweep"}});let D=x&&l.isGasAsset,O=T||D,L=b.filter((f)=>O?f.amount.some((g)=>g.unit==="lovelace")&&f.amount.every((g)=>g.unit==="lovelace"):f.amount.some((g)=>g.unit==="lovelace")).sort((f,g)=>{let G=f.amount.some((N)=>N.unit!=="lovelace"),te=g.amount.some((N)=>N.unit!=="lovelace");if(G===te)return 0;return G?1:-1}),V=B.getAddressFromString(k),F=B.getAddressFromString(s),H=ce(L,V),E;if(_){let f=new Map;f.set("msg",[_]),E={metadata:[{data:f,label:674}]}}let v={...K,minFeeB:K.minFeeB.plus(K.minFeeA.times(4))};if(D){let f=ue({auxiliaryData:E,bufferedParams:v,currentSlot:I,inputs:H,recipientAddress:F,TransactionConstructor:C}),{payload:g}=f.buildTransaction();return{tx:f,unsignedTx:g}}let M=new m(l.getBaseValue("string")),j=[{address:F,amount:M,tokens:[]}],q=new C({protocolParams:v}).paymentTransaction({auxiliaryData:E,changeAddress:V,inputs:H,outputs:j,ttl:I+3600}),{payload:ee}=q.buildTransaction();return{tx:q,unsignedTx:ee}}async function p(n){let s=await u();if(!s||!("signTransaction"in s))throw new h("core_wallet_connection_not_found");return s.signTransaction(n)}async function P({recipient:n,assetValue:s,memo:l,sweep:_}){let T=await u();if(!T||!("signTransaction"in T))throw new h("core_wallet_connection_not_found");let{unsignedTx:x}=await d({assetValue:s,memo:l,recipient:n,sender:await r(),sweep:_}),C=await p(x);return await Y(C)}async function A(n){let s=await p(n);return await Y(s)}return{createTransaction:d,estimateTransactionFee:y,getAddress:r,getBalance:i,signAndBroadcastTransaction:A,signTransaction:p,transfer:P,validateAddress:le}}export{we as getCardanoToolbox,le as validateCardanoAddress};
|