h_test_1 0.0.46 → 0.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../types/ethereum-network.types.cjs`),t=require(`../../functions/utils/serialize.utils.cjs`),n=require(`../../constants/vite.constants.cjs`),r=require(`../../constants/chains.constants.cjs`),i=require(`../../types/hinkal.types.cjs`),a=require(`../../API/API.cjs`),o=require(`../../constants/kyc.constants.cjs`),s=require(`../../error-handling/error-codes.constants.cjs`),c=require(`../../functions/utils/erc20tokenFunctions.cjs`);require(`../../API/index.cjs`);const l=require(`../../crypto/poseidon.cjs`),u=require(`../crypto-keys/keys.cjs`),d=require(`../../functions/pre-transaction/solana.cjs`),f=require(`./hinkalCheckSolanaTokenRegistry.cjs`),p=require(`../../functions/web3/functionCalls/accessTokenCalls.cjs`),m=require(`../../functions/utils/token-check.utils.cjs`),h=require(`../TokenDBs/PrivateTokensDB.cjs`),g=require(`../../functions/web3/events/getShieldedBalance.cjs`),ee=require(`../../functions/utils/reloadPage.cjs`),_=require(`../../functions/utils/cacheDevice.utils.cjs`),v=require(`../../functions/web3/getContractMetadata.cjs`),y=require(`../../providers/SolanaProviderAdapter.cjs`),b=require(`./hinkalCheckTokenRegistry.cjs`),x=require(`../merkle-tree/MerkleTree.cjs`);require(`../merkle-tree/index.cjs`);const S=require(`./hinkalDeposit.cjs`),te=require(`../../functions/private-wallet/emporium.helpers.cjs`),C=require(`../../functions/web3/events/getApprovedBalance.cjs`),ne=require(`../../functions/kyc/checkTokenLimitsUSD.cjs`),w=require(`./hinkalDepositAndWithdraw.cjs`),T=require(`./hinkalSolanaDeposit.cjs`),E=require(`./hinkalSwap.cjs`),D=require(`./hinkalWithdraw.cjs`),O=require(`./resetMerkleTrees.cjs`),k=require(`../MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.cjs`),A=require(`./hinkalPrivateWallet.cjs`),j=require(`./hinkalGetRecipientInfo.cjs`),M=require(`./hinkalSignSubAccount.cjs`),N=require(`./hinkalActionReceive.cjs`);require(`../TokenDBs/index.cjs`);const P=require(`./hinkalProoflessDeposit.cjs`),F=require(`./hinkalProxySwap.cjs`),I=require(`./hinkalMultiSend.cjs`),L=require(`./hinkalTransfer.cjs`),R=require(`./hinkalProxyToPrivate.cjs`),z=require(`../../providers/TronProviderAdapter.cjs`),B=require(`./hinkalSolanaDepositAndWithdraw.cjs`),V=require(`./hinkalSolanaWithdraw.cjs`),H=require(`./hinkalSolanaTransfer.cjs`),U=require(`./hinkalSolanaSwap.cjs`),W=require(`./hinkalSolanaProxySend.cjs`),G=require(`./hinkalSolanaProxySwap.cjs`),K=require(`./hinkalSolanaProxyShield.cjs`),q=require(`../../functions/web3/fetchSolanaMerkleTreeRootHash.cjs`),J=require(`./hinkalDepositAndBridge.cjs`),Y=require(`./hinkalClaimUtxo.cjs`),X=require(`./hinkalSolanaProoflessDeposit.cjs`),Z=require(`./hinkalSolanaClaimUtxo.cjs`),re=require(`./hinkalWithdrawStuckUtxos.cjs`);let Q=require(`ethers`),$=require(`@solana/web3.js`);var ie=class{ethereumProviderAdapter;solanaProviderAdapter;tronProviderAdapter;userKeys;signingMessage=`Login to Hinkal Protocol`;privateTransferSigningMessage=`Login to Hinkal's Private Transfer App`;merkleTreeHinkalByChain={};merkleTreeAccessTokenByChain={};nullifiersByChain={};encryptedOutputsByChain={};approvalsByChain={};commitmentsSnapshotServiceByChain={};nullifierSnapshotServiceByChain={};accessTokenSnapshotServiceByChain={};approvalsSnapshotServiceByChain={};utxoUtils;lastCallState=new Map;cacheDevice;generateProofRemotely;disableMerkleTreeUpdates;constructor(e){this.userKeys=new u.UserKeys(void 0),r.HINKAL_SUPPORTED_CHAINS.forEach(e=>{this.merkleTreeHinkalByChain[e]=x.MerkleTree.create(l.poseidonFunction,0n),this.merkleTreeAccessTokenByChain[e]=x.MerkleTree.create(l.poseidonFunction,0n),this.nullifiersByChain[e]=new Set,this.encryptedOutputsByChain[e]=[],this.approvalsByChain[e]=new Map}),this.generateProofRemotely=e?.generateProofRemotely??!1,this.utxoUtils=new k.MultiThreadedUtxoUtils,this.cacheDevice=_.createCacheDevice(e),this.disableMerkleTreeUpdates=e?.disableMerkleTreeUpdates??!1}enforceRateLimit(e,n,r=1e3){let i=Date.now(),a=t.CustomJSONStringify(n),o=this.lastCallState.get(e);if(o&&o.argsKey===a&&i-o.timestamp<r)throw Error(`${e} was already called with the same arguments`);this.lastCallState.set(e,{timestamp:i,argsKey:a})}getProviderAdapter(e){let t=e;t||=this.ethereumProviderAdapter?r.chainIds.ethMainnet:this.solanaProviderAdapter?r.chainIds.solanaMainnet:r.chainIds.tronMainnet;let n;if(n=r.isSolanaLike(t)?this.solanaProviderAdapter:r.isTronLike(t)?this.tronProviderAdapter:this.ethereumProviderAdapter,!n)throw Error(`ProviderAdapter is not initialized`);return n}async initProviderAdapter(e,t){let n=r.chainIds.ethMainnet;t instanceof y.SolanaProviderAdapter?n=r.chainIds.solanaMainnet:t instanceof z.TronProviderAdapter&&(n=r.currentTronChainId),await this.updateProviderAdapter(n,t),t.initConnector(e);let i=await t.connectAndPatchProvider(e);await t.init(i),await this.setListeners()}getSigningMessage(e=i.LoginMessageMode.PROTOCOL){switch(e){case i.LoginMessageMode.PRIVATE_TRANSFER:return this.privateTransferSigningMessage;case i.LoginMessageMode.PROTOCOL:default:return this.signingMessage}}async initUserKeys(e=i.LoginMessageMode.PROTOCOL){let t=this.getSigningMessage(e);this.userKeys=new u.UserKeys(await this.getProviderAdapter().signMessage(t))}initUserKeysWithSignature(e){this.userKeys=new u.UserKeys(e)}async initUserKeysFromSeedPhrases(e){let t=e.join(` `),n=Q.ethers.toUtf8Bytes(t);this.userKeys=new u.UserKeys(Q.ethers.keccak256(n))}async resetMerkle(e){this.disableMerkleTreeUpdates||(e?.every(e=>this.isSelectedNetworkSupported(e))??!0)&&await O.resetMerkleTrees(this,e)}getTronWeb(){let e=this.tronProviderAdapter;if(!e)throw Error(`Tron provider adapter not initialized`);if(!(e instanceof z.TronProviderAdapter))throw Error(`Tron provider adapter is not a TronProviderAdapter`);let t=e.getTronWeb();if(!t)throw Error(`TronWeb not available`);return t}getSupportedChains(){return this.ethereumProviderAdapter&&this.solanaProviderAdapter?r.WALLET_SUPPORTED_CHAINS:this.ethereumProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>!r.isSolanaLike(e)&&!r.isTronLike(e)):this.solanaProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>r.isSolanaLike(e)):this.tronProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>r.isTronLike(e)):[]}async waitForTransaction(e,t,n=1){return!!await this.getProviderAdapter(e).waitForTransaction(e,t,n)}getContract(e,t,n=void 0){return this.getProviderAdapter(e).getContract(e,t,n)}getContractWithFetcherByChainId(e,t,n=void 0){return v.getContractWithFetcherByChainId(e,t,n)}async signMessage(e){return await this.getProviderAdapter().signMessage(e)}async signTypedData(e,t,n){return await this.getProviderAdapter().signTypedData(e,t,n)}async signWithSubAccount(e,t,n,r){return M.hinkalSignSubAccount(e,t,n,r)}getContractWithSigner(e,t,n=``){return this.getProviderAdapter(e).getContractWithSigner(e,t,n)}getContractWithFetcher(e,t,n=``){return this.getProviderAdapter(e).getContractWithFetcher(e,t,n)}isSelectedNetworkSupported(e){return!!r.networkRegistry[e]}async switchNetwork(e){try{await this.getProviderAdapter().switchNetwork(e)}catch{throw Error(s.transactionErrorCodes.FAILED_TO_SWITCH_NETWORKS)}}isPermitterAvailable(e){return this.getProviderAdapter(e).isPermitterAvailable()}async disconnectFromConnector(){await this.ethereumProviderAdapter?.disconnectFromConnector(),await this.solanaProviderAdapter?.disconnectFromConnector(),await this.tronProviderAdapter?.disconnectFromConnector()}async resetProviderAdapters(){this.ethereumProviderAdapter=void 0,this.solanaProviderAdapter=void 0,this.tronProviderAdapter=void 0}async updateProviderAdapter(e,t){try{r.isSolanaLike(e)?(this.solanaProviderAdapter&&this.solanaProviderAdapter.release(),this.solanaProviderAdapter=t):r.isTronLike(e)?(this.tronProviderAdapter&&this.tronProviderAdapter.release(),this.tronProviderAdapter=t):(this.ethereumProviderAdapter&&this.ethereumProviderAdapter.release(),this.ethereumProviderAdapter=t)}catch(e){throw console.error(e),Error(`updateProviderAdapter failed, please try again.`)}}async setListeners(){this.ethereumProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}}),this.solanaProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}}),this.tronProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}})}async onAccountChanged(){await this.ethereumProviderAdapter?.onAccountChanged(),await this.solanaProviderAdapter?.onAccountChanged(),await this.tronProviderAdapter?.onAccountChanged();let e=i.EventType.AccountChanged;typeof document<`u`?document?.dispatchEvent(new Event(e)):process?.emit(`message`,e,void 0)}async onChainChanged(e){e?await this.getProviderAdapter(e).onChainChanged(e):(await this.disconnectFromConnector(),ee.reloadPage())}async monitorConnectedAddress(e){await a.API.monitor(await this.getEthereumAddressByChain(e))}async getBalances(e,t,n,r,i=!1,a,o=!1){return g.getShieldedBalance(this,e,t,n,r,i,this.generateProofRemotely,a,o)}async getApprovedBalances(e,t=!1,n=!1){return C.getApprovedBalance(this,e,t,n)}async getTotalBalance(e,t,i,a=!1,o,s=!1){let l=i??await this.getEthereumAddressByChain(e),u=t??this.userKeys,d=await this.getBalances(e,u.getShieldedPrivateKey(),u.getShieldedPublicKey(),l,a,o,s),f=!r.isSolanaLike(e)&&!s?await this.getApprovedBalances(e,a,o):new Map,p=n.isExtension?await h.privateTokensDB.getPrivateTokens(e,l):c.getErc20TokensForChain(e),m=[];return p.forEach(e=>{let t=e.erc20TokenAddress.toLowerCase(),n=d.get(t),r=f.get(t),i={token:e,balance:(n?.balance??0n)+(r?.balance??0n),timestamp:n?.timestamp||r?.timestamp||`0`,nfts:n?.nfts||[]};m.push(i)}),m}async getStuckShieldedBalances(e,t,n){return(await this.getTotalBalance(e,t,n,!1,!1,!0)).filter(e=>e.balance>0n)}getSupportedPassportLinks(){return o.supportedPassportLinks}checkAccessToken(e,t){return p.checkHinkalAccessToken(this,e,t)}checkExternalTokenLimitsUSD(e,t,n){return ne.checkTokenLimitsUSD(e,t,n)}async getHinkalTreeRootHash(t){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:n,originalDeployer:i}=r.networkRegistry[t].contractData;if(!e||!n||!i)throw Error(`Missing Solana configuration for chain ${t}`);let a=new $.PublicKey(i),o=d.getMerkleAccountPublicKey(new $.PublicKey(n),a);return q.fetchSolanaMerkleTreeRootHash(this.getSolanaProgram(e),o)}return this.getContractWithFetcherByChainId(t,e.ContractType.HinkalContract).getRootHash()}async getAccessTokenTreeRootHash(t){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:n,originalDeployer:i}=r.networkRegistry[t].contractData;if(!e||!n||!i)throw Error(`Missing Solana configuration for chain ${t}`);let a=new $.PublicKey(i),o=d.getAccessTokenMerkleAccountPublicKey(new $.PublicKey(n),a);return q.fetchSolanaMerkleTreeRootHash(this.getSolanaProgram(e),o)}return this.getContractWithFetcherByChainId(t,e.ContractType.AccessTokenContract).getRootHash()}async resetMerkleTreesIfNecessary(e){let t=(await Promise.all((e??this.getSupportedChains()).map(async e=>{let[t,n]=await Promise.all([this.getHinkalTreeRootHash(e),this.getAccessTokenTreeRootHash(e)]);return{chainId:e,needsReset:BigInt(t)!==this.merkleTreeHinkalByChain[e].getRootHash()||BigInt(n)!==this.merkleTreeAccessTokenByChain[e].getRootHash()}}))).filter(e=>e.needsReset).map(e=>e.chainId);t.length>0&&(console.log(`resetting merkle tree in resetMerkleTreesIfNecessary for chains:`,t),await this.resetMerkle(t))}async getEthereumAddress(){let e=this.ethereumProviderAdapter??this.solanaProviderAdapter??this.tronProviderAdapter;if(!e)throw Error(`No provider adapter initialized`);return e.getAddress()}getEthereumAddressByChain(e){return this.getProviderAdapter(e).getAddress()}async getRandomRelay(e,t=!1){return(await a.API.getIdleRelay(e,t)).relay}getGasPrice(e){let t=this.getProviderAdapter(e);if(!t)throw Error(`Illegal State of providerAdapter in Hinkal: no providerAdapter initialized`);return t.getGasPrice(e)}getAPI(){return a.API}snapshotsClearInterval(){this.getSupportedChains().forEach(e=>{this.commitmentsSnapshotServiceByChain[e]?.intervalClear(),this.accessTokenSnapshotServiceByChain[e]?.intervalClear(),this.nullifierSnapshotServiceByChain[e]?.intervalClear(),this.approvalsSnapshotServiceByChain[e]?.intervalClear()})}checkTokenRegistry(t,n,i){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:a,originalDeployer:o}=r.networkRegistry[t].contractData;if(!e||!a||!o)throw Error(`missing solana data`);return f.hinkalCheckSolanaTokenRegistry(this.getSolanaProgram(e),new $.PublicKey(o),n,i)}return r.isTronLike(t)?b.hinkalCheckTronTokenRegistry(n,i,t):b.hinkalCheckTokenRegistry(this.getContractWithFetcher(t,e.ContractType.HinkalHelperContract),n,i)}getRecipientInfo(){return j.getRecipientInfo(this)}getApprovedUtxos(e,t=!1){return C.getApprovedUtxos(this,e,t)}getApprovedUtxosForToken(e,t,n=!1){return C.getApprovedUtxosForToken(this,e,t,n)}async deposit(e,t,n=!0,r=!1){return S.hinkalDeposit(this,e,t,n,r)}async depositSolana(e,t){return T.hinkalSolanaDeposit(this,e,t)}async depositForOther(e,t,n,r=!0,i=!1){return this.enforceRateLimit(this.depositForOther.name,[e,t,n]),S.hinkalDepositForOther(this,e,t,n,r,i)}async depositSolanaForOther(e,t,n){return this.enforceRateLimit(this.depositSolanaForOther.name,[e,t,n]),T.hinkalSolanaDepositForOther(this,e,t,n)}async depositAndWithdraw(e,t,n,i,a,o,s,c=!0){return r.isSolanaLike(m.validateAndGetChainId([e]))?B.hinkalSolanaDepositAndWithdraw(this,e,t,n,i,a,o,s):w.hinkalDepositAndWithdraw(this,e,t,n,i,a,o,s,c)}async claimUtxo(e,t,n,i){return r.isSolanaLike(m.validateAndGetChainId([e]))?Z.hinkalSolanaClaimUtxo(this,e,t,n,i):Y.hinkalClaimUtxo(this,e,t,n,i)}async depositAndBridge(e,t,n,r,i,a,o=!0){return J.hinkalDepositAndBridge(this,e,t,n,r,i,a,o)}async prooflessDeposit(e,t,n,i){return r.isSolanaLike(m.validateAndGetChainId(e))?X.hinkalSolanaProoflessDeposit(this,e,t,n,i):P.hinkalProoflessDeposit(this,e,t,n,i)}getSolanaProgram(e){if(!this.solanaProviderAdapter)throw Error(`No provider adapter initialized`);if(!(`getSolanaProgram`in this.solanaProviderAdapter))throw Error(`Current provider adapter is not a Solana provider adapter`);return this.solanaProviderAdapter.getSolanaProgram(e)}getSolanaPublicKey(){if(!this.solanaProviderAdapter)throw Error(`No provider adapter initialized`);if(!(`getSolanaPublicKey`in this.solanaProviderAdapter))throw Error(`Current provider adapter is not a Solana provider adapter`);return this.solanaProviderAdapter.getSolanaPublicKey()}async transfer(e,t,n,i,a,o){return r.isSolanaLike(m.validateAndGetChainId(e))?H.hinkalSolanaTransfer(this,e,t,n,i,a,o):L.hinkalTransfer(this,e,t,n,i,a,o)}async withdraw(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?V.hinkalSolanaWithdraw(this,e,t,n,a,o,s):D.hinkalWithdraw(this,e,t,n,i,a,o,s)}async withdrawStuckUtxos(e,t){return re.hinkalWithdrawStuckUtxos(this,e,t)}async swap(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?this.swapSolana(e,t,i,a,o):E.hinkalSwap(this,e,t,n,i,a,o,s)}async swapSolana(e,t,n,r,i){let a=JSON.parse(n),o=BigInt(a.swapperAccountSalt),{instructionLists:s,addressLookupTableAccount:c}=a.data;return U.hinkalSolanaSwap(this,e,t,o,s,c,r,i)}async actionReceive(e,t,n,i,a,o){if(!a)throw Error(`subAccount is required`);return r.isSolanaLike(m.validateAndGetChainId(e))?K.hinkalSolanaProxyShield(this,e[0],t[0],a,void 0,o):N.hinkalActionReceive(this,e,t,n,i,a,o)}async actionPrivateWallet(e,t,n,r,i,a,o,s,c,l,u=!1,d,f,p){return this.enforceRateLimit(this.actionPrivateWallet.name,[e,t,n,r,i,a,o,s,c,p]),A.hinkalPrivateWallet(this,e,t,n,r,i,a,o,s,c,l,u,d,f,p)}async proxySwap(e,t,n,i,a,o,s,c,l=!1,u,d){return r.isSolanaLike(m.validateAndGetChainId(e))?G.hinkalSolanaProxySwap(this,e,t,i,o,s,c):F.hinkalProxySwap(this,e,t,n,i,a,o,s,c,l,u,d)}async proxyToPrivate(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?(this.enforceRateLimit(this.proxyToPrivate.name,[e[0],t[0],n,i]),K.hinkalSolanaProxyShield(this,e[0],t[0],n,i,s)):R.hinkalProxyToPrivate(this,e,t,i,a,o,n,s)}async proxySend(e,t,n,i,a,o,s){let c=m.validateAndGetChainId(e);if(r.isSolanaLike(c))return W.hinkalSolanaProxySend(this,e[0],t[0],n,i,s);let l=te.createTransaferEmporiumOpsBatch(this,c,e.map(e=>e.erc20TokenAddress),t,i),u=e.map((e,n)=>({token:e,amount:-1n*t[n]}));return await this.actionPrivateWallet(c,[],[],[],l,u,n,a,o,void 0,void 0,void 0,s,void 0)}async multiSendPrivateRecipients(e,t,n){return this.enforceRateLimit(this.multiSendPrivateRecipients.name,[e,t,n]),I.hinkalMultiSendPrivateRecipients(this,e,t,n)}areMerkleTreeUpdatesDisabled(){return this.disableMerkleTreeUpdates}updateMerkleTreeUpdates(e){this.disableMerkleTreeUpdates=e}};exports.Hinkal=ie;
1
+ require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../types/ethereum-network.types.cjs`),t=require(`../../functions/utils/serialize.utils.cjs`),n=require(`../../constants/vite.constants.cjs`),r=require(`../../constants/chains.constants.cjs`),i=require(`../../types/hinkal.types.cjs`),a=require(`../../API/API.cjs`),o=require(`../../constants/kyc.constants.cjs`),s=require(`../../error-handling/error-codes.constants.cjs`),c=require(`../../functions/utils/erc20tokenFunctions.cjs`);require(`../../API/index.cjs`);const l=require(`../../crypto/poseidon.cjs`),u=require(`../crypto-keys/keys.cjs`),d=require(`../../functions/pre-transaction/solana.cjs`),f=require(`./hinkalCheckSolanaTokenRegistry.cjs`),p=require(`../../functions/web3/functionCalls/accessTokenCalls.cjs`),m=require(`../../functions/utils/token-check.utils.cjs`),h=require(`../TokenDBs/PrivateTokensDB.cjs`),g=require(`../../functions/web3/events/getShieldedBalance.cjs`),ee=require(`../../functions/utils/reloadPage.cjs`),_=require(`../../functions/utils/cacheDevice.utils.cjs`),v=require(`../../functions/web3/getContractMetadata.cjs`),y=require(`../../providers/SolanaProviderAdapter.cjs`),b=require(`./hinkalCheckTokenRegistry.cjs`),x=require(`../merkle-tree/MerkleTree.cjs`);require(`../merkle-tree/index.cjs`);const S=require(`./hinkalDeposit.cjs`),te=require(`../../functions/private-wallet/emporium.helpers.cjs`),C=require(`../../functions/web3/events/getApprovedBalance.cjs`),ne=require(`../../functions/kyc/checkTokenLimitsUSD.cjs`),w=require(`./hinkalDepositAndWithdraw.cjs`),T=require(`./hinkalSolanaDeposit.cjs`),E=require(`./hinkalSwap.cjs`),D=require(`./hinkalWithdraw.cjs`),O=require(`./resetMerkleTrees.cjs`),k=require(`../MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.cjs`),A=require(`./hinkalPrivateWallet.cjs`),j=require(`./hinkalGetRecipientInfo.cjs`),M=require(`./hinkalSignSubAccount.cjs`),N=require(`./hinkalActionReceive.cjs`);require(`../TokenDBs/index.cjs`);const P=require(`./hinkalProoflessDeposit.cjs`),F=require(`./hinkalProxySwap.cjs`),I=require(`./hinkalMultiSend.cjs`),L=require(`./hinkalTransfer.cjs`),R=require(`./hinkalProxyToPrivate.cjs`),z=require(`../../providers/TronProviderAdapter.cjs`),B=require(`./hinkalSolanaDepositAndWithdraw.cjs`),V=require(`./hinkalSolanaWithdraw.cjs`),H=require(`./hinkalSolanaTransfer.cjs`),U=require(`./hinkalSolanaSwap.cjs`),W=require(`./hinkalSolanaProxySend.cjs`),G=require(`./hinkalSolanaProxySwap.cjs`),K=require(`./hinkalSolanaProxyShield.cjs`),q=require(`../../functions/web3/fetchSolanaMerkleTreeRootHash.cjs`),J=require(`./hinkalDepositAndBridge.cjs`),Y=require(`./hinkalClaimUtxo.cjs`),X=require(`./hinkalSolanaProoflessDeposit.cjs`),Z=require(`./hinkalSolanaClaimUtxo.cjs`),re=require(`./hinkalWithdrawStuckUtxos.cjs`);let Q=require(`ethers`),$=require(`@solana/web3.js`);var ie=class{ethereumProviderAdapter;solanaProviderAdapter;tronProviderAdapter;userKeys;signingMessage=`Login to Hinkal Protocol`;privateTransferSigningMessage=`Login to Hinkal's Private Transfer App`;merkleTreeHinkalByChain={};merkleTreeAccessTokenByChain={};nullifiersByChain={};encryptedOutputsByChain={};approvalsByChain={};commitmentsSnapshotServiceByChain={};nullifierSnapshotServiceByChain={};accessTokenSnapshotServiceByChain={};approvalsSnapshotServiceByChain={};utxoUtils;lastCallState=new Map;cacheDevice;generateProofRemotely;disableMerkleTreeUpdates;constructor(e){this.userKeys=new u.UserKeys(void 0),r.HINKAL_SUPPORTED_CHAINS.forEach(e=>{this.merkleTreeHinkalByChain[e]=x.MerkleTree.create(l.poseidonFunction,0n),this.merkleTreeAccessTokenByChain[e]=x.MerkleTree.create(l.poseidonFunction,0n),this.nullifiersByChain[e]=new Set,this.encryptedOutputsByChain[e]=[],this.approvalsByChain[e]=new Map}),this.generateProofRemotely=e?.generateProofRemotely??!0,this.utxoUtils=new k.MultiThreadedUtxoUtils,this.cacheDevice=_.createCacheDevice(e),this.disableMerkleTreeUpdates=e?.disableMerkleTreeUpdates??!1}enforceRateLimit(e,n,r=1e3){let i=Date.now(),a=t.CustomJSONStringify(n),o=this.lastCallState.get(e);if(o&&o.argsKey===a&&i-o.timestamp<r)throw Error(`${e} was already called with the same arguments`);this.lastCallState.set(e,{timestamp:i,argsKey:a})}getProviderAdapter(e){let t=e;t||=this.ethereumProviderAdapter?r.chainIds.ethMainnet:this.solanaProviderAdapter?r.chainIds.solanaMainnet:r.chainIds.tronMainnet;let n;if(n=r.isSolanaLike(t)?this.solanaProviderAdapter:r.isTronLike(t)?this.tronProviderAdapter:this.ethereumProviderAdapter,!n)throw Error(`ProviderAdapter is not initialized`);return n}async initProviderAdapter(e,t){let n=r.chainIds.ethMainnet;t instanceof y.SolanaProviderAdapter?n=r.chainIds.solanaMainnet:t instanceof z.TronProviderAdapter&&(n=r.currentTronChainId),await this.updateProviderAdapter(n,t),t.initConnector(e);let i=await t.connectAndPatchProvider(e);await t.init(i),await this.setListeners()}getSigningMessage(e=i.LoginMessageMode.PROTOCOL){switch(e){case i.LoginMessageMode.PRIVATE_TRANSFER:return this.privateTransferSigningMessage;case i.LoginMessageMode.PROTOCOL:default:return this.signingMessage}}async initUserKeys(e=i.LoginMessageMode.PROTOCOL){let t=this.getSigningMessage(e);this.userKeys=new u.UserKeys(await this.getProviderAdapter().signMessage(t))}initUserKeysWithSignature(e){this.userKeys=new u.UserKeys(e)}async initUserKeysFromSeedPhrases(e){let t=e.join(` `),n=Q.ethers.toUtf8Bytes(t);this.userKeys=new u.UserKeys(Q.ethers.keccak256(n))}async resetMerkle(e){this.disableMerkleTreeUpdates||(e?.every(e=>this.isSelectedNetworkSupported(e))??!0)&&await O.resetMerkleTrees(this,e)}getTronWeb(){let e=this.tronProviderAdapter;if(!e)throw Error(`Tron provider adapter not initialized`);if(!(e instanceof z.TronProviderAdapter))throw Error(`Tron provider adapter is not a TronProviderAdapter`);let t=e.getTronWeb();if(!t)throw Error(`TronWeb not available`);return t}getSupportedChains(){return this.ethereumProviderAdapter&&this.solanaProviderAdapter?r.WALLET_SUPPORTED_CHAINS:this.ethereumProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>!r.isSolanaLike(e)&&!r.isTronLike(e)):this.solanaProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>r.isSolanaLike(e)):this.tronProviderAdapter?r.HINKAL_SUPPORTED_CHAINS.filter(e=>r.isTronLike(e)):[]}async waitForTransaction(e,t,n=1){return!!await this.getProviderAdapter(e).waitForTransaction(e,t,n)}getContract(e,t,n=void 0){return this.getProviderAdapter(e).getContract(e,t,n)}getContractWithFetcherByChainId(e,t,n=void 0){return v.getContractWithFetcherByChainId(e,t,n)}async signMessage(e){return await this.getProviderAdapter().signMessage(e)}async signTypedData(e,t,n){return await this.getProviderAdapter().signTypedData(e,t,n)}async signWithSubAccount(e,t,n,r){return M.hinkalSignSubAccount(e,t,n,r)}getContractWithSigner(e,t,n=``){return this.getProviderAdapter(e).getContractWithSigner(e,t,n)}getContractWithFetcher(e,t,n=``){return this.getProviderAdapter(e).getContractWithFetcher(e,t,n)}isSelectedNetworkSupported(e){return!!r.networkRegistry[e]}async switchNetwork(e){try{await this.getProviderAdapter().switchNetwork(e)}catch{throw Error(s.transactionErrorCodes.FAILED_TO_SWITCH_NETWORKS)}}isPermitterAvailable(e){return this.getProviderAdapter(e).isPermitterAvailable()}async disconnectFromConnector(){await this.ethereumProviderAdapter?.disconnectFromConnector(),await this.solanaProviderAdapter?.disconnectFromConnector(),await this.tronProviderAdapter?.disconnectFromConnector()}async resetProviderAdapters(){this.ethereumProviderAdapter=void 0,this.solanaProviderAdapter=void 0,this.tronProviderAdapter=void 0}async updateProviderAdapter(e,t){try{r.isSolanaLike(e)?(this.solanaProviderAdapter&&this.solanaProviderAdapter.release(),this.solanaProviderAdapter=t):r.isTronLike(e)?(this.tronProviderAdapter&&this.tronProviderAdapter.release(),this.tronProviderAdapter=t):(this.ethereumProviderAdapter&&this.ethereumProviderAdapter.release(),this.ethereumProviderAdapter=t)}catch(e){throw console.error(e),Error(`updateProviderAdapter failed, please try again.`)}}async setListeners(){this.ethereumProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}}),this.solanaProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}}),this.tronProviderAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}})}async onAccountChanged(){await this.ethereumProviderAdapter?.onAccountChanged(),await this.solanaProviderAdapter?.onAccountChanged(),await this.tronProviderAdapter?.onAccountChanged();let e=i.EventType.AccountChanged;typeof document<`u`?document?.dispatchEvent(new Event(e)):process?.emit(`message`,e,void 0)}async onChainChanged(e){e?await this.getProviderAdapter(e).onChainChanged(e):(await this.disconnectFromConnector(),ee.reloadPage())}async monitorConnectedAddress(e){await a.API.monitor(await this.getEthereumAddressByChain(e))}async getBalances(e,t,n,r,i=!1,a,o=!1){return g.getShieldedBalance(this,e,t,n,r,i,this.generateProofRemotely,a,o)}async getApprovedBalances(e,t=!1,n=!1){return C.getApprovedBalance(this,e,t,n)}async getTotalBalance(e,t,i,a=!1,o,s=!1){let l=i??await this.getEthereumAddressByChain(e),u=t??this.userKeys,d=await this.getBalances(e,u.getShieldedPrivateKey(),u.getShieldedPublicKey(),l,a,o,s),f=!r.isSolanaLike(e)&&!s?await this.getApprovedBalances(e,a,o):new Map,p=n.isExtension?await h.privateTokensDB.getPrivateTokens(e,l):c.getErc20TokensForChain(e),m=[];return p.forEach(e=>{let t=e.erc20TokenAddress.toLowerCase(),n=d.get(t),r=f.get(t),i={token:e,balance:(n?.balance??0n)+(r?.balance??0n),timestamp:n?.timestamp||r?.timestamp||`0`,nfts:n?.nfts||[]};m.push(i)}),m}async getStuckShieldedBalances(e,t,n){return(await this.getTotalBalance(e,t,n,!1,!1,!0)).filter(e=>e.balance>0n)}getSupportedPassportLinks(){return o.supportedPassportLinks}checkAccessToken(e,t){return p.checkHinkalAccessToken(this,e,t)}checkExternalTokenLimitsUSD(e,t,n){return ne.checkTokenLimitsUSD(e,t,n)}async getHinkalTreeRootHash(t){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:n,originalDeployer:i}=r.networkRegistry[t].contractData;if(!e||!n||!i)throw Error(`Missing Solana configuration for chain ${t}`);let a=new $.PublicKey(i),o=d.getMerkleAccountPublicKey(new $.PublicKey(n),a);return q.fetchSolanaMerkleTreeRootHash(this.getSolanaProgram(e),o)}return this.getContractWithFetcherByChainId(t,e.ContractType.HinkalContract).getRootHash()}async getAccessTokenTreeRootHash(t){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:n,originalDeployer:i}=r.networkRegistry[t].contractData;if(!e||!n||!i)throw Error(`Missing Solana configuration for chain ${t}`);let a=new $.PublicKey(i),o=d.getAccessTokenMerkleAccountPublicKey(new $.PublicKey(n),a);return q.fetchSolanaMerkleTreeRootHash(this.getSolanaProgram(e),o)}return this.getContractWithFetcherByChainId(t,e.ContractType.AccessTokenContract).getRootHash()}async resetMerkleTreesIfNecessary(e){let t=(await Promise.all((e??this.getSupportedChains()).map(async e=>{let[t,n]=await Promise.all([this.getHinkalTreeRootHash(e),this.getAccessTokenTreeRootHash(e)]);return{chainId:e,needsReset:BigInt(t)!==this.merkleTreeHinkalByChain[e].getRootHash()||BigInt(n)!==this.merkleTreeAccessTokenByChain[e].getRootHash()}}))).filter(e=>e.needsReset).map(e=>e.chainId);t.length>0&&(console.log(`resetting merkle tree in resetMerkleTreesIfNecessary for chains:`,t),await this.resetMerkle(t))}async getEthereumAddress(){let e=this.ethereumProviderAdapter??this.solanaProviderAdapter??this.tronProviderAdapter;if(!e)throw Error(`No provider adapter initialized`);return e.getAddress()}getEthereumAddressByChain(e){return this.getProviderAdapter(e).getAddress()}async getRandomRelay(e,t=!1){return(await a.API.getIdleRelay(e,t)).relay}getGasPrice(e){let t=this.getProviderAdapter(e);if(!t)throw Error(`Illegal State of providerAdapter in Hinkal: no providerAdapter initialized`);return t.getGasPrice(e)}getAPI(){return a.API}snapshotsClearInterval(){this.getSupportedChains().forEach(e=>{this.commitmentsSnapshotServiceByChain[e]?.intervalClear(),this.accessTokenSnapshotServiceByChain[e]?.intervalClear(),this.nullifierSnapshotServiceByChain[e]?.intervalClear(),this.approvalsSnapshotServiceByChain[e]?.intervalClear()})}checkTokenRegistry(t,n,i){if(r.isSolanaLike(t)){let{hinkalIdl:e,hinkalAddress:a,originalDeployer:o}=r.networkRegistry[t].contractData;if(!e||!a||!o)throw Error(`missing solana data`);return f.hinkalCheckSolanaTokenRegistry(this.getSolanaProgram(e),new $.PublicKey(o),n,i)}return r.isTronLike(t)?b.hinkalCheckTronTokenRegistry(n,i,t):b.hinkalCheckTokenRegistry(this.getContractWithFetcher(t,e.ContractType.HinkalHelperContract),n,i)}getRecipientInfo(){return j.getRecipientInfo(this)}getApprovedUtxos(e,t=!1){return C.getApprovedUtxos(this,e,t)}getApprovedUtxosForToken(e,t,n=!1){return C.getApprovedUtxosForToken(this,e,t,n)}async deposit(e,t,n=!0,r=!1){return S.hinkalDeposit(this,e,t,n,r)}async depositSolana(e,t){return T.hinkalSolanaDeposit(this,e,t)}async depositForOther(e,t,n,r=!0,i=!1){return this.enforceRateLimit(this.depositForOther.name,[e,t,n]),S.hinkalDepositForOther(this,e,t,n,r,i)}async depositSolanaForOther(e,t,n){return this.enforceRateLimit(this.depositSolanaForOther.name,[e,t,n]),T.hinkalSolanaDepositForOther(this,e,t,n)}async depositAndWithdraw(e,t,n,i,a,o,s,c=!0){return r.isSolanaLike(m.validateAndGetChainId([e]))?B.hinkalSolanaDepositAndWithdraw(this,e,t,n,i,a,o,s):w.hinkalDepositAndWithdraw(this,e,t,n,i,a,o,s,c)}async claimUtxo(e,t,n,i){return r.isSolanaLike(m.validateAndGetChainId([e]))?Z.hinkalSolanaClaimUtxo(this,e,t,n,i):Y.hinkalClaimUtxo(this,e,t,n,i)}async depositAndBridge(e,t,n,r,i,a,o=!0){return J.hinkalDepositAndBridge(this,e,t,n,r,i,a,o)}async prooflessDeposit(e,t,n,i){return r.isSolanaLike(m.validateAndGetChainId(e))?X.hinkalSolanaProoflessDeposit(this,e,t,n,i):P.hinkalProoflessDeposit(this,e,t,n,i)}getSolanaProgram(e){if(!this.solanaProviderAdapter)throw Error(`No provider adapter initialized`);if(!(`getSolanaProgram`in this.solanaProviderAdapter))throw Error(`Current provider adapter is not a Solana provider adapter`);return this.solanaProviderAdapter.getSolanaProgram(e)}getSolanaPublicKey(){if(!this.solanaProviderAdapter)throw Error(`No provider adapter initialized`);if(!(`getSolanaPublicKey`in this.solanaProviderAdapter))throw Error(`Current provider adapter is not a Solana provider adapter`);return this.solanaProviderAdapter.getSolanaPublicKey()}async transfer(e,t,n,i,a,o){return r.isSolanaLike(m.validateAndGetChainId(e))?H.hinkalSolanaTransfer(this,e,t,n,i,a,o):L.hinkalTransfer(this,e,t,n,i,a,o)}async withdraw(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?V.hinkalSolanaWithdraw(this,e,t,n,a,o,s):D.hinkalWithdraw(this,e,t,n,i,a,o,s)}async withdrawStuckUtxos(e,t){return re.hinkalWithdrawStuckUtxos(this,e,t)}async swap(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?this.swapSolana(e,t,i,a,o):E.hinkalSwap(this,e,t,n,i,a,o,s)}async swapSolana(e,t,n,r,i){let a=JSON.parse(n),o=BigInt(a.swapperAccountSalt),{instructionLists:s,addressLookupTableAccount:c}=a.data;return U.hinkalSolanaSwap(this,e,t,o,s,c,r,i)}async actionReceive(e,t,n,i,a,o){if(!a)throw Error(`subAccount is required`);return r.isSolanaLike(m.validateAndGetChainId(e))?K.hinkalSolanaProxyShield(this,e[0],t[0],a,void 0,o):N.hinkalActionReceive(this,e,t,n,i,a,o)}async actionPrivateWallet(e,t,n,r,i,a,o,s,c,l,u=!1,d,f,p){return this.enforceRateLimit(this.actionPrivateWallet.name,[e,t,n,r,i,a,o,s,c,p]),A.hinkalPrivateWallet(this,e,t,n,r,i,a,o,s,c,l,u,d,f,p)}async proxySwap(e,t,n,i,a,o,s,c,l=!1,u,d){return r.isSolanaLike(m.validateAndGetChainId(e))?G.hinkalSolanaProxySwap(this,e,t,i,o,s,c):F.hinkalProxySwap(this,e,t,n,i,a,o,s,c,l,u,d)}async proxyToPrivate(e,t,n,i,a,o,s){return r.isSolanaLike(m.validateAndGetChainId(e))?(this.enforceRateLimit(this.proxyToPrivate.name,[e[0],t[0],n,i]),K.hinkalSolanaProxyShield(this,e[0],t[0],n,i,s)):R.hinkalProxyToPrivate(this,e,t,i,a,o,n,s)}async proxySend(e,t,n,i,a,o,s){let c=m.validateAndGetChainId(e);if(r.isSolanaLike(c))return W.hinkalSolanaProxySend(this,e[0],t[0],n,i,s);let l=te.createTransaferEmporiumOpsBatch(this,c,e.map(e=>e.erc20TokenAddress),t,i),u=e.map((e,n)=>({token:e,amount:-1n*t[n]}));return await this.actionPrivateWallet(c,[],[],[],l,u,n,a,o,void 0,void 0,void 0,s,void 0)}async multiSendPrivateRecipients(e,t,n){return this.enforceRateLimit(this.multiSendPrivateRecipients.name,[e,t,n]),I.hinkalMultiSendPrivateRecipients(this,e,t,n)}areMerkleTreeUpdatesDisabled(){return this.disableMerkleTreeUpdates}updateMerkleTreeUpdates(e){this.disableMerkleTreeUpdates=e}};exports.Hinkal=ie;
@@ -84,7 +84,7 @@ var _e = class {
84
84
  constructor(e) {
85
85
  this.userKeys = new h(void 0), r.forEach((e) => {
86
86
  this.merkleTreeHinkalByChain[e] = E.create(m, 0n), this.merkleTreeAccessTokenByChain[e] = E.create(m, 0n), this.nullifiersByChain[e] = /* @__PURE__ */ new Set(), this.encryptedOutputsByChain[e] = [], this.approvalsByChain[e] = /* @__PURE__ */ new Map();
87
- }), this.generateProofRemotely = e?.generateProofRemotely ?? !1, this.utxoUtils = new B(), this.cacheDevice = x(e), this.disableMerkleTreeUpdates = e?.disableMerkleTreeUpdates ?? !1;
87
+ }), this.generateProofRemotely = e?.generateProofRemotely ?? !0, this.utxoUtils = new B(), this.cacheDevice = x(e), this.disableMerkleTreeUpdates = e?.disableMerkleTreeUpdates ?? !1;
88
88
  }
89
89
  enforceRateLimit(e, n, r = 1e3) {
90
90
  let i = Date.now(), a = t(n), o = this.lastCallState.get(e);
@@ -1 +1 @@
1
- const e=require(`../../types/ethereum-network.types.cjs`),t=require(`../../types/external-action.types.cjs`),n=require(`../../constants/chains.constants.cjs`),r=require(`../../constants/protocol.constants.cjs`),i=require(`../../types/hinkal.types.cjs`);require(`../../types/index.cjs`);const a=require(`../../error-handling/error-codes.constants.cjs`),o=require(`../../functions/utils/time.utils.cjs`),s=require(`../../functions/utils/tron.utils.cjs`),c=require(`../../functions/utils/token-check.utils.cjs`),l=require(`../../functions/web3/events/getShieldedBalance.cjs`),u=require(`../../functions/pre-transaction/outputUtxoProcessing.cjs`),d=require(`../../functions/utils/fees.utils.cjs`),f=require(`../../functions/pre-transaction/outputApprovalDataProcessing.cjs`),p=require(`../../functions/pre-transaction/getVolatileTransferAmount.cjs`),m=require(`../../functions/pre-transaction/constructAdminData.cjs`),h=require(`../../functions/pre-transaction/getFeeStructure.cjs`),g=require(`../../functions/pre-transaction/getKycAndSignatureData.cjs`);require(`../../functions/pre-transaction/index.cjs`);const _=require(`../../functions/snarkjs/constructGeneralZkProof.cjs`),v=require(`../../functions/web3/functionCalls/transactCallDirect.cjs`),y=require(`../../functions/web3/functionCalls/transactCallRelayer.cjs`),b=require(`../../functions/pre-transaction/merge-with-fee-structure.cjs`);var x=async(e,t,n,r)=>{console.log(`hinkalWithdraw 0 deltaAmounts`,{deltaAmounts:r,erc20Addresses:n});let a=[...await l.addPaddingToUtxos(e,t,n,r)];console.log(`hinkalWithdraw 1 inputUtxosArray`,a);let s=[],c=i.defaultHinkalLogicArgs(r.length,e.userKeys),d=o.getCurrentTimeInSeconds().toString();for(let i=0;i<n.length;i+=1){let{outputUtxos:n}=u.outputUtxoProcessing(e.userKeys,a[i],r[i],d,void 0,!1);s.push(n),console.log(`hinkalWithdraw 2 outputUtxosArray`,s);let{useApprovalUtxoData:o}=f.outputApprovalDataProcessing(e,t,a[i],r[i]);o&&(c.useApprovalUtxoData[i]=o,c.doPreTxApproval=!0)}return{inputUtxosArray:a,outputUtxosArray:s,hinkalLogicArgs:c}},S=async(i,o,l,u,f,S,C,w)=>{let T=c.validateAndGetChainId(o),E=n.isTronLike(T),D=s.addressToHexFormat(await i.getEthereumAddressByChain(T)),O=o.map(e=>e.erc20TokenAddress),k=await p.modifyVolatileTokenAmountChanges(T,o,l),A;if(!f){let e=C??await h.getFeeStructure(T,S,O,t.ExternalActionId.Transact),n=d.calculateTotalFee(-k[0],e);A={feeToken:e.feeToken,flatFee:n,variableRate:0n},b.mergeWithFeeStructure(T,O,k,A)}let j=o[0];if(!j)throw Error(`Deposit Action: No Token Found`);let M={externalActionId:0n,externalAddress:s.addressToHexFormat(u),externalActionMetadata:`0x00`},[N,{patchAccessTokenMerkleTree:P,signatureData:F},{inputUtxosArray:I,outputUtxosArray:L,hinkalLogicArgs:R}]=await Promise.all([i.getRandomRelay(T,!0),g.getKycAndSignatureData(i,T,O,k,D),x(i,T,O,k)]);if(!f&&!N)throw Error(a.transactionErrorCodes.RELAYER_NOT_AVAILABLE);let z=`swapperM${k.length.toString()}x${I[0].length}x1`,{zkCallData:B,circomData:V,dimData:H}=await _.constructZkProof(i.merkleTreeHinkalByChain[T],i.merkleTreeAccessTokenByChain[T],I,L,i.userKeys,z,M.externalActionId,M.externalAddress,M.externalActionMetadata,i.generateProofRemotely,f?r.zeroAddress:N,T,void 0,void 0,void 0,P,R,void 0,A,i.getContractWithFetcher(T,e.ContractType.HinkalHelperContract),F,f?D:void 0),U=await s.reorderZkCallData(E,B,H,V);if(f){if(!j)throw Error(`Withdraw Action: No Token Found`);return await v.transactCallDirect(i,T,k[0],j,B,V,H)}return await y.transactCallRelayer(T,B,H,V,void 0,void 0,m.constructAdminData(w,T,O,k,D),U)};exports.hinkalWithdraw=S;
1
+ const e=require(`../../types/ethereum-network.types.cjs`),t=require(`../../types/external-action.types.cjs`),n=require(`../../constants/chains.constants.cjs`),r=require(`../../constants/protocol.constants.cjs`),i=require(`../../types/hinkal.types.cjs`);require(`../../types/index.cjs`);const a=require(`../../error-handling/error-codes.constants.cjs`),o=require(`../../functions/utils/time.utils.cjs`),s=require(`../../functions/utils/tron.utils.cjs`),c=require(`../../functions/utils/token-check.utils.cjs`),l=require(`../../functions/web3/events/getShieldedBalance.cjs`),u=require(`../../functions/pre-transaction/outputUtxoProcessing.cjs`),d=require(`../../functions/utils/fees.utils.cjs`),f=require(`../../functions/pre-transaction/outputApprovalDataProcessing.cjs`),p=require(`../../functions/pre-transaction/getVolatileTransferAmount.cjs`),m=require(`../../functions/pre-transaction/constructAdminData.cjs`),h=require(`../../functions/pre-transaction/getFeeStructure.cjs`),g=require(`../../functions/pre-transaction/getKycAndSignatureData.cjs`);require(`../../functions/pre-transaction/index.cjs`);const _=require(`../../functions/snarkjs/constructGeneralZkProof.cjs`),v=require(`../../functions/web3/functionCalls/transactCallDirect.cjs`),y=require(`../../functions/web3/functionCalls/transactCallRelayer.cjs`),b=require(`../../functions/pre-transaction/merge-with-fee-structure.cjs`);var x=async(e,t,n,r)=>{let a=[...await l.addPaddingToUtxos(e,t,n,r)],s=[],c=i.defaultHinkalLogicArgs(r.length,e.userKeys),d=o.getCurrentTimeInSeconds().toString();for(let i=0;i<n.length;i+=1){let{outputUtxos:n}=u.outputUtxoProcessing(e.userKeys,a[i],r[i],d,void 0,!1);s.push(n);let{useApprovalUtxoData:o}=f.outputApprovalDataProcessing(e,t,a[i],r[i]);o&&(c.useApprovalUtxoData[i]=o,c.doPreTxApproval=!0)}return{inputUtxosArray:a,outputUtxosArray:s,hinkalLogicArgs:c}},S=async(i,o,l,u,f,S,C,w)=>{let T=c.validateAndGetChainId(o),E=n.isTronLike(T),D=s.addressToHexFormat(await i.getEthereumAddressByChain(T)),O=o.map(e=>e.erc20TokenAddress),k=await p.modifyVolatileTokenAmountChanges(T,o,l),A;if(!f){let e=C??await h.getFeeStructure(T,S,O,t.ExternalActionId.Transact),n=d.calculateTotalFee(-k[0],e);A={feeToken:e.feeToken,flatFee:n,variableRate:0n},b.mergeWithFeeStructure(T,O,k,A)}let j=o[0];if(!j)throw Error(`Deposit Action: No Token Found`);let M={externalActionId:0n,externalAddress:s.addressToHexFormat(u),externalActionMetadata:`0x00`},[N,{patchAccessTokenMerkleTree:P,signatureData:F},{inputUtxosArray:I,outputUtxosArray:L,hinkalLogicArgs:R}]=await Promise.all([i.getRandomRelay(T,!0),g.getKycAndSignatureData(i,T,O,k,D),x(i,T,O,k)]);if(!f&&!N)throw Error(a.transactionErrorCodes.RELAYER_NOT_AVAILABLE);let z=`swapperM${k.length.toString()}x${I[0].length}x1`,{zkCallData:B,circomData:V,dimData:H}=await _.constructZkProof(i.merkleTreeHinkalByChain[T],i.merkleTreeAccessTokenByChain[T],I,L,i.userKeys,z,M.externalActionId,M.externalAddress,M.externalActionMetadata,i.generateProofRemotely,f?r.zeroAddress:N,T,void 0,void 0,void 0,P,R,void 0,A,i.getContractWithFetcher(T,e.ContractType.HinkalHelperContract),F,f?D:void 0),U=await s.reorderZkCallData(E,B,H,V);if(f){if(!j)throw Error(`Withdraw Action: No Token Found`);return await v.transactCallDirect(i,T,k[0],j,B,V,H)}return await y.transactCallRelayer(T,B,H,V,void 0,void 0,m.constructAdminData(w,T,O,k,D),U)};exports.hinkalWithdraw=S;
@@ -23,16 +23,10 @@ import { transactCallRelayer as b } from "../../functions/web3/functionCalls/tra
23
23
  import { mergeWithFeeStructure as x } from "../../functions/pre-transaction/merge-with-fee-structure.mjs";
24
24
  //#region libs/shared/common/src/data-structures/Hinkal/hinkalWithdraw.ts
25
25
  var S = async (e, t, n, r) => {
26
- console.log("hinkalWithdraw 0 deltaAmounts", {
27
- deltaAmounts: r,
28
- erc20Addresses: n
29
- });
30
- let a = [...await u(e, t, n, r)];
31
- console.log("hinkalWithdraw 1 inputUtxosArray", a);
32
- let s = [], c = i(r.length, e.userKeys), l = o().toString();
26
+ let a = [...await u(e, t, n, r)], s = [], c = i(r.length, e.userKeys), l = o().toString();
33
27
  for (let i = 0; i < n.length; i += 1) {
34
28
  let { outputUtxos: n } = d(e.userKeys, a[i], r[i], l, void 0, !1);
35
- s.push(n), console.log("hinkalWithdraw 2 outputUtxosArray", s);
29
+ s.push(n);
36
30
  let { useApprovalUtxoData: o } = p(e, t, a[i], r[i]);
37
31
  o && (c.useApprovalUtxoData[i] = o, c.doPreTxApproval = !0);
38
32
  }
@@ -1 +1 @@
1
- const e=require(`../../../functions/utils/resolve-sync.utils.cjs`);var t=class{blockchainEventEmitter;eventName;constructor(e,t){this.blockchainEventEmitter=e,this.eventName=t,e.addEventProcessorFunction(this.processEventsPage.bind(this))}get latestBlockNumber(){return this.blockchainEventEmitter.latestBlockNumber}get chainId(){return this.blockchainEventEmitter.chainId}intervalClear(){this.blockchainEventEmitter.intervalClear()}async processEventsPage(t){let n=new Set;t.forEach(({eventName:e,transactionHash:t})=>{e===`BlockedUtxosCreated`&&n.add(t)});let r=[];await e.resolveSync(t.map(e=>async()=>{if(e.eventName!==this.eventName)return;let{blockNumber:t,transactionHash:i}=e,a=this.mapEvent(e),o=n.has(i);await this.acceptEvent(a,t,i,o)&&r.push(a),console.log(`NEW EVENT`,{event:e})}));let i=r.length;return await this.afterEventsAccepted(i),r.length}};exports.AbstractEventService=t;
1
+ const e=require(`../../../functions/utils/resolve-sync.utils.cjs`);var t=class{blockchainEventEmitter;eventName;constructor(e,t){this.blockchainEventEmitter=e,this.eventName=t,e.addEventProcessorFunction(this.processEventsPage.bind(this))}get latestBlockNumber(){return this.blockchainEventEmitter.latestBlockNumber}get chainId(){return this.blockchainEventEmitter.chainId}intervalClear(){this.blockchainEventEmitter.intervalClear()}async processEventsPage(t){let n=new Set;t.forEach(({eventName:e,transactionHash:t})=>{e===`BlockedUtxosCreated`&&n.add(t)});let r=[];await e.resolveSync(t.map(e=>async()=>{if(e.eventName!==this.eventName)return;let{blockNumber:t,transactionHash:i}=e,a=this.mapEvent(e),o=n.has(i);await this.acceptEvent(a,t,i,o)&&r.push(a)}));let i=r.length;return await this.afterEventsAccepted(i),r.length}};exports.AbstractEventService=t;
@@ -24,7 +24,7 @@ var t = class {
24
24
  await e(t.map((e) => async () => {
25
25
  if (e.eventName !== this.eventName) return;
26
26
  let { blockNumber: t, transactionHash: i } = e, a = this.mapEvent(e), o = n.has(i);
27
- await this.acceptEvent(a, t, i, o) && r.push(a), console.log("NEW EVENT", { event: e });
27
+ await this.acceptEvent(a, t, i, o) && r.push(a);
28
28
  }));
29
29
  let i = r.length;
30
30
  return await this.afterEventsAccepted(i), r.length;
@@ -1 +1 @@
1
- const e=require(`../error-codes.constants.cjs`),t=require(`../../functions/web3/etherFunctions.cjs`),n=require(`../../functions/utils/amounts.utils.cjs`),r=require(`./FeeOverTransactionValueError.cjs`),i=require(`../types.cjs`);var a=(e,r)=>{let{totalFeeWEI:a,feeUnit:o}=e.data;if(!o)return e.message;let s=t.getAmountInToken(o,a),c=`transact`,l=`an equivalent of `;return r===i.ErrorCategory.WITHDRAW&&(c=`withdraw`,l=``),`Fees are over transaction value. Please ${c} at least ${l} ${n.fixDecimalsAmount(Number(s))} of ${o?.symbol} (subject to real-time price)`},o=(t,n)=>{throw t instanceof r.FeeOverTransactionValueError||t?.message===e.transactionErrorCodes.INSUFFICIENT_FUNDS_TO_TRANSACT?(console.log(`rethrowKnownGasErrorIfPossible 1`,t),t):Error(n)};exports.getGenericFeeOverTransactionValueErrorMessage=a,exports.rethrowKnownGasErrorIfPossible=o;
1
+ const e=require(`../error-codes.constants.cjs`),t=require(`../../functions/web3/etherFunctions.cjs`),n=require(`../../functions/utils/amounts.utils.cjs`),r=require(`./FeeOverTransactionValueError.cjs`),i=require(`../types.cjs`);var a=(e,r)=>{let{totalFeeWEI:a,feeUnit:o}=e.data;if(!o)return e.message;let s=t.getAmountInToken(o,a),c=`transact`,l=`an equivalent of `;return r===i.ErrorCategory.WITHDRAW&&(c=`withdraw`,l=``),`Fees are over transaction value. Please ${c} at least ${l} ${n.fixDecimalsAmount(Number(s))} of ${o?.symbol} (subject to real-time price)`},o=(t,n)=>{throw t instanceof r.FeeOverTransactionValueError||t?.message===e.transactionErrorCodes.INSUFFICIENT_FUNDS_TO_TRANSACT?t:Error(n)};exports.getGenericFeeOverTransactionValueErrorMessage=a,exports.rethrowKnownGasErrorIfPossible=o;
@@ -10,7 +10,7 @@ var a = (e, r) => {
10
10
  let s = t(o, a), c = "transact", l = "an equivalent of ";
11
11
  return r === i.WITHDRAW && (c = "withdraw", l = ""), `Fees are over transaction value. Please ${c} at least ${l} ${n(Number(s))} of ${o?.symbol} (subject to real-time price)`;
12
12
  }, o = (t, n) => {
13
- throw t instanceof r || t?.message === e.INSUFFICIENT_FUNDS_TO_TRANSACT ? (console.log("rethrowKnownGasErrorIfPossible 1", t), t) : Error(n);
13
+ throw t instanceof r || t?.message === e.INSUFFICIENT_FUNDS_TO_TRANSACT ? t : Error(n);
14
14
  };
15
15
  //#endregion
16
16
  export { a as getGenericFeeOverTransactionValueErrorMessage, o as rethrowKnownGasErrorIfPossible };
@@ -1 +1 @@
1
- const e=require(`../types/transaction.types.cjs`);require(`../types/index.cjs`);const t=require(`./error-codes.constants.cjs`),n=require(`./customErrors/ErrorWithAmount.cjs`),r=require(`./customErrors/FeeOverTransactionValueError.cjs`),i=require(`./types.cjs`),a=require(`./customErrors/customErrors.helpers.cjs`);require(`./customErrors/index.cjs`);const o=require(`./isInsufficientFundsError.cjs`);var s=e=>{if(typeof e==`object`&&e){if(`response`in e&&typeof e.response==`object`&&e.response!==null&&`data`in e.response&&typeof e.response.data==`object`&&e.response.data!==null&&`message`in e.response.data&&typeof e.response.data.message==`string`)return e.response.data.message;if(`data`in e&&typeof e.data==`object`&&e.data!==null&&`message`in e.data&&typeof e.data.message==`string`)return e.data.message;if(`message`in e&&typeof e.message==`string`)return e.message}if(e instanceof Error)return e.message;if(typeof e==`string`)return e},c=e=>{switch(e){case i.ErrorCategory.DEPOSIT:return`Deposit failed`;case i.ErrorCategory.SWAP:return`Swap failed`;case i.ErrorCategory.BRIDGE:return`Bridge failed`;case i.ErrorCategory.WITHDRAW:return`Send failed`;case i.ErrorCategory.Fund:return`Unshield failed`;case i.ErrorCategory.Receive:return`Shield failed`;case i.ErrorCategory.DappTransaction:return`DApp transaction failed`;case i.ErrorCategory.Approve:return`Approval failed`;default:return t.transactionErrorCodes.UNKNOWN}},l=(e,i)=>{if(e instanceof r.FeeOverTransactionValueError)return a.getGenericFeeOverTransactionValueErrorMessage(e,i);if(e instanceof n.ErrorWithAmount){let{amount:t,message:n}=e;return`${n} ${t}`}let l=s(e);if(l&&o.isInsufficientFundsError(l))return console.log(`getErrorMessage 1 insufficient funds`,l),t.insufficientResourcesErrorCodes.INSUFFICIENT_FUNDS;if(l){let e=l.toLowerCase(),n=Object.keys(t.transactionErrorCodes).find(n=>e===t.transactionErrorCodes[n].toLowerCase());if(n&&n in t.UserFriendlyErrorCodes)return t.UserFriendlyErrorCodes[n];let r=Object.entries(t.transactionErrorCodes).find(([t,n])=>e.includes(n.toLowerCase()));if(r)return t.UserFriendlyErrorCodes[r[0]]??r[1];if(Object.values(t.DIRECTLY_SHOW_MESSAGE_ERROR_CODES).find(t=>e.includes(t.toLowerCase())))return l}return i?c(i):t.transactionErrorCodes.UNKNOWN},u=(t,n)=>{let r;switch(n){case e.TransactionRequestType.Send:case e.TransactionRequestType.ProxySend:r=i.ErrorCategory.WITHDRAW;break;case e.TransactionRequestType.SwapTokens:case e.TransactionRequestType.ProxySwapTokens:r=i.ErrorCategory.SWAP;break;case e.TransactionRequestType.ReceiveFromShieldedAccount:r=i.ErrorCategory.Receive;break;case e.TransactionRequestType.Fund:r=i.ErrorCategory.Fund;break;case e.TransactionRequestType.PrivateTransactionFromProxy:r=i.ErrorCategory.DappTransaction;break;default:r=void 0;break}return l(t,r)};exports.extractMessage=s,exports.getErrorMessage=l,exports.getErrorMessageFromTransactionRequest=u;
1
+ const e=require(`../types/transaction.types.cjs`);require(`../types/index.cjs`);const t=require(`./error-codes.constants.cjs`),n=require(`./customErrors/ErrorWithAmount.cjs`),r=require(`./customErrors/FeeOverTransactionValueError.cjs`),i=require(`./types.cjs`),a=require(`./customErrors/customErrors.helpers.cjs`);require(`./customErrors/index.cjs`);const o=require(`./isInsufficientFundsError.cjs`);var s=e=>{if(typeof e==`object`&&e){if(`response`in e&&typeof e.response==`object`&&e.response!==null&&`data`in e.response&&typeof e.response.data==`object`&&e.response.data!==null&&`message`in e.response.data&&typeof e.response.data.message==`string`)return e.response.data.message;if(`data`in e&&typeof e.data==`object`&&e.data!==null&&`message`in e.data&&typeof e.data.message==`string`)return e.data.message;if(`message`in e&&typeof e.message==`string`)return e.message}if(e instanceof Error)return e.message;if(typeof e==`string`)return e},c=e=>{switch(e){case i.ErrorCategory.DEPOSIT:return`Deposit failed`;case i.ErrorCategory.SWAP:return`Swap failed`;case i.ErrorCategory.BRIDGE:return`Bridge failed`;case i.ErrorCategory.WITHDRAW:return`Send failed`;case i.ErrorCategory.Fund:return`Unshield failed`;case i.ErrorCategory.Receive:return`Shield failed`;case i.ErrorCategory.DappTransaction:return`DApp transaction failed`;case i.ErrorCategory.Approve:return`Approval failed`;default:return t.transactionErrorCodes.UNKNOWN}},l=(e,i)=>{if(e instanceof r.FeeOverTransactionValueError)return a.getGenericFeeOverTransactionValueErrorMessage(e,i);if(e instanceof n.ErrorWithAmount){let{amount:t,message:n}=e;return`${n} ${t}`}let l=s(e);if(l&&o.isInsufficientFundsError(l))return t.insufficientResourcesErrorCodes.INSUFFICIENT_FUNDS;if(l){let e=l.toLowerCase(),n=Object.keys(t.transactionErrorCodes).find(n=>e===t.transactionErrorCodes[n].toLowerCase());if(n&&n in t.UserFriendlyErrorCodes)return t.UserFriendlyErrorCodes[n];let r=Object.entries(t.transactionErrorCodes).find(([t,n])=>e.includes(n.toLowerCase()));if(r)return t.UserFriendlyErrorCodes[r[0]]??r[1];if(Object.values(t.DIRECTLY_SHOW_MESSAGE_ERROR_CODES).find(t=>e.includes(t.toLowerCase())))return l}return i?c(i):t.transactionErrorCodes.UNKNOWN},u=(t,n)=>{let r;switch(n){case e.TransactionRequestType.Send:case e.TransactionRequestType.ProxySend:r=i.ErrorCategory.WITHDRAW;break;case e.TransactionRequestType.SwapTokens:case e.TransactionRequestType.ProxySwapTokens:r=i.ErrorCategory.SWAP;break;case e.TransactionRequestType.ReceiveFromShieldedAccount:r=i.ErrorCategory.Receive;break;case e.TransactionRequestType.Fund:r=i.ErrorCategory.Fund;break;case e.TransactionRequestType.PrivateTransactionFromProxy:r=i.ErrorCategory.DappTransaction;break;default:r=void 0;break}return l(t,r)};exports.extractMessage=s,exports.getErrorMessage=l,exports.getErrorMessageFromTransactionRequest=u;
@@ -35,7 +35,7 @@ var u = (e) => {
35
35
  return `${n} ${t}`;
36
36
  }
37
37
  let f = u(e);
38
- if (f && l(f)) return console.log("getErrorMessage 1 insufficient funds", f), r.INSUFFICIENT_FUNDS;
38
+ if (f && l(f)) return r.INSUFFICIENT_FUNDS;
39
39
  if (f) {
40
40
  let e = f.toLowerCase(), r = Object.keys(i).find((t) => e === i[t].toLowerCase());
41
41
  if (r && r in n) return n[r];
@@ -1 +1 @@
1
- require(`../../constants/conversion.constants.cjs`);const e=require(`../../types/hinkal.types.cjs`),t=require(`../utils/caseInsensitive.utils.cjs`),n=require(`../../error-handling/error-codes.constants.cjs`),r=require(`../utils/amounts.utils.cjs`),i=require(`../utils/processUseApprovalUtxoData.cjs`);var a=(a,o,s,c,l,u)=>{if(console.log(`outputApprovalDataProcessing 1`,u),u&&u>0)throw Error(n.transactionErrorCodes.INSUFFICIENT_FUNDS);let d=r.countTotalAmountInUtxos(s),{erc20TokenAddress:f}=s[0],p=a.getApprovedUtxosForToken(f,o).filter(e=>!t.caseInsensitiveEqual(e.interactionAddress,l)),m=e.defaultUseApprovalUTXOData(3,0n);if(c<0n&&d+c<0n){let e=-(d+c);for(let t=0;t<Math.min(p.length,3)&&e!==0n;t+=1){let n=p[t],r=n.amount>=e?-e:-n.amount;e+=r,m.approvalChanges[t]=r,m.externalApprovalAddresses[t]=n.interactionAddress,m.conversionInHinkalAddress[t]=n.inHinkalAddress}if(console.log(`outputApprovalDataProcessing 2`,{neededAmount:e}),e!==0n)throw Error(n.transactionErrorCodes.INSUFFICIENT_FUNDS)}return{useApprovalUtxoData:i.isUseApprovalDataEmpty(m)?void 0:m}};exports.outputApprovalDataProcessing=a;
1
+ require(`../../constants/conversion.constants.cjs`);const e=require(`../../types/hinkal.types.cjs`),t=require(`../utils/caseInsensitive.utils.cjs`),n=require(`../../error-handling/error-codes.constants.cjs`),r=require(`../utils/amounts.utils.cjs`),i=require(`../utils/processUseApprovalUtxoData.cjs`);var a=(a,o,s,c,l,u)=>{if(u&&u>0)throw Error(n.transactionErrorCodes.INSUFFICIENT_FUNDS);let d=r.countTotalAmountInUtxos(s),{erc20TokenAddress:f}=s[0],p=a.getApprovedUtxosForToken(f,o).filter(e=>!t.caseInsensitiveEqual(e.interactionAddress,l)),m=e.defaultUseApprovalUTXOData(3,0n);if(c<0n&&d+c<0n){let e=-(d+c);for(let t=0;t<Math.min(p.length,3)&&e!==0n;t+=1){let n=p[t],r=n.amount>=e?-e:-n.amount;e+=r,m.approvalChanges[t]=r,m.externalApprovalAddresses[t]=n.interactionAddress,m.conversionInHinkalAddress[t]=n.inHinkalAddress}if(e!==0n)throw Error(n.transactionErrorCodes.INSUFFICIENT_FUNDS)}return{useApprovalUtxoData:i.isUseApprovalDataEmpty(m)?void 0:m}};exports.outputApprovalDataProcessing=a;
@@ -6,7 +6,7 @@ import { countTotalAmountInUtxos as r } from "../utils/amounts.utils.mjs";
6
6
  import { isUseApprovalDataEmpty as i } from "../utils/processUseApprovalUtxoData.mjs";
7
7
  //#region libs/shared/common/src/functions/pre-transaction/outputApprovalDataProcessing.ts
8
8
  var a = (a, o, s, c, l, u) => {
9
- if (console.log("outputApprovalDataProcessing 1", u), u && u > 0) throw Error(n.INSUFFICIENT_FUNDS);
9
+ if (u && u > 0) throw Error(n.INSUFFICIENT_FUNDS);
10
10
  let d = r(s), { erc20TokenAddress: f } = s[0], p = a.getApprovedUtxosForToken(f, o).filter((e) => !t(e.interactionAddress, l)), m = e(3, 0n);
11
11
  if (c < 0n && d + c < 0n) {
12
12
  let e = -(d + c);
@@ -14,7 +14,7 @@ var a = (a, o, s, c, l, u) => {
14
14
  let n = p[t], r = n.amount >= e ? -e : -n.amount;
15
15
  e += r, m.approvalChanges[t] = r, m.externalApprovalAddresses[t] = n.interactionAddress, m.conversionInHinkalAddress[t] = n.inHinkalAddress;
16
16
  }
17
- if (console.log("outputApprovalDataProcessing 2", { neededAmount: e }), e !== 0n) throw Error(n.INSUFFICIENT_FUNDS);
17
+ if (e !== 0n) throw Error(n.INSUFFICIENT_FUNDS);
18
18
  }
19
19
  return { useApprovalUtxoData: i(m) ? void 0 : m };
20
20
  };
@@ -1 +1 @@
1
- const e=require(`../../error-handling/error-codes.constants.cjs`),t=require(`../utils/amounts.utils.cjs`),n=require(`../../data-structures/utxo/Utxo.cjs`);var r=(r,i,a,o,s,c=!0,l,u)=>{let d=t.countTotalAmountInUtxos(i),{erc20TokenAddress:f,mintAddress:p}=i[0];if(c&&a<0n&&d+a<0n)throw console.log(`outputUtxoProcessing 1 insufficient funds to transact`,{amountChange:a,totalAmount:d}),Error(e.transactionErrorCodes.INSUFFICIENT_FUNDS_TO_TRANSACT);let m=[new n.Utxo({amount:t.bigintMax(d+a,0n),erc20TokenAddress:f,mintAddress:p,shieldedPrivateKey:r.getShieldedPrivateKey(),timeStamp:o,tokenId:s})];if(l!==void 0&&u!==void 0){let[e,t,r]=l.split(`,`);m.push(new n.Utxo({amount:u,erc20TokenAddress:f,randomization:BigInt(e),stealthAddress:t,encryptionKey:r,timeStamp:o}))}return{outputUtxos:m}};exports.outputUtxoProcessing=r;
1
+ const e=require(`../../error-handling/error-codes.constants.cjs`),t=require(`../utils/amounts.utils.cjs`),n=require(`../../data-structures/utxo/Utxo.cjs`);var r=(r,i,a,o,s,c=!0,l,u)=>{let d=t.countTotalAmountInUtxos(i),{erc20TokenAddress:f,mintAddress:p}=i[0];if(c&&a<0n&&d+a<0n)throw Error(e.transactionErrorCodes.INSUFFICIENT_FUNDS_TO_TRANSACT);let m=[new n.Utxo({amount:t.bigintMax(d+a,0n),erc20TokenAddress:f,mintAddress:p,shieldedPrivateKey:r.getShieldedPrivateKey(),timeStamp:o,tokenId:s})];if(l!==void 0&&u!==void 0){let[e,t,r]=l.split(`,`);m.push(new n.Utxo({amount:u,erc20TokenAddress:f,randomization:BigInt(e),stealthAddress:t,encryptionKey:r,timeStamp:o}))}return{outputUtxos:m}};exports.outputUtxoProcessing=r;
@@ -4,10 +4,7 @@ import { Utxo as r } from "../../data-structures/utxo/Utxo.mjs";
4
4
  //#region libs/shared/common/src/functions/pre-transaction/outputUtxoProcessing.ts
5
5
  var i = (i, a, o, s, c, l = !0, u, d) => {
6
6
  let f = n(a), { erc20TokenAddress: p, mintAddress: m } = a[0];
7
- if (l && o < 0n && f + o < 0n) throw console.log("outputUtxoProcessing 1 insufficient funds to transact", {
8
- amountChange: o,
9
- totalAmount: f
10
- }), Error(e.INSUFFICIENT_FUNDS_TO_TRANSACT);
7
+ if (l && o < 0n && f + o < 0n) throw Error(e.INSUFFICIENT_FUNDS_TO_TRANSACT);
11
8
  let h = [new r({
12
9
  amount: t(f + o, 0n),
13
10
  erc20TokenAddress: p,
@@ -1 +1 @@
1
- require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../constants/chains.constants.cjs`),t=require(`../../utils/caseInsensitive.utils.cjs`),n=require(`../../utils/addresses.cjs`),r=require(`../../../API/scheduled-transactions-calls.cjs`),i=require(`../../../data-structures/utxo/Utxo.cjs`),a=require(`../../utils/upToDateState.cjs`),o=require(`../../utils/cacheFunctions.cjs`),s=require(`../../utils/encodeTokenWithId.cjs`),c=require(`../../utils/solanaMint.utils.cjs`),l=require(`./getInputUtxosEnclave.cjs`),u=require(`../../utils/tron.utils.cjs`);var d=new(require(`async-mutex`)).Mutex,f=async(e,t,n,r,i,s,c,l,u)=>d.runExclusive(async()=>{u+=1;let d=s.slice(u);console.log(`sending list of outputs for batch processing`,{outputsSlice:d,lastOutput:l});let{lastOutput:f,additionalEncryptedOutputs:p}=await e.utxoUtils.batchProcess(d,l,t,n);console.log(`batch process result`,{lastOutputNew:f,additionalEncryptedOutputs:p});let m=[...c,...p];return await a.checkAddressNotUpdated(e,r),o.setHinkalCache({lastOutput:f,encryptedOutputs:m},e,n,i),await e.utxoUtils.buildBatchProcess(m,t,n)}),p=async(e,t,n,r)=>{let{utxos:i,encryptedOutputs:a,lastOutput:s}=await l.getInputUtxosEnclave(e,n,t);return o.setHinkalCache({encryptedOutputs:a,lastOutput:s},e,n,r),i},m=async(e,t,n,r,i,a,o,s,c)=>{try{return await p(e,t,n,i)}catch{return f(e,t,n,r,i,a,o,s,c)}},h=e=>{if(Array.isArray(e))return e;if(e!==void 0)return[e]},g=async(e,t,n)=>await e.utxoUtils.batchFilterUtxosWithNullifier(t,n),_=(e,t,n,r,a,o,s)=>{for(e.sort((e,t)=>e.amount<=t.amount?1:-1);e.length<t||e.length>t&&e.length<6;)if(e.push(new i.Utxo({amount:0n,erc20TokenAddress:a,mintAddress:s,shieldedPrivateKey:r,tokenId:o})),n)for(;e.length>6;)e.splice(e.length-1)},v=async({hinkal:e,chainId:t,passedShieldedPublicKey:n=void 0,ethAddress:r=void 0,resetCacheBefore:i=!1,allowRemoteDecryption:s=!1,useBlockedUtxos:c=!1})=>{let l=r??await e.getEthereumAddress(),u=n??e.userKeys.getShieldedPublicKey();console.log(`getInputUtxoAndBalance 0 start`,{chainId:t,ethereumAddress:l,shieldedPublicKey:u});let{userKeys:d}=e,p=e.encryptedOutputsByChain[t],h=e.nullifiersByChain[t],_=Array.from(p);console.log(`getInputUtxoAndBalance 2 hinkalOutputs`,{hinkalOutputs:_,encryptedOutputs:p,nullifiers:h}),i&&o.resetCache(e,t,u);let{encryptedOutputs:v,lastOutput:y}=o.getHinkalCache(e,t,u);console.log(`getInputUtxoAndBalance 1 cachedEncryptedOutputs`,{cachedEncryptedOutputs:v,lastOutput:y}),await a.checkAddressNotUpdated(e,l);let b=y!==``,x=_.findIndex(e=>e.value===y),S=x>-1,C=!b&&x===-1;console.log(`getInputUtxoAndBalance 3 case1`,S,C,b,x);let w=e.areMerkleTreeUpdatesDisabled(),T=!w&&(S||!s&&C),E=!w&&s&&C,D=!T&&!E;console.log(`getInputUtxoAndBalance 4 forceReadFromCache`,w),console.log(`getInputUtxoAndBalance 5 decryptLocally`,T),console.log(`getInputUtxoAndBalance 6 decryptRemotely`,E),console.log(`getInputUtxoAndBalance 7 useCache`,D);let O=[];T?O=await f(e,d,t,l,u,_,v,y,x):E?O=await m(e,d,t,l,u,_,v,y,x):D&&(O=await e.utxoUtils.buildBatchProcess(v,d,t)),console.log({allUtxos:O}),await a.checkAddressNotUpdated(e,l);let k=await g(e,O,h);console.log(`getInputUtxoAndBalance 8 inputUtxos`,k);let A=c?k.filter(e=>e.isBlocked):k.filter(e=>!e.isBlocked);return console.log(`getInputUtxoAndBalance 9 filteredInputUtxos`,A),{inputUtxos:A}},y=async({hinkal:t,chainId:i,passedShieldedPublicKey:a=void 0,ethAddress:o=void 0,resetCacheBefore:s=!1,allowRemoteDecryption:c=!1})=>{let l=o??await t.getEthereumAddressByChain(i),d=n.hashEthereumAddress(e.isTronLike(i)?u.addressToHexFormat(l):l),{inputUtxos:f}=await v({hinkal:t,chainId:i,passedShieldedPublicKey:a,ethAddress:l,resetCacheBefore:s,allowRemoteDecryption:c,useBlockedUtxos:!0});if(!f.length)return{inputUtxos:[]};let{indexes:p}=await r.getScheduledTransactionsNullifierIndexes({hashedEthereumAddress:d,nullifiers:f.map(e=>e.getNullifier())});return{inputUtxos:p.map(e=>f[e]).filter(e=>!!e)}},b=async({hinkal:n,tokenWithId:r,minInput:i=2,sliceIfMore6:a=!0,chainId:o,passedShieldedPrivateKey:l=void 0,passedShieldedPublicKey:u=void 0,ethAddress:d=void 0,resetCacheBefore:f=!1,ensuredTokensWithId:p,useBlockedUtxos:m=!1})=>{console.log(`getInputUtxoAndBalancePerToken 0 start`,{tokenWithId:r,minInput:i,sliceIfMore6:a,chainId:o,passedShieldedPrivateKey:l,passedShieldedPublicKey:u,ethAddress:d,resetCacheBefore:f,ensuredTokensWithId:p,useBlockedUtxos:m});let g=l??n.userKeys.getShieldedPrivateKey();console.log(`getInputUtxoAndBalancePerToken 1 useBlockedUtxos`,m);let{inputUtxos:b}=m?await y({hinkal:n,chainId:o,ethAddress:d,passedShieldedPrivateKey:l,resetCacheBefore:f}):await v({hinkal:n,tokenWithId:r,minInput:i,sliceIfMore6:a,chainId:o,passedShieldedPrivateKey:l,passedShieldedPublicKey:u,ethAddress:d,resetCacheBefore:f});console.log(`getInputUtxoAndBalancePerToken 2 inputUtxos`,b);let x=h(r);console.log(`getInputUtxoAndBalancePerToken 3 tokensWithId`,x);let S=new Map;b.forEach(e=>{let n=e.getTokenAddress(o);if(x&&!x.some(r=>t.caseInsensitiveEqual(r.erc20TokenAddress,n)&&r.tokenId===e.tokenId))return;let r=s.encodeTokenWithId(o,{erc20TokenAddress:n,tokenId:e.tokenId}),i=S.get(r)??[];S.set(r,[...i,e])}),console.log(`getInputUtxoAndBalancePerToken 4 inputUtxosPerToken`,S),p?.forEach(e=>{let t=s.encodeTokenWithId(o,{erc20TokenAddress:e.erc20TokenAddress,tokenId:e.tokenId});S.set(t,S.get(t)??[])}),console.log(`getInputUtxoAndBalancePerToken 5 ensuredTokensWithId`,p);for(let[t,n]of S){let r=t.split(`-`)[0],s=Number(t.split(`-`)[1]),l=e.isSolanaLike(o),u=l?r:void 0;_(n,i,a,g,l?c.formatMintAddress(r).compressedAddress.toLowerCase():r.toLowerCase(),s,u)}return console.log(`getInputUtxoAndBalancePerToken 6 inputUtxosPerToken`,S),S};exports.attemptGetInputUtxosRemotely=m,exports.getInputUtxoAndBalance=v,exports.getInputUtxoAndBalanceOfStuckUtxos=y,exports.getInputUtxoAndBalancePerToken=b,exports.getInputUtxosRemotely=p;
1
+ require(`../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../../constants/chains.constants.cjs`),t=require(`../../utils/caseInsensitive.utils.cjs`),n=require(`../../utils/addresses.cjs`),r=require(`../../../API/scheduled-transactions-calls.cjs`),i=require(`../../../data-structures/utxo/Utxo.cjs`),a=require(`../../utils/upToDateState.cjs`),o=require(`../../utils/cacheFunctions.cjs`),s=require(`../../utils/encodeTokenWithId.cjs`),c=require(`../../utils/solanaMint.utils.cjs`),l=require(`./getInputUtxosEnclave.cjs`),u=require(`../../utils/tron.utils.cjs`);var d=new(require(`async-mutex`)).Mutex,f=async(e,t,n,r,i,s,c,l,u)=>d.runExclusive(async()=>{u+=1;let d=s.slice(u),{lastOutput:f,additionalEncryptedOutputs:p}=await e.utxoUtils.batchProcess(d,l,t,n),m=[...c,...p];return await a.checkAddressNotUpdated(e,r),o.setHinkalCache({lastOutput:f,encryptedOutputs:m},e,n,i),await e.utxoUtils.buildBatchProcess(m,t,n)}),p=async(e,t,n,r)=>{let{utxos:i,encryptedOutputs:a,lastOutput:s}=await l.getInputUtxosEnclave(e,n,t);return o.setHinkalCache({encryptedOutputs:a,lastOutput:s},e,n,r),i},m=async(e,t,n,r,i,a,o,s,c)=>{try{return await p(e,t,n,i)}catch{return f(e,t,n,r,i,a,o,s,c)}},h=e=>{if(Array.isArray(e))return e;if(e!==void 0)return[e]},g=async(e,t,n)=>await e.utxoUtils.batchFilterUtxosWithNullifier(t,n),_=(e,t,n,r,a,o,s)=>{for(e.sort((e,t)=>e.amount<=t.amount?1:-1);e.length<t||e.length>t&&e.length<6;)if(e.push(new i.Utxo({amount:0n,erc20TokenAddress:a,mintAddress:s,shieldedPrivateKey:r,tokenId:o})),n)for(;e.length>6;)e.splice(e.length-1)},v=async({hinkal:e,chainId:t,passedShieldedPublicKey:n=void 0,ethAddress:r=void 0,resetCacheBefore:i=!1,allowRemoteDecryption:s=!1,useBlockedUtxos:c=!1})=>{let l=r??await e.getEthereumAddress(),u=n??e.userKeys.getShieldedPublicKey(),{userKeys:d}=e,p=e.encryptedOutputsByChain[t],h=e.nullifiersByChain[t],_=Array.from(p);i&&o.resetCache(e,t,u);let{encryptedOutputs:v,lastOutput:y}=o.getHinkalCache(e,t,u);await a.checkAddressNotUpdated(e,l);let b=y!==``,x=_.findIndex(e=>e.value===y),S=x>-1,C=!b&&x===-1,w=e.areMerkleTreeUpdatesDisabled(),T=!w&&(S||!s&&C),E=!w&&s&&C,D=!T&&!E,O=[];T?O=await f(e,d,t,l,u,_,v,y,x):E?O=await m(e,d,t,l,u,_,v,y,x):D&&(O=await e.utxoUtils.buildBatchProcess(v,d,t)),await a.checkAddressNotUpdated(e,l);let k=await g(e,O,h);return{inputUtxos:c?k.filter(e=>e.isBlocked):k.filter(e=>!e.isBlocked)}},y=async({hinkal:t,chainId:i,passedShieldedPublicKey:a=void 0,ethAddress:o=void 0,resetCacheBefore:s=!1,allowRemoteDecryption:c=!1})=>{let l=o??await t.getEthereumAddressByChain(i),d=n.hashEthereumAddress(e.isTronLike(i)?u.addressToHexFormat(l):l),{inputUtxos:f}=await v({hinkal:t,chainId:i,passedShieldedPublicKey:a,ethAddress:l,resetCacheBefore:s,allowRemoteDecryption:c,useBlockedUtxos:!0});if(!f.length)return{inputUtxos:[]};let{indexes:p}=await r.getScheduledTransactionsNullifierIndexes({hashedEthereumAddress:d,nullifiers:f.map(e=>e.getNullifier())});return{inputUtxos:p.map(e=>f[e]).filter(e=>!!e)}},b=async({hinkal:n,tokenWithId:r,minInput:i=2,sliceIfMore6:a=!0,chainId:o,passedShieldedPrivateKey:l=void 0,passedShieldedPublicKey:u=void 0,ethAddress:d=void 0,resetCacheBefore:f=!1,ensuredTokensWithId:p,useBlockedUtxos:m=!1})=>{let g=l??n.userKeys.getShieldedPrivateKey(),{inputUtxos:b}=m?await y({hinkal:n,chainId:o,ethAddress:d,passedShieldedPrivateKey:l,resetCacheBefore:f}):await v({hinkal:n,tokenWithId:r,minInput:i,sliceIfMore6:a,chainId:o,passedShieldedPrivateKey:l,passedShieldedPublicKey:u,ethAddress:d,resetCacheBefore:f}),x=h(r),S=new Map;b.forEach(e=>{let n=e.getTokenAddress(o);if(x&&!x.some(r=>t.caseInsensitiveEqual(r.erc20TokenAddress,n)&&r.tokenId===e.tokenId))return;let r=s.encodeTokenWithId(o,{erc20TokenAddress:n,tokenId:e.tokenId}),i=S.get(r)??[];S.set(r,[...i,e])}),p?.forEach(e=>{let t=s.encodeTokenWithId(o,{erc20TokenAddress:e.erc20TokenAddress,tokenId:e.tokenId});S.set(t,S.get(t)??[])});for(let[t,n]of S){let r=t.split(`-`)[0],s=Number(t.split(`-`)[1]),l=e.isSolanaLike(o),u=l?r:void 0;_(n,i,a,g,l?c.formatMintAddress(r).compressedAddress.toLowerCase():r.toLowerCase(),s,u)}return S};exports.attemptGetInputUtxosRemotely=m,exports.getInputUtxoAndBalance=v,exports.getInputUtxoAndBalanceOfStuckUtxos=y,exports.getInputUtxoAndBalancePerToken=b,exports.getInputUtxosRemotely=p;
@@ -13,17 +13,7 @@ import { Mutex as m } from "async-mutex";
13
13
  //#region libs/shared/common/src/functions/web3/events/getInputUtxoAndBalance.ts
14
14
  var h = new m(), g = async (e, t, n, r, i, a, s, c, u) => h.runExclusive(async () => {
15
15
  u += 1;
16
- let d = a.slice(u);
17
- console.log("sending list of outputs for batch processing", {
18
- outputsSlice: d,
19
- lastOutput: c
20
- });
21
- let { lastOutput: f, additionalEncryptedOutputs: p } = await e.utxoUtils.batchProcess(d, c, t, n);
22
- console.log("batch process result", {
23
- lastOutputNew: f,
24
- additionalEncryptedOutputs: p
25
- });
26
- let m = [...s, ...p];
16
+ let d = a.slice(u), { lastOutput: f, additionalEncryptedOutputs: p } = await e.utxoUtils.batchProcess(d, c, t, n), m = [...s, ...p];
27
17
  return await o(e, r), l({
28
18
  lastOutput: f,
29
19
  encryptedOutputs: m
@@ -52,33 +42,14 @@ var h = new m(), g = async (e, t, n, r, i, a, s, c, u) => h.runExclusive(async (
52
42
  tokenId: o
53
43
  })), n) for (; e.length > 6;) e.splice(e.length - 1);
54
44
  }, S = async ({ hinkal: e, chainId: t, passedShieldedPublicKey: n = void 0, ethAddress: r = void 0, resetCacheBefore: i = !1, allowRemoteDecryption: a = !1, useBlockedUtxos: l = !1 }) => {
55
- let u = r ?? await e.getEthereumAddress(), d = n ?? e.userKeys.getShieldedPublicKey();
56
- console.log("getInputUtxoAndBalance 0 start", {
57
- chainId: t,
58
- ethereumAddress: u,
59
- shieldedPublicKey: d
60
- });
61
- let { userKeys: f } = e, p = e.encryptedOutputsByChain[t], m = e.nullifiersByChain[t], h = Array.from(p);
62
- console.log("getInputUtxoAndBalance 2 hinkalOutputs", {
63
- hinkalOutputs: h,
64
- encryptedOutputs: p,
65
- nullifiers: m
66
- }), i && c(e, t, d);
45
+ let u = r ?? await e.getEthereumAddress(), d = n ?? e.userKeys.getShieldedPublicKey(), { userKeys: f } = e, p = e.encryptedOutputsByChain[t], m = e.nullifiersByChain[t], h = Array.from(p);
46
+ i && c(e, t, d);
67
47
  let { encryptedOutputs: _, lastOutput: y } = s(e, t, d);
68
- console.log("getInputUtxoAndBalance 1 cachedEncryptedOutputs", {
69
- cachedEncryptedOutputs: _,
70
- lastOutput: y
71
- }), await o(e, u);
72
- let x = y !== "", S = h.findIndex((e) => e.value === y), C = S > -1, w = !x && S === -1;
73
- console.log("getInputUtxoAndBalance 3 case1", C, w, x, S);
74
- let T = e.areMerkleTreeUpdatesDisabled(), E = !T && (C || !a && w), D = !T && a && w, O = !E && !D;
75
- console.log("getInputUtxoAndBalance 4 forceReadFromCache", T), console.log("getInputUtxoAndBalance 5 decryptLocally", E), console.log("getInputUtxoAndBalance 6 decryptRemotely", D), console.log("getInputUtxoAndBalance 7 useCache", O);
76
- let k = [];
77
- E ? k = await g(e, f, t, u, d, h, _, y, S) : D ? k = await v(e, f, t, u, d, h, _, y, S) : O && (k = await e.utxoUtils.buildBatchProcess(_, f, t)), console.log({ allUtxos: k }), await o(e, u);
48
+ await o(e, u);
49
+ let x = y !== "", S = h.findIndex((e) => e.value === y), C = S > -1, w = !x && S === -1, T = e.areMerkleTreeUpdatesDisabled(), E = !T && (C || !a && w), D = !T && a && w, O = !E && !D, k = [];
50
+ E ? k = await g(e, f, t, u, d, h, _, y, S) : D ? k = await v(e, f, t, u, d, h, _, y, S) : O && (k = await e.utxoUtils.buildBatchProcess(_, f, t)), await o(e, u);
78
51
  let A = await b(e, k, m);
79
- console.log("getInputUtxoAndBalance 8 inputUtxos", A);
80
- let j = l ? A.filter((e) => e.isBlocked) : A.filter((e) => !e.isBlocked);
81
- return console.log("getInputUtxoAndBalance 9 filteredInputUtxos", j), { inputUtxos: j };
52
+ return { inputUtxos: l ? A.filter((e) => e.isBlocked) : A.filter((e) => !e.isBlocked) };
82
53
  }, C = async ({ hinkal: e, chainId: n, passedShieldedPublicKey: a = void 0, ethAddress: o = void 0, resetCacheBefore: s = !1, allowRemoteDecryption: c = !1 }) => {
83
54
  let l = o ?? await e.getEthereumAddressByChain(n), u = r(t(n) ? p(l) : l), { inputUtxos: d } = await S({
84
55
  hinkal: e,
@@ -96,21 +67,7 @@ var h = new m(), g = async (e, t, n, r, i, a, s, c, u) => h.runExclusive(async (
96
67
  });
97
68
  return { inputUtxos: f.map((e) => d[e]).filter((e) => !!e) };
98
69
  }, w = async ({ hinkal: t, tokenWithId: r, minInput: i = 2, sliceIfMore6: a = !0, chainId: o, passedShieldedPrivateKey: s = void 0, passedShieldedPublicKey: c = void 0, ethAddress: l = void 0, resetCacheBefore: f = !1, ensuredTokensWithId: p, useBlockedUtxos: m = !1 }) => {
99
- console.log("getInputUtxoAndBalancePerToken 0 start", {
100
- tokenWithId: r,
101
- minInput: i,
102
- sliceIfMore6: a,
103
- chainId: o,
104
- passedShieldedPrivateKey: s,
105
- passedShieldedPublicKey: c,
106
- ethAddress: l,
107
- resetCacheBefore: f,
108
- ensuredTokensWithId: p,
109
- useBlockedUtxos: m
110
- });
111
- let h = s ?? t.userKeys.getShieldedPrivateKey();
112
- console.log("getInputUtxoAndBalancePerToken 1 useBlockedUtxos", m);
113
- let { inputUtxos: g } = m ? await C({
70
+ let h = s ?? t.userKeys.getShieldedPrivateKey(), { inputUtxos: g } = m ? await C({
114
71
  hinkal: t,
115
72
  chainId: o,
116
73
  ethAddress: l,
@@ -126,11 +83,7 @@ var h = new m(), g = async (e, t, n, r, i, a, s, c, u) => h.runExclusive(async (
126
83
  passedShieldedPublicKey: c,
127
84
  ethAddress: l,
128
85
  resetCacheBefore: f
129
- });
130
- console.log("getInputUtxoAndBalancePerToken 2 inputUtxos", g);
131
- let _ = y(r);
132
- console.log("getInputUtxoAndBalancePerToken 3 tokensWithId", _);
133
- let v = /* @__PURE__ */ new Map();
86
+ }), _ = y(r), v = /* @__PURE__ */ new Map();
134
87
  g.forEach((e) => {
135
88
  let t = e.getTokenAddress(o);
136
89
  if (_ && !_.some((r) => n(r.erc20TokenAddress, t) && r.tokenId === e.tokenId)) return;
@@ -139,18 +92,18 @@ var h = new m(), g = async (e, t, n, r, i, a, s, c, u) => h.runExclusive(async (
139
92
  tokenId: e.tokenId
140
93
  }), i = v.get(r) ?? [];
141
94
  v.set(r, [...i, e]);
142
- }), console.log("getInputUtxoAndBalancePerToken 4 inputUtxosPerToken", v), p?.forEach((e) => {
95
+ }), p?.forEach((e) => {
143
96
  let t = u(o, {
144
97
  erc20TokenAddress: e.erc20TokenAddress,
145
98
  tokenId: e.tokenId
146
99
  });
147
100
  v.set(t, v.get(t) ?? []);
148
- }), console.log("getInputUtxoAndBalancePerToken 5 ensuredTokensWithId", p);
101
+ });
149
102
  for (let [t, n] of v) {
150
103
  let r = t.split("-")[0], s = Number(t.split("-")[1]), c = e(o), l = c ? r : void 0;
151
104
  x(n, i, a, h, c ? d(r).compressedAddress.toLowerCase() : r.toLowerCase(), s, l);
152
105
  }
153
- return console.log("getInputUtxoAndBalancePerToken 6 inputUtxosPerToken", v), v;
106
+ return v;
154
107
  };
155
108
  //#endregion
156
109
  export { v as attemptGetInputUtxosRemotely, S as getInputUtxoAndBalance, C as getInputUtxoAndBalanceOfStuckUtxos, w as getInputUtxoAndBalancePerToken, _ as getInputUtxosRemotely };
@@ -1 +1 @@
1
- const e=require(`../../../constants/vite.constants.cjs`),t=require(`../../../constants/chains.constants.cjs`),n=require(`../../utils/caseInsensitive.utils.cjs`),r=require(`../../../error-handling/error-codes.constants.cjs`),i=require(`../etherFunctions.cjs`),a=require(`../../utils/erc20tokenFunctions.cjs`),o=require(`../../../data-structures/utxo/Utxo.cjs`),s=require(`../../../error-handling/customErrors/ErrorWithAmount.cjs`);require(`../../../error-handling/customErrors/index.cjs`);const c=require(`../../utils/encodeTokenWithId.cjs`),l=require(`../../utils/solanaMint.utils.cjs`),u=require(`./getInputUtxoAndBalance.cjs`),d=require(`../../../data-structures/TokenDBs/PrivateTokensDB.cjs`),f=require(`../../utils/mutexes.utils.cjs`);var p=async(t,r,i,o,s,c=!1,l,p=!1,m=!1)=>f.getChainBalanceFetchingMutex(r).runExclusive(async()=>{let{inputUtxos:f}=m?await u.getInputUtxoAndBalanceOfStuckUtxos({hinkal:t,chainId:r,ethAddress:s,passedShieldedPrivateKey:i,resetCacheBefore:c,allowRemoteDecryption:l}):await u.getInputUtxoAndBalance({hinkal:t,sliceIfMore6:!1,chainId:r,passedShieldedPrivateKey:i,passedShieldedPublicKey:o,ethAddress:s,resetCacheBefore:c,allowRemoteDecryption:l});p&&e.isExtension&&await d.privateTokensDB.fetchAndUpdatePrivateTokens(f.map(e=>e.getTokenAddress(r)).filter(e=>e!==void 0),r,s);let h=(e.isExtension?await d.privateTokensDB.getPrivateTokens(r,s):a.getErc20TokensForChain(r)).map(e=>({token:e,balance:f.reduce((t,i)=>{let a=e.erc20TokenAddress;return n.caseInsensitiveEqual(a,i.getTokenAddress(r))?t+i.amount:t},0n),timestamp:f.filter(t=>n.caseInsensitiveEqual(t.getTokenAddress(r),e.erc20TokenAddress))[0]?.timeStamp,nfts:f.filter(t=>n.caseInsensitiveEqual(t.getTokenAddress(r),e.erc20TokenAddress)&&t.tokenId!==0).map(e=>({tokenId:e.tokenId,timestamp:e.timeStamp}))})),g=new Map;return h.forEach(e=>{g.set(e.token.erc20TokenAddress.toLowerCase(),e)}),g}),m=async(e,n,d,f,p=6,m=d.map(()=>0),h=!1,g=!1)=>{console.log(`addPaddingToUtxos 0 start`,{erc20Addresses:d,amountChanges:f,maxInput:p,tokenIds:m,forceEmptyUtxos:h,useBlockedUtxos:g});let{userKeys:_}=e,v=[],y=[];if(d.length===0)return[];let b=await u.getInputUtxoAndBalancePerToken({hinkal:e,sliceIfMore6:!1,ensuredTokensWithId:d.map((e,t)=>({erc20TokenAddress:d[t],tokenId:m[t]})),allowRemoteDecryption:!1,useBlockedUtxos:g,chainId:n});console.log(`addPaddingToUtxos 1 inputUtxosPerToken`,b);let x=0;for(let e=0;e<d.length;e+=1)if(h===!1){let t=b.get(c.encodeTokenWithId(n,{erc20TokenAddress:d[e],tokenId:m[e]}))??[];if(!t)throw Error(`Missing utxos for token`);x=Math.max(t.length,x),y.push(t)}else y.push([]);return x===2?(console.log(`addPaddingToUtxos 2 inputUtxosArrayToBePadded`,y),y):(y.forEach((e,c)=>{if(e.length>p){let t=e.slice(0,p),o=t.reduce((e,t)=>e+t.amount,0n);if(f[c]<0n&&o<-f[c]){let e=a.getERC20Token(d[c],n),t=e.decimals===18?6:2,l=Number(i.getAmountWithPrecision(o,e,t));throw new s.ErrorWithAmount(l,`${r.DIRECTLY_SHOW_MESSAGE_ERROR_CODES.UTXO_LIMITATIONS}. Please try again with ${l} ${e.symbol}, including gas fees.`)}v.push(t)}else if(e.length<=p){let r=[...e],i=p-e.length;for(;i>0;){--i;let e=t.isSolanaLike(n),a=e?d[c]:void 0,s=e?l.formatMintAddress(d[c]).compressedAddress:d[c];r.push(new o.Utxo({amount:0n,erc20TokenAddress:s,mintAddress:a,shieldedPrivateKey:_.getShieldedPrivateKey(),tokenId:m[c]}))}v.push(r)}}),v)};exports.addPaddingToUtxos=m,exports.getShieldedBalance=p;
1
+ const e=require(`../../../constants/vite.constants.cjs`),t=require(`../../../constants/chains.constants.cjs`),n=require(`../../utils/caseInsensitive.utils.cjs`),r=require(`../../../error-handling/error-codes.constants.cjs`),i=require(`../etherFunctions.cjs`),a=require(`../../utils/erc20tokenFunctions.cjs`),o=require(`../../../data-structures/utxo/Utxo.cjs`),s=require(`../../../error-handling/customErrors/ErrorWithAmount.cjs`);require(`../../../error-handling/customErrors/index.cjs`);const c=require(`../../utils/encodeTokenWithId.cjs`),l=require(`../../utils/solanaMint.utils.cjs`),u=require(`./getInputUtxoAndBalance.cjs`),d=require(`../../../data-structures/TokenDBs/PrivateTokensDB.cjs`),f=require(`../../utils/mutexes.utils.cjs`);var p=async(t,r,i,o,s,c=!1,l,p=!1,m=!1)=>f.getChainBalanceFetchingMutex(r).runExclusive(async()=>{let{inputUtxos:f}=m?await u.getInputUtxoAndBalanceOfStuckUtxos({hinkal:t,chainId:r,ethAddress:s,passedShieldedPrivateKey:i,resetCacheBefore:c,allowRemoteDecryption:l}):await u.getInputUtxoAndBalance({hinkal:t,sliceIfMore6:!1,chainId:r,passedShieldedPrivateKey:i,passedShieldedPublicKey:o,ethAddress:s,resetCacheBefore:c,allowRemoteDecryption:l});p&&e.isExtension&&await d.privateTokensDB.fetchAndUpdatePrivateTokens(f.map(e=>e.getTokenAddress(r)).filter(e=>e!==void 0),r,s);let h=(e.isExtension?await d.privateTokensDB.getPrivateTokens(r,s):a.getErc20TokensForChain(r)).map(e=>({token:e,balance:f.reduce((t,i)=>{let a=e.erc20TokenAddress;return n.caseInsensitiveEqual(a,i.getTokenAddress(r))?t+i.amount:t},0n),timestamp:f.filter(t=>n.caseInsensitiveEqual(t.getTokenAddress(r),e.erc20TokenAddress))[0]?.timeStamp,nfts:f.filter(t=>n.caseInsensitiveEqual(t.getTokenAddress(r),e.erc20TokenAddress)&&t.tokenId!==0).map(e=>({tokenId:e.tokenId,timestamp:e.timeStamp}))})),g=new Map;return h.forEach(e=>{g.set(e.token.erc20TokenAddress.toLowerCase(),e)}),g}),m=async(e,n,d,f,p=6,m=d.map(()=>0),h=!1,g=!1)=>{let{userKeys:_}=e,v=[],y=[];if(d.length===0)return[];let b=await u.getInputUtxoAndBalancePerToken({hinkal:e,sliceIfMore6:!1,ensuredTokensWithId:d.map((e,t)=>({erc20TokenAddress:d[t],tokenId:m[t]})),allowRemoteDecryption:!1,useBlockedUtxos:g,chainId:n}),x=0;for(let e=0;e<d.length;e+=1)if(h===!1){let t=b.get(c.encodeTokenWithId(n,{erc20TokenAddress:d[e],tokenId:m[e]}))??[];if(!t)throw Error(`Missing utxos for token`);x=Math.max(t.length,x),y.push(t)}else y.push([]);return x===2?y:(y.forEach((e,c)=>{if(e.length>p){let t=e.slice(0,p),o=t.reduce((e,t)=>e+t.amount,0n);if(f[c]<0n&&o<-f[c]){let e=a.getERC20Token(d[c],n),t=e.decimals===18?6:2,l=Number(i.getAmountWithPrecision(o,e,t));throw new s.ErrorWithAmount(l,`${r.DIRECTLY_SHOW_MESSAGE_ERROR_CODES.UTXO_LIMITATIONS}. Please try again with ${l} ${e.symbol}, including gas fees.`)}v.push(t)}else if(e.length<=p){let r=[...e],i=p-e.length;for(;i>0;){--i;let e=t.isSolanaLike(n),a=e?d[c]:void 0,s=e?l.formatMintAddress(d[c]).compressedAddress:d[c];r.push(new o.Utxo({amount:0n,erc20TokenAddress:s,mintAddress:a,shieldedPrivateKey:_.getShieldedPrivateKey(),tokenId:m[c]}))}v.push(r)}}),v)};exports.addPaddingToUtxos=m,exports.getShieldedBalance=p;
@@ -48,14 +48,6 @@ var g = async (t, r, i, a, s, c = !1, l, u = !1, p = !1) => h(r).runExclusive(as
48
48
  _.set(e.token.erc20TokenAddress.toLowerCase(), e);
49
49
  }), _;
50
50
  }), _ = async (e, n, o, d, f = 6, m = o.map(() => 0), h = !1, g = !1) => {
51
- console.log("addPaddingToUtxos 0 start", {
52
- erc20Addresses: o,
53
- amountChanges: d,
54
- maxInput: f,
55
- tokenIds: m,
56
- forceEmptyUtxos: h,
57
- useBlockedUtxos: g
58
- });
59
51
  let { userKeys: _ } = e, v = [], y = [];
60
52
  if (o.length === 0) return [];
61
53
  let b = await p({
@@ -68,9 +60,7 @@ var g = async (t, r, i, a, s, c = !1, l, u = !1, p = !1) => h(r).runExclusive(as
68
60
  allowRemoteDecryption: !1,
69
61
  useBlockedUtxos: g,
70
62
  chainId: n
71
- });
72
- console.log("addPaddingToUtxos 1 inputUtxosPerToken", b);
73
- let x = 0;
63
+ }), x = 0;
74
64
  for (let e = 0; e < o.length; e += 1) if (h === !1) {
75
65
  let t = b.get(l(n, {
76
66
  erc20TokenAddress: o[e],
@@ -79,7 +69,7 @@ var g = async (t, r, i, a, s, c = !1, l, u = !1, p = !1) => h(r).runExclusive(as
79
69
  if (!t) throw Error("Missing utxos for token");
80
70
  x = Math.max(t.length, x), y.push(t);
81
71
  } else y.push([]);
82
- return x === 2 ? (console.log("addPaddingToUtxos 2 inputUtxosArrayToBePadded", y), y) : (y.forEach((e, l) => {
72
+ return x === 2 ? y : (y.forEach((e, l) => {
83
73
  if (e.length > f) {
84
74
  let t = e.slice(0, f), s = t.reduce((e, t) => e + t.amount, 0n);
85
75
  if (d[l] < 0n && s < -d[l]) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h_test_1",
3
- "version": "0.0.46",
3
+ "version": "0.0.47",
4
4
  "homepage": "hinkal.io",
5
5
  "author": {
6
6
  "name": "Hinkal Protocol"