h_test_1 0.0.6 → 0.0.7

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
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./babyJub.cjs"),r=require("./poseidon.cjs"),i=require("libsodium-wrappers"),s=require("process"),n=require("buffer"),c=async()=>{(typeof window<"u"||typeof self<"u")&&(typeof window<"u"&&(window.global=window),globalThis.Buffer=n.Buffer,globalThis.process=s);try{await Promise.all([i.ready,r.poseidonHolder.init(),o.jubHolder.init()]),console.log("preProcessing completed succesfully")}catch(e){console.log("preProcessing failed",e)}};exports.preProcessing=c;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./babyJub.cjs"),o=require("./poseidon.cjs"),i=require("libsodium-wrappers"),r=require("process"),n=require("buffer"),s=async()=>{(typeof window<"u"||typeof self<"u")&&(typeof window<"u"&&(window.global=window),globalThis.Buffer=n.Buffer,globalThis.process=r),await Promise.all([i.ready,o.poseidonHolder.init(),e.jubHolder.init()])};exports.preProcessing=s;
@@ -1,16 +1,11 @@
1
- import { jubHolder as e } from "./babyJub.mjs";
1
+ import { jubHolder as o } from "./babyJub.mjs";
2
2
  import { poseidonHolder as i } from "./poseidon.mjs";
3
- import r from "libsodium-wrappers";
4
- import s from "process";
3
+ import e from "libsodium-wrappers";
4
+ import r from "process";
5
5
  import { Buffer as f } from "buffer";
6
- const c = async () => {
7
- (typeof window < "u" || typeof self < "u") && (typeof window < "u" && (window.global = window), globalThis.Buffer = f, globalThis.process = s);
8
- try {
9
- await Promise.all([r.ready, i.init(), e.init()]), console.log("preProcessing completed succesfully");
10
- } catch (o) {
11
- console.log("preProcessing failed", o);
12
- }
6
+ const m = async () => {
7
+ (typeof window < "u" || typeof self < "u") && (typeof window < "u" && (window.global = window), globalThis.Buffer = f, globalThis.process = r), await Promise.all([e.ready, i.init(), o.init()]);
13
8
  };
14
9
  export {
15
- c as preProcessing
10
+ m as preProcessing
16
11
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("../../types/hinkal.types.cjs"),S=require("../../types/ethereum-network.types.cjs"),x=require("./hinkalCheckSolanaTokenRegistry.cjs"),m=require("../../functions/web3/functionCalls/accessTokenCalls.cjs"),W=require("../../functions/web3/events/getShieldedBalance.cjs"),A=require("../crypto-keys/keys.cjs"),I=require("./hinkalDeposit.cjs"),B=require("./hinkalDepositAndWithdraw.cjs"),w=require("./hinkalSolanaDeposit.cjs"),K=require("./hinkalSwap.cjs"),U=require("./hinkalWithdraw.cjs"),L=require("./hinkalWithdrawStuckUtxos.cjs"),N=require("./resetMerkleTrees.cjs"),M=require("../merkle-tree/MerkleTree.cjs");require("ethers");const R=require("../../error-handling/error-codes.constants.cjs"),F=require("../../crypto/poseidon.cjs");require("circomlibjs-hinkal-fork");require("libsodium-wrappers");require("process");require("buffer");const h=require("../../constants/chains.constants.cjs");require("../../API/getServerURL.cjs");require("axios");require("../../constants/coingecko.constants.cjs");require("../../constants/server.constants.cjs");require("../http/HttpClient.cjs");const _=require("../../constants/vite.constants.cjs"),P=require("../../API/API.cjs");require("../../constants/token-data/index.cjs");require("../../constants/contracts.constants.cjs");const O=require("../../constants/kyc.constants.cjs");require("../../constants/reorg-depths.constants.cjs");require("../../constants/addresses.constants.cjs");require("../../constants/token.limits.constants.cjs");require("../../constants/presale.constants.cjs");require("../../constants/activity.constants.cjs");require("../../constants/tasks.constants.cjs");require("../../constants/events.constants.cjs");require("../../API/tenderly.api.cjs");const j=require("../../functions/utils/reloadPage.cjs"),z=require("../MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.cjs"),$=require("./hinkalPrivateWallet.cjs"),J=require("../../functions/utils/cacheFunctions.cjs"),Q=require("../../functions/utils/cacheDevice.utils.cjs"),V=require("../../functions/web3/getContractMetadata.cjs"),X=require("./hinkalGetRecipientInfo.cjs"),Y=require("./hinkalApprove.cjs"),Z=require("./hinkalInsideTransact.cjs"),v=require("../../functions/web3/events/getApprovedBalance.cjs"),C=require("../../functions/web3/functionCalls/inHinkalApprovalCalls.cjs"),G=require("./hinkalSignSubAccount.cjs"),ee=require("./hinkalCheckTokenRegistry.cjs"),te=require("./hinkalActionReceive.cjs"),re=require("./hinkalActionFundApproveAndTransact.cjs"),ie=require("../TokenDBs/PrivateTokensDB.cjs");require("idb-keyval");const ae=require("../../functions/utils/erc20tokenFunctions.cjs");require("multiformats");const g=require("@solana/web3.js");require("@solana/spl-token");require("async-mutex");require("../../functions/utils/convertIntegrationProviderToExternalActionId.cjs");require("../../types/circom-data.types.cjs");require("../../types/activities.types.cjs");const E=require("../../functions/pre-transaction/solana.cjs");require("@coral-xyz/anchor");require("../../functions/utils/userAgent.cjs");require("../../functions/utils/mutexes.utils.cjs");require("node-forge");require("../../functions/web3/getTokenHolder.cjs");const ne=require("../../functions/private-wallet/emporium.helpers.cjs"),se=require("./hinkalProoflessDeposit.cjs"),oe=require("./hinkalProxySwap.cjs"),ce=require("./hinkalMultiSend.cjs"),he=require("./hinkalTransfer.cjs"),le=require("./hinkalProxyToPrivate.cjs"),de=require("./hinkalSolanaDepositAndWithdraw.cjs"),pe=require("./hinkalSolanaWithdraw.cjs"),ue=require("./hinkalSolanaTransfer.cjs"),ge=require("./hinkalSolanaSwap.cjs"),ke=require("./hinkalSolanaProxySend.cjs"),ve=require("./hinkalSolanaProxySwap.cjs"),D=require("./hinkalSolanaProxyShield.cjs"),H=require("../../functions/web3/fetchSolanaMerkleTreeRootHash.cjs"),ye=require("./hinkalDepostAndBridge.cjs");class Se{providerAdapter;userKeys;signingMessage="Login to Hinkal Protocol";privateTransferSigningMessage="Login to Hinkal's Private Transfer App";merkleTreeHinkal;merkleTreeAccessToken;nullifiers;encryptedOutputs;approvals;commitmentsSnapshotService;nullifierSnapshotService;accessTokenSnapshotService;approvalsSnapshotService;utxoUtils;cacheDevice;generateProofRemotely;disableMerkleTreeUpdates;constructor(e){this.userKeys=new A.UserKeys(void 0),this.merkleTreeHinkal=M.MerkleTree.create(F.poseidonFunction,0n),this.merkleTreeAccessToken=M.MerkleTree.create(F.poseidonFunction,0n),this.nullifiers=new Set,this.encryptedOutputs=[],this.approvals=new Map,this.generateProofRemotely=e?.generateProofRemotely??!1,this.utxoUtils=new z.MultiThreadedUtxoUtils,this.cacheDevice=Q.createCacheDevice(e),this.disableMerkleTreeUpdates=e?.disableMerkleTreeUpdates??!1}async initProviderAdapter(e,t){await this.updateProviderAdapter(t),this.providerAdapter?.initConnector(e);const r=await this.connectAndPatchProvider(e);await t.init(r),await this.setListeners()}async initUserKeys(e=!1){const t=e?this.privateTransferSigningMessage:this.signingMessage;this.userKeys=new A.UserKeys(await this.getProviderAdapter().signMessage(t))}async initUserKeysWithPassword(e){this.userKeys=new A.UserKeys(e)}async resetMerkle(){this.disableMerkleTreeUpdates||this.isSelectedNetworkSupported()&&await N.resetMerkleTrees(this)}getProviderAdapter(){if(!this.providerAdapter)throw new Error("ProviderAdapter is not initialized");return this.providerAdapter}async waitForTransaction(e,t=1){return!!await this.providerAdapter?.waitForTransaction(e,t)}getContractMetadata(e,t){return this.getProviderAdapter().getContractMetadata(e,t)}getContract(e,t=void 0,r){return this.getProviderAdapter().getContract(e,t,r)}getContractWithFetcherByChainId(e,t,r=void 0){return V.getContractWithFetcherByChainId(e,t,r)}async signMessage(e){return await this.getProviderAdapter().signMessage(e)}async signTypedData(e,t,r){return await this.getProviderAdapter().signTypedData(e,t,r)}async signWithSubAccount(e,t,r){return G.hinkalSignSubAccount(this,e,t,r)}getContractWithSigner(e,t=""){return this.getProviderAdapter().getContractWithSigner(e,t)}getContractWithFetcher(e,t=""){return this.getProviderAdapter().getContractWithFetcher(e,t)}getContractWithFetcherForEthereum(e,t){return this.getProviderAdapter().getContractWithFetcherForEthereum(e,t)}isSelectedNetworkSupported(){return!!h.networkRegistry[this.getCurrentChainId()]}async switchNetwork(e){try{await this.getProviderAdapter().switchNetwork(e)}catch{throw new Error(R.transactionErrorCodes.FAILED_TO_SWITCH_NETWORKS)}}async switchAccount(e){await this.getProviderAdapter().switchAccount(e)}getCurrentChainId(){const{chainId:e}=this.getProviderAdapter();if(!e)throw new Error("Illegal State: no chainId");return e}getSelectedNetwork(){return this.providerAdapter?.getSelectedNetwork()}isPermitterAvailable(){return this.getProviderAdapter().isPermitterAvailable()}async connectAndPatchProvider(e){return await this.getProviderAdapter().connectAndPatchProvider(e)}async disconnectFromConnector(){await this.getProviderAdapter().disconnectFromConnector()}async updateProviderAdapter(e){try{this.providerAdapter&&this.providerAdapter.release(),this.providerAdapter=e}catch(t){throw console.error(t),Error("updateProviderAdapter failed, please try again.")}}async setListeners(){this.providerAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}})}async onAccountChanged(){await this.getProviderAdapter().onAccountChanged();const e=T.EventType.AccountChanged;typeof document<"u"?document?.dispatchEvent(new Event(e)):process?.emit("message",e,void 0)}async onChainChanged(e){if(e){await this.getProviderAdapter().onChainChanged(e);const t=T.EventType.NetworkChange;typeof document<"u"?document.dispatchEvent(new Event(t)):process?.emit("message",t,void 0)}else await this.disconnectFromConnector(),j.reloadPage()}async monitorConnectedAddress(){const e=this.getCurrentChainId();h.isSolanaLike(e)||await P.API.monitor(await this.getEthereumAddress(),e)}async getBalances(e,t,r,i,a=!1,n,s=!1){return W.getShieldedBalance(this,e,t,r,i,a,this.generateProofRemotely,n,s)}async getApprovedBalances(e=!1,t=!1){return v.getApprovedBalance(this,e,t)}async getTotalBalance(e,t,r,i=!1,a,n=!1){const s=e??this.getCurrentChainId(),o=r??await this.getEthereumAddress(),c=t??this.userKeys,l=await this.getBalances(s,c.getShieldedPrivateKey(),c.getShieldedPublicKey(),o,i,a,n),p=!h.isSolanaLike(s)&&!n?await this.getApprovedBalances(i,a):new Map,d=_.isExtension?await ie.privateTokensDB.getPrivateTokens(s,o):ae.getErc20TokensForChain(s),u=[];return d.forEach(k=>{const f=k.erc20TokenAddress.toLowerCase(),y=l.get(f),q=p.get(f),b={token:k,balance:(y?.balance??0n)+(q?.balance??0n),timestamp:y?.timestamp||q?.timestamp||"0",nfts:y?.nfts||[]};u.push(b)}),u}async getStuckShieldedBalances(e,t,r){return(await this.getTotalBalance(e,t,r,!1,!1,!0)).filter(a=>a.balance>0n)}getSupportedPassportLinks(){return O.supportedPassportLinks}checkAccessToken(){return m.checkHinkalAccessToken(this)}async mintHinkalAccessToken(e,t){return m.mintAccessToken(this,e,t)}async getHinkalTreeRootHash(){const e=this.getCurrentChainId();if(h.isSolanaLike(e)){const{hinkalIdl:r,hinkalAddress:i,originalDeployer:a}=h.networkRegistry[e].contractData;if(!r||!i||!a)throw new Error(`Missing Solana configuration for chain ${e}`);const n=new g.PublicKey(a),s=new g.PublicKey(i),o=E.getMerkleAccountPublicKey(s,n),c=this.getSolanaProgram(r);return H.fetchSolanaMerkleTreeRootHash(c,o)}return this.getContractWithFetcher(S.ContractType.HinkalContract).getRootHash()}async getAccessTokenTreeRootHash(){const e=this.getCurrentChainId();if(h.isSolanaLike(e)){const{hinkalIdl:r,hinkalAddress:i,originalDeployer:a}=h.networkRegistry[e].contractData;if(!r||!i||!a)throw new Error(`Missing Solana configuration for chain ${e}`);const n=new g.PublicKey(a),s=new g.PublicKey(i),o=E.getAccessTokenMerkleAccountPublicKey(s,n),c=this.getSolanaProgram(r);return H.fetchSolanaMerkleTreeRootHash(c,o)}return this.getContractWithFetcher(S.ContractType.AccessTokenContract).getRootHash()}async resetMerkleTreesIfNecessary(){if(!this.isSelectedNetworkSupported())throw new Error(R.transactionErrorCodes.UNSUPPORTED_NETWORK);const[e,t]=await Promise.all([this.getHinkalTreeRootHash(),this.getAccessTokenTreeRootHash()]);(BigInt(e)!==this.merkleTreeHinkal.getRootHash()||BigInt(t)!==this.merkleTreeAccessToken.getRootHash())&&(console.log("resetting merkle tree in resetMerkleTreesIfNecessary"),await this.resetMerkle())}async getEventsFromHinkal(){await Promise.all([this.accessTokenSnapshotService?.retrieveEventsFromLatestBlock(),this.commitmentsSnapshotService?.retrieveEventsFromLatestBlock(),this.nullifierSnapshotService?.retrieveEventsFromLatestBlock(),this.approvalsSnapshotService?.retrieveEventsFromLatestBlock()])}getEthereumAddress(){return this.getProviderAdapter().getAddress()}async getRandomRelay(e=!1){const t=this.getCurrentChainId();return(await P.API.getIdleRelay(t,e)).relay}getGasPrice(){if(!this.providerAdapter?.chainId)throw new Error("Illegal State of providerAdapter in Hinkal: no chainId");return this.providerAdapter.getGasPrice()}getAPI(){return P.API}resetCache(){J.resetCache(this,this.getCurrentChainId(),this.userKeys.getShieldedPublicKey())}snapshotsClearInterval(){this.commitmentsSnapshotService?.intervalClear(),this.accessTokenSnapshotService?.intervalClear(),this.nullifierSnapshotService?.intervalClear(),this.approvalsSnapshotService?.intervalClear()}checkTokenRegistry(e,t){const r=this.getCurrentChainId();if(h.isSolanaLike(r)){const{hinkalIdl:a,hinkalAddress:n,originalDeployer:s}=h.networkRegistry[r].contractData;if(!a||!n||!s)throw new Error("missing solana data");const o=this.getSolanaProgram(a),c=new g.PublicKey(s);return x.hinkalCheckSolanaTokenRegistry(o,c,e,t)}const i=this.getContractWithFetcher(S.ContractType.HinkalHelperContract);return ee.hinkalCheckTokenRegistry(i,e,t)}getRecipientInfo(){return X.getRecipientInfo(this)}async getInteractionApprovals(e){return await C.getInteractionApprovals(this,e)}getApprovedUtxos(e=!1){return v.getApprovedUtxos(this,e)}getApprovedUtxosForToken(e,t=!1){return v.getApprovedUtxosForToken(this,e,t)}getMyApprovalAmountForInteraction(e,t){return v.getMyApprovalAmountForInteraction(this,e,t)}async checkExistingApprovalFromHinkal(e,t){return await C.checkExistingApprovalFromHinkal(this,e,t)}async getBufferEntry(e,t,r){return C.getBufferEntry(this,e,t,r)}async deposit(e,t){return I.hinkalDeposit(this,e,t)}async depositForOther(e,t,r){return I.hinkalDepositForOther(this,e,t,r)}async depositAndWithdraw(e,t,r,i,a,n){return h.isSolanaLike(this.getCurrentChainId())?de.hinkalSolanaDepositAndWithdraw(this,e.erc20TokenAddress,t,r,i,a,n):B.hinkalDepositAndWithdraw(this,e,t,r,i,a,n)}async depositAndBridge(e,t,r,i,a){return ye.hinkalDepositAndBridge(this,e,t,r,i,a)}async prooflessDeposit(e,t,r){return se.hinkalProoflessDeposit(this,e,t,r)}getSolanaProgram(e){if(!this.providerAdapter)throw new Error("No provider adapter initialized");if(!("getSolanaProgram"in this.providerAdapter))throw new Error("Current provider adapter is not a Solana provider adapter");return this.providerAdapter.getSolanaProgram(e)}getSolanaPublicKey(){if(!this.providerAdapter)throw new Error("No provider adapter initialized");if(!("getSolanaPublicKey"in this.providerAdapter))throw new Error("Current provider adapter is not a Solana provider adapter");return this.providerAdapter.getSolanaPublicKey()}async depositSolana(e,t){return w.hinkalSolanaDeposit(this,e,t)}async depositSolanaForOther(e,t,r){return w.hinkalSolanaDepositForOther(this,e,t,r)}async solanaMultiPaymentDeposit(e,t){return w.hinkalSolanaMultiPaymentDeposit(this,e,t)}async transfer(e,t,r,i,a,n,s=!1){return h.isSolanaLike(this.getCurrentChainId())?ue.hinkalSolanaTransfer(this,e,t,r,i,a,s):he.hinkalTransfer(this,e,t,r,i,a,n,s)}async withdraw(e,t,r,i,a,n,s,o=!1){return h.isSolanaLike(this.getCurrentChainId())?pe.hinkalSolanaWithdraw(this,e.map(c=>c.erc20TokenAddress),t,r,a,n,o):U.hinkalWithdraw(this,e,t,r,i,a,n,s,o)}async withdrawStuckUtxos(e,t){return L.hinkalWithdrawStuckUtxos(this,e,t)}async swap(e,t,r,i,a,n,s,o=!1,c=!1){return h.isSolanaLike(this.getCurrentChainId())?this.swapSolana(e,t,i,a,n,o):K.hinkalSwap(this,e,t,r,i,a,n,s,o,c)}async swapSolana(e,t,r,i,a,n=!1){const s=JSON.parse(r),o=BigInt(s.swapperAccountSalt),{instructionLists:c,addressLookupTableAccount:l}=s.data;return ge.hinkalSolanaSwap(this,e,t,o,c,l,i,a,n)}async actionReceive(e,t,r,i,a,n,s=!1){if(!a)throw new Error("subAccount is required");return h.isSolanaLike(this.getCurrentChainId())?D.hinkalSolanaProxyShield(this,e[0],t[0],a,void 0,s):te.hinkalActionReceive(this,e,t,r,i,a,n,s)}async actionFundApproveAndTransact(e,t,r,i,a,n,s,o,c=!1,l,p,d){return re.hinkalActionFundApproveAndTransact(this,e,t,r,i,a,n,s,o,c,l,p,d)}async actionPrivateWallet(e,t,r,i,a,n,s,o,c,l=!1,p,d,u,k=!1){return $.hinkalPrivateWallet(this,e,t,r,i,a,n,s,o,c,l,p,d,u,k)}async approve(e,t,r,i,a,n=!1){return Y.hinkalApprove(this,e,t,r,i,a,n)}async hinkalInsideTransact(e,t,r,i,a,n,s,o,c,l=!1){return Z.hinkalInsideTransact(this,e,t,r,i,a,n,s,o,c,l)}async proxySwap(e,t,r,i,a,n,s,o,c=!1,l,p,d=!1){return h.isSolanaLike(this.getCurrentChainId())?ve.hinkalSolanaProxySwap(this,e,t,i,n,s,o,d):oe.hinkalProxySwap(this,e,t,r,i,a,n,s,o,c,l,p,d)}async proxyToPrivate(e,t,r,i,a,n,s,o=!1){return h.isSolanaLike(this.getCurrentChainId())?D.hinkalSolanaProxyShield(this,e[0],t[0],r,i,o):le.hinkalProxyToPrivate(this,e,t,i,a,n,r,s,o)}async proxySend(e,t,r,i,a,n,s,o=!1){if(h.isSolanaLike(this.getCurrentChainId()))return ke.hinkalSolanaProxySend(this,e[0],t[0],r,i,o);const c=ne.createTransaferEmporiumOpsBatch(this,e.map(d=>d.erc20TokenAddress),t,i),l=e.map((d,u)=>({token:d,amount:-1n*t[u]}));return await this.actionPrivateWallet([],[],[],c,l,r,a,n,void 0,void 0,void 0,s,void 0,o)}async multiSendPrivateRecipients(e,t,r){return ce.hinkalMultiSendPrivateRecipients(this,e,t,r)}areMerkleTreeUpdatesDisabled(){return this.disableMerkleTreeUpdates}updateMerkleTreeUpdates(e){this.disableMerkleTreeUpdates=e}}exports.Hinkal=Se;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const T=require("../../types/hinkal.types.cjs"),S=require("../../types/ethereum-network.types.cjs"),x=require("./hinkalCheckSolanaTokenRegistry.cjs"),m=require("../../functions/web3/functionCalls/accessTokenCalls.cjs"),W=require("../../functions/web3/events/getShieldedBalance.cjs"),A=require("../crypto-keys/keys.cjs"),I=require("./hinkalDeposit.cjs"),B=require("./hinkalDepositAndWithdraw.cjs"),w=require("./hinkalSolanaDeposit.cjs"),K=require("./hinkalSwap.cjs"),U=require("./hinkalWithdraw.cjs"),L=require("./hinkalWithdrawStuckUtxos.cjs"),N=require("./resetMerkleTrees.cjs"),M=require("../merkle-tree/MerkleTree.cjs");require("ethers");const R=require("../../error-handling/error-codes.constants.cjs"),F=require("../../crypto/poseidon.cjs");require("circomlibjs-hinkal-fork");require("libsodium-wrappers");require("process");require("buffer");const h=require("../../constants/chains.constants.cjs");require("../../API/getServerURL.cjs");require("axios");require("../../constants/coingecko.constants.cjs");require("../../constants/server.constants.cjs");require("../http/HttpClient.cjs");const _=require("../../constants/vite.constants.cjs"),P=require("../../API/API.cjs");require("../../constants/token-data/index.cjs");require("../../constants/contracts.constants.cjs");const O=require("../../constants/kyc.constants.cjs");require("../../constants/reorg-depths.constants.cjs");require("../../constants/addresses.constants.cjs");require("../../constants/token.limits.constants.cjs");require("../../constants/presale.constants.cjs");require("../../constants/activity.constants.cjs");require("../../constants/tasks.constants.cjs");require("../../constants/events.constants.cjs");require("../../API/tenderly.api.cjs");const j=require("../../functions/utils/reloadPage.cjs"),z=require("../MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.cjs"),$=require("./hinkalPrivateWallet.cjs"),J=require("../../functions/utils/cacheFunctions.cjs"),Q=require("../../functions/utils/cacheDevice.utils.cjs"),V=require("../../functions/web3/getContractMetadata.cjs"),X=require("./hinkalGetRecipientInfo.cjs"),Y=require("./hinkalApprove.cjs"),Z=require("./hinkalInsideTransact.cjs"),v=require("../../functions/web3/events/getApprovedBalance.cjs"),C=require("../../functions/web3/functionCalls/inHinkalApprovalCalls.cjs"),G=require("./hinkalSignSubAccount.cjs"),ee=require("./hinkalCheckTokenRegistry.cjs"),te=require("./hinkalActionReceive.cjs"),re=require("./hinkalActionFundApproveAndTransact.cjs"),ie=require("../TokenDBs/PrivateTokensDB.cjs");require("idb-keyval");const ne=require("../../functions/utils/erc20tokenFunctions.cjs");require("multiformats");const g=require("@solana/web3.js");require("@solana/spl-token");require("async-mutex");require("../../functions/utils/convertIntegrationProviderToExternalActionId.cjs");require("../../types/circom-data.types.cjs");require("../../types/activities.types.cjs");const E=require("../../functions/pre-transaction/solana.cjs");require("@coral-xyz/anchor");require("../../functions/utils/userAgent.cjs");require("../../functions/utils/mutexes.utils.cjs");require("node-forge");require("../../functions/web3/getTokenHolder.cjs");const ae=require("../../functions/private-wallet/emporium.helpers.cjs"),se=require("./hinkalProoflessDeposit.cjs"),oe=require("./hinkalProxySwap.cjs"),ce=require("./hinkalMultiSend.cjs"),he=require("./hinkalTransfer.cjs"),le=require("./hinkalProxyToPrivate.cjs"),de=require("./hinkalSolanaDepositAndWithdraw.cjs"),pe=require("./hinkalSolanaWithdraw.cjs"),ue=require("./hinkalSolanaTransfer.cjs"),ge=require("./hinkalSolanaSwap.cjs"),ke=require("./hinkalSolanaProxySend.cjs"),ve=require("./hinkalSolanaProxySwap.cjs"),D=require("./hinkalSolanaProxyShield.cjs"),H=require("../../functions/web3/fetchSolanaMerkleTreeRootHash.cjs"),ye=require("./hinkalDepostAndBridge.cjs");class Se{providerAdapter;userKeys;signingMessage="Login to Hinkal Protocol";privateTransferSigningMessage="Login to Hinkal's Private Transfer App";merkleTreeHinkal;merkleTreeAccessToken;nullifiers;encryptedOutputs;approvals;commitmentsSnapshotService;nullifierSnapshotService;accessTokenSnapshotService;approvalsSnapshotService;utxoUtils;cacheDevice;generateProofRemotely;disableMerkleTreeUpdates;constructor(e){this.userKeys=new A.UserKeys(void 0),this.merkleTreeHinkal=M.MerkleTree.create(F.poseidonFunction,0n),this.merkleTreeAccessToken=M.MerkleTree.create(F.poseidonFunction,0n),this.nullifiers=new Set,this.encryptedOutputs=[],this.approvals=new Map,this.generateProofRemotely=e?.generateProofRemotely??!0,this.utxoUtils=new z.MultiThreadedUtxoUtils,this.cacheDevice=Q.createCacheDevice(e),this.disableMerkleTreeUpdates=e?.disableMerkleTreeUpdates??!1}async initProviderAdapter(e,t){await this.updateProviderAdapter(t),this.providerAdapter?.initConnector(e);const r=await this.connectAndPatchProvider(e);await t.init(r),await this.setListeners()}async initUserKeys(e=!1){const t=e?this.privateTransferSigningMessage:this.signingMessage;this.userKeys=new A.UserKeys(await this.getProviderAdapter().signMessage(t))}async initUserKeysWithPassword(e){this.userKeys=new A.UserKeys(e)}async resetMerkle(){this.disableMerkleTreeUpdates||this.isSelectedNetworkSupported()&&await N.resetMerkleTrees(this)}getProviderAdapter(){if(!this.providerAdapter)throw new Error("ProviderAdapter is not initialized");return this.providerAdapter}async waitForTransaction(e,t=1){return!!await this.providerAdapter?.waitForTransaction(e,t)}getContractMetadata(e,t){return this.getProviderAdapter().getContractMetadata(e,t)}getContract(e,t=void 0,r){return this.getProviderAdapter().getContract(e,t,r)}getContractWithFetcherByChainId(e,t,r=void 0){return V.getContractWithFetcherByChainId(e,t,r)}async signMessage(e){return await this.getProviderAdapter().signMessage(e)}async signTypedData(e,t,r){return await this.getProviderAdapter().signTypedData(e,t,r)}async signWithSubAccount(e,t,r){return G.hinkalSignSubAccount(this,e,t,r)}getContractWithSigner(e,t=""){return this.getProviderAdapter().getContractWithSigner(e,t)}getContractWithFetcher(e,t=""){return this.getProviderAdapter().getContractWithFetcher(e,t)}getContractWithFetcherForEthereum(e,t){return this.getProviderAdapter().getContractWithFetcherForEthereum(e,t)}isSelectedNetworkSupported(){return!!h.networkRegistry[this.getCurrentChainId()]}async switchNetwork(e){try{await this.getProviderAdapter().switchNetwork(e)}catch{throw new Error(R.transactionErrorCodes.FAILED_TO_SWITCH_NETWORKS)}}async switchAccount(e){await this.getProviderAdapter().switchAccount(e)}getCurrentChainId(){const{chainId:e}=this.getProviderAdapter();if(!e)throw new Error("Illegal State: no chainId");return e}getSelectedNetwork(){return this.providerAdapter?.getSelectedNetwork()}isPermitterAvailable(){return this.getProviderAdapter().isPermitterAvailable()}async connectAndPatchProvider(e){return await this.getProviderAdapter().connectAndPatchProvider(e)}async disconnectFromConnector(){await this.getProviderAdapter().disconnectFromConnector()}async updateProviderAdapter(e){try{this.providerAdapter&&this.providerAdapter.release(),this.providerAdapter=e}catch(t){throw console.error(t),Error("updateProviderAdapter failed, please try again.")}}async setListeners(){this.providerAdapter?.setChainEventListener({onAccountChanged:()=>{this.onAccountChanged()},onChainChanged:e=>{this.onChainChanged(e)}})}async onAccountChanged(){await this.getProviderAdapter().onAccountChanged();const e=T.EventType.AccountChanged;typeof document<"u"?document?.dispatchEvent(new Event(e)):process?.emit("message",e,void 0)}async onChainChanged(e){if(e){await this.getProviderAdapter().onChainChanged(e);const t=T.EventType.NetworkChange;typeof document<"u"?document.dispatchEvent(new Event(t)):process?.emit("message",t,void 0)}else await this.disconnectFromConnector(),j.reloadPage()}async monitorConnectedAddress(){const e=this.getCurrentChainId();h.isSolanaLike(e)||await P.API.monitor(await this.getEthereumAddress(),e)}async getBalances(e,t,r,i,n=!1,a,s=!1){return W.getShieldedBalance(this,e,t,r,i,n,this.generateProofRemotely,a,s)}async getApprovedBalances(e=!1,t=!1){return v.getApprovedBalance(this,e,t)}async getTotalBalance(e,t,r,i=!1,n,a=!1){const s=e??this.getCurrentChainId(),o=r??await this.getEthereumAddress(),c=t??this.userKeys,l=await this.getBalances(s,c.getShieldedPrivateKey(),c.getShieldedPublicKey(),o,i,n,a),p=!h.isSolanaLike(s)&&!a?await this.getApprovedBalances(i,n):new Map,d=_.isExtension?await ie.privateTokensDB.getPrivateTokens(s,o):ne.getErc20TokensForChain(s),u=[];return d.forEach(k=>{const f=k.erc20TokenAddress.toLowerCase(),y=l.get(f),q=p.get(f),b={token:k,balance:(y?.balance??0n)+(q?.balance??0n),timestamp:y?.timestamp||q?.timestamp||"0",nfts:y?.nfts||[]};u.push(b)}),u}async getStuckShieldedBalances(e,t,r){return(await this.getTotalBalance(e,t,r,!1,!1,!0)).filter(n=>n.balance>0n)}getSupportedPassportLinks(){return O.supportedPassportLinks}checkAccessToken(){return m.checkHinkalAccessToken(this)}async mintHinkalAccessToken(e,t){return m.mintAccessToken(this,e,t)}async getHinkalTreeRootHash(){const e=this.getCurrentChainId();if(h.isSolanaLike(e)){const{hinkalIdl:r,hinkalAddress:i,originalDeployer:n}=h.networkRegistry[e].contractData;if(!r||!i||!n)throw new Error(`Missing Solana configuration for chain ${e}`);const a=new g.PublicKey(n),s=new g.PublicKey(i),o=E.getMerkleAccountPublicKey(s,a),c=this.getSolanaProgram(r);return H.fetchSolanaMerkleTreeRootHash(c,o)}return this.getContractWithFetcher(S.ContractType.HinkalContract).getRootHash()}async getAccessTokenTreeRootHash(){const e=this.getCurrentChainId();if(h.isSolanaLike(e)){const{hinkalIdl:r,hinkalAddress:i,originalDeployer:n}=h.networkRegistry[e].contractData;if(!r||!i||!n)throw new Error(`Missing Solana configuration for chain ${e}`);const a=new g.PublicKey(n),s=new g.PublicKey(i),o=E.getAccessTokenMerkleAccountPublicKey(s,a),c=this.getSolanaProgram(r);return H.fetchSolanaMerkleTreeRootHash(c,o)}return this.getContractWithFetcher(S.ContractType.AccessTokenContract).getRootHash()}async resetMerkleTreesIfNecessary(){if(!this.isSelectedNetworkSupported())throw new Error(R.transactionErrorCodes.UNSUPPORTED_NETWORK);const[e,t]=await Promise.all([this.getHinkalTreeRootHash(),this.getAccessTokenTreeRootHash()]);(BigInt(e)!==this.merkleTreeHinkal.getRootHash()||BigInt(t)!==this.merkleTreeAccessToken.getRootHash())&&(console.log("resetting merkle tree in resetMerkleTreesIfNecessary"),await this.resetMerkle())}async getEventsFromHinkal(){await Promise.all([this.accessTokenSnapshotService?.retrieveEventsFromLatestBlock(),this.commitmentsSnapshotService?.retrieveEventsFromLatestBlock(),this.nullifierSnapshotService?.retrieveEventsFromLatestBlock(),this.approvalsSnapshotService?.retrieveEventsFromLatestBlock()])}getEthereumAddress(){return this.getProviderAdapter().getAddress()}async getRandomRelay(e=!1){const t=this.getCurrentChainId();return(await P.API.getIdleRelay(t,e)).relay}getGasPrice(){if(!this.providerAdapter?.chainId)throw new Error("Illegal State of providerAdapter in Hinkal: no chainId");return this.providerAdapter.getGasPrice()}getAPI(){return P.API}resetCache(){J.resetCache(this,this.getCurrentChainId(),this.userKeys.getShieldedPublicKey())}snapshotsClearInterval(){this.commitmentsSnapshotService?.intervalClear(),this.accessTokenSnapshotService?.intervalClear(),this.nullifierSnapshotService?.intervalClear(),this.approvalsSnapshotService?.intervalClear()}checkTokenRegistry(e,t){const r=this.getCurrentChainId();if(h.isSolanaLike(r)){const{hinkalIdl:n,hinkalAddress:a,originalDeployer:s}=h.networkRegistry[r].contractData;if(!n||!a||!s)throw new Error("missing solana data");const o=this.getSolanaProgram(n),c=new g.PublicKey(s);return x.hinkalCheckSolanaTokenRegistry(o,c,e,t)}const i=this.getContractWithFetcher(S.ContractType.HinkalHelperContract);return ee.hinkalCheckTokenRegistry(i,e,t)}getRecipientInfo(){return X.getRecipientInfo(this)}async getInteractionApprovals(e){return await C.getInteractionApprovals(this,e)}getApprovedUtxos(e=!1){return v.getApprovedUtxos(this,e)}getApprovedUtxosForToken(e,t=!1){return v.getApprovedUtxosForToken(this,e,t)}getMyApprovalAmountForInteraction(e,t){return v.getMyApprovalAmountForInteraction(this,e,t)}async checkExistingApprovalFromHinkal(e,t){return await C.checkExistingApprovalFromHinkal(this,e,t)}async getBufferEntry(e,t,r){return C.getBufferEntry(this,e,t,r)}async deposit(e,t){return I.hinkalDeposit(this,e,t)}async depositForOther(e,t,r){return I.hinkalDepositForOther(this,e,t,r)}async depositAndWithdraw(e,t,r,i,n,a){return h.isSolanaLike(this.getCurrentChainId())?de.hinkalSolanaDepositAndWithdraw(this,e.erc20TokenAddress,t,r,i,n,a):B.hinkalDepositAndWithdraw(this,e,t,r,i,n,a)}async depositAndBridge(e,t,r,i,n){return ye.hinkalDepositAndBridge(this,e,t,r,i,n)}async prooflessDeposit(e,t,r){return se.hinkalProoflessDeposit(this,e,t,r)}getSolanaProgram(e){if(!this.providerAdapter)throw new Error("No provider adapter initialized");if(!("getSolanaProgram"in this.providerAdapter))throw new Error("Current provider adapter is not a Solana provider adapter");return this.providerAdapter.getSolanaProgram(e)}getSolanaPublicKey(){if(!this.providerAdapter)throw new Error("No provider adapter initialized");if(!("getSolanaPublicKey"in this.providerAdapter))throw new Error("Current provider adapter is not a Solana provider adapter");return this.providerAdapter.getSolanaPublicKey()}async depositSolana(e,t){return w.hinkalSolanaDeposit(this,e,t)}async depositSolanaForOther(e,t,r){return w.hinkalSolanaDepositForOther(this,e,t,r)}async solanaMultiPaymentDeposit(e,t){return w.hinkalSolanaMultiPaymentDeposit(this,e,t)}async transfer(e,t,r,i,n,a,s=!1){return h.isSolanaLike(this.getCurrentChainId())?ue.hinkalSolanaTransfer(this,e,t,r,i,n,s):he.hinkalTransfer(this,e,t,r,i,n,a,s)}async withdraw(e,t,r,i,n,a,s,o=!1){return h.isSolanaLike(this.getCurrentChainId())?pe.hinkalSolanaWithdraw(this,e.map(c=>c.erc20TokenAddress),t,r,n,a,o):U.hinkalWithdraw(this,e,t,r,i,n,a,s,o)}async withdrawStuckUtxos(e,t){return L.hinkalWithdrawStuckUtxos(this,e,t)}async swap(e,t,r,i,n,a,s,o=!1,c=!1){return h.isSolanaLike(this.getCurrentChainId())?this.swapSolana(e,t,i,n,a,o):K.hinkalSwap(this,e,t,r,i,n,a,s,o,c)}async swapSolana(e,t,r,i,n,a=!1){const s=JSON.parse(r),o=BigInt(s.swapperAccountSalt),{instructionLists:c,addressLookupTableAccount:l}=s.data;return ge.hinkalSolanaSwap(this,e,t,o,c,l,i,n,a)}async actionReceive(e,t,r,i,n,a,s=!1){if(!n)throw new Error("subAccount is required");return h.isSolanaLike(this.getCurrentChainId())?D.hinkalSolanaProxyShield(this,e[0],t[0],n,void 0,s):te.hinkalActionReceive(this,e,t,r,i,n,a,s)}async actionFundApproveAndTransact(e,t,r,i,n,a,s,o,c=!1,l,p,d){return re.hinkalActionFundApproveAndTransact(this,e,t,r,i,n,a,s,o,c,l,p,d)}async actionPrivateWallet(e,t,r,i,n,a,s,o,c,l=!1,p,d,u,k=!1){return $.hinkalPrivateWallet(this,e,t,r,i,n,a,s,o,c,l,p,d,u,k)}async approve(e,t,r,i,n,a=!1){return Y.hinkalApprove(this,e,t,r,i,n,a)}async hinkalInsideTransact(e,t,r,i,n,a,s,o,c,l=!1){return Z.hinkalInsideTransact(this,e,t,r,i,n,a,s,o,c,l)}async proxySwap(e,t,r,i,n,a,s,o,c=!1,l,p,d=!1){return h.isSolanaLike(this.getCurrentChainId())?ve.hinkalSolanaProxySwap(this,e,t,i,a,s,o,d):oe.hinkalProxySwap(this,e,t,r,i,n,a,s,o,c,l,p,d)}async proxyToPrivate(e,t,r,i,n,a,s,o=!1){return h.isSolanaLike(this.getCurrentChainId())?D.hinkalSolanaProxyShield(this,e[0],t[0],r,i,o):le.hinkalProxyToPrivate(this,e,t,i,n,a,r,s,o)}async proxySend(e,t,r,i,n,a,s,o=!1){if(h.isSolanaLike(this.getCurrentChainId()))return ke.hinkalSolanaProxySend(this,e[0],t[0],r,i,o);const c=ae.createTransaferEmporiumOpsBatch(this,e.map(d=>d.erc20TokenAddress),t,i),l=e.map((d,u)=>({token:d,amount:-1n*t[u]}));return await this.actionPrivateWallet([],[],[],c,l,r,n,a,void 0,void 0,void 0,s,void 0,o)}async multiSendPrivateRecipients(e,t,r){return ce.hinkalMultiSendPrivateRecipients(this,e,t,r)}areMerkleTreeUpdatesDisabled(){return this.disableMerkleTreeUpdates}updateMerkleTreeUpdates(e){this.disableMerkleTreeUpdates=e}}exports.Hinkal=Se;
@@ -103,7 +103,7 @@ class cr {
103
103
  generateProofRemotely;
104
104
  disableMerkleTreeUpdates;
105
105
  constructor(e) {
106
- this.userKeys = new y(void 0), this.merkleTreeHinkal = P.create(I, 0n), this.merkleTreeAccessToken = P.create(I, 0n), this.nullifiers = /* @__PURE__ */ new Set(), this.encryptedOutputs = [], this.approvals = /* @__PURE__ */ new Map(), this.generateProofRemotely = e?.generateProofRemotely ?? !1, this.utxoUtils = new J(), this.cacheDevice = X(e), this.disableMerkleTreeUpdates = e?.disableMerkleTreeUpdates ?? !1;
106
+ this.userKeys = new y(void 0), this.merkleTreeHinkal = P.create(I, 0n), this.merkleTreeAccessToken = P.create(I, 0n), this.nullifiers = /* @__PURE__ */ new Set(), this.encryptedOutputs = [], this.approvals = /* @__PURE__ */ new Map(), this.generateProofRemotely = e?.generateProofRemotely ?? !0, this.utxoUtils = new J(), this.cacheDevice = X(e), this.disableMerkleTreeUpdates = e?.disableMerkleTreeUpdates ?? !1;
107
107
  }
108
108
  async initProviderAdapter(e, t) {
109
109
  await this.updateProviderAdapter(t), this.providerAdapter?.initConnector(e);
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("../../constants/protocol.constants.cjs"),f=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),w=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),h=require("../../functions/web3/events/getShieldedBalance.cjs"),q=require("../../functions/web3/functionCalls/transactCallDirect.cjs"),C=require("../utxo/Utxo.cjs"),F=require("../../error-handling/error-codes.constants.cjs");require("../../types/circom-data.types.cjs");const I=require("../../types/ethereum-network.types.cjs"),M=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const R=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),_=require("../../functions/utils/addresses.cjs"),z=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),H=require("../../functions/utils/time.utils.cjs"),S=require("../../API/admin-calls.cjs"),U=require("../../functions/pre-transaction/constructAdminData.cjs"),K=async(e,a,t)=>{const{patchAccessTokenMerkleTree:o,kycRequired:r,hasAccessToken:l}=await z.shouldPatchAccessTokenMerkleTree(e,a,t),c=void 0,p=await e.getEthereumAddress(),i=await R.getSignatureDataForTransact(e.getCurrentChainId(),p,e.userKeys,r,l),n={externalActionId:0n,externalAddress:await e.getEthereumAddress(),externalActionMetadata:"0x00"};return{signatureData:i,externalActionData:n,contractTransaction:c,contractToApprove:c,patchAccessTokenMerkleTree:o}},O=async(e,a,t)=>{console.log("deposit 1");const o=a.map(s=>s.erc20TokenAddress),{externalActionData:r,contractTransaction:l,contractToApprove:c,patchAccessTokenMerkleTree:p,signatureData:i}=await K(e,o,t);console.log("deposit 2");const n=[...await h.addPaddingToUtxos(e,o,t)],A=`swapperM${t.length.toString()}x${n[0].length}x1`,d=[];console.log("deposit 3");const T=H.getCurrentTimeInSeconds().toString();for(let s=0;s<o.length;s+=1){const{outputUtxos:v}=f.outputUtxoProcessing(e.userKeys,n[s],t[s],T);d.push(v)}console.log("deposit 4");const{zkCallData:g,circomData:m,dimData:x}=await w.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,n,d,e.userKeys,A,r.externalActionId,r.externalAddress,r.externalActionMetadata,e.generateProofRemotely,P.zeroAddress,e.getCurrentChainId(),void 0,void 0,void 0,p,void 0,void 0,void 0,e.getContractWithFetcher(I.ContractType.HinkalHelperContract),i);console.log("deposit 5");const y=await q.transactCallDirect(e,t,a,g,m,x,c,l);console.log("deposit 6");const D=U.constructAdminData(M.AdminTransactionType.Onboarding,e.getCurrentChainId(),o,t,await e.getEthereumAddress());return S.emitTxPublicData(e.getCurrentChainId(),D),y},b=async(e,a,t,o)=>{const r=a.map(u=>u.erc20TokenAddress),[l,c,p]=o.split(",");if(!_.isValidPrivateAddress(o))throw Error(F.transactionErrorCodes.RECIPIENT_FORMAT_INCORRECT);const i=r.map(u=>[new C.Utxo({amount:0n,erc20TokenAddress:u,shieldedPrivateKey:e.userKeys.getShieldedPrivateKey()}),new C.Utxo({amount:0n,erc20TokenAddress:u,shieldedPrivateKey:e.userKeys.getShieldedPrivateKey()})]),n=`swapperM${t.length.toString()}x${i[0].length}x1`,A=r.map((u,E)=>[new C.Utxo({amount:t[E],erc20TokenAddress:u,randomization:BigInt(l),stealthAddress:c,encryptionKey:p})]),{externalActionData:d,contractTransaction:T,contractToApprove:g,patchAccessTokenMerkleTree:m}=await K(e,r,t),{zkCallData:x,circomData:y,dimData:D}=await w.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,i,A,e.userKeys,n,d.externalActionId,d.externalAddress,d.externalActionMetadata,e.generateProofRemotely,P.zeroAddress,e.getCurrentChainId(),void 0,void 0,void 0,m,void 0,void 0,void 0,e.getContractWithFetcher(I.ContractType.HinkalHelperContract)),s=await q.transactCallDirect(e,t,a,x,y,D,g,T),v=U.constructAdminData(M.AdminTransactionType.PaymentLink,e.getCurrentChainId(),r,t,await e.getEthereumAddress());return S.emitTxPublicData(e.getCurrentChainId(),v),s};exports.hinkalDeposit=O;exports.hinkalDepositForOther=b;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("../../constants/protocol.constants.cjs"),f=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),w=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),h=require("../../functions/web3/events/getShieldedBalance.cjs"),q=require("../../functions/web3/functionCalls/transactCallDirect.cjs"),C=require("../utxo/Utxo.cjs"),F=require("../../error-handling/error-codes.constants.cjs");require("../../types/circom-data.types.cjs");const I=require("../../types/ethereum-network.types.cjs"),M=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const R=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),_=require("../../functions/utils/addresses.cjs"),z=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),H=require("../../functions/utils/time.utils.cjs"),S=require("../../API/admin-calls.cjs"),U=require("../../functions/pre-transaction/constructAdminData.cjs"),K=async(t,s,e)=>{const{patchAccessTokenMerkleTree:o,kycRequired:r,hasAccessToken:A}=await z.shouldPatchAccessTokenMerkleTree(t,s,e),c=void 0,l=await t.getEthereumAddress(),i=await R.getSignatureDataForTransact(t.getCurrentChainId(),l,t.userKeys,r,A),n={externalActionId:0n,externalAddress:await t.getEthereumAddress(),externalActionMetadata:"0x00"};return{signatureData:i,externalActionData:n,contractTransaction:c,contractToApprove:c,patchAccessTokenMerkleTree:o}},O=async(t,s,e)=>{const o=s.map(a=>a.erc20TokenAddress),{externalActionData:r,contractTransaction:A,contractToApprove:c,patchAccessTokenMerkleTree:l,signatureData:i}=await K(t,o,e),n=[...await h.addPaddingToUtxos(t,o,e)],p=`swapperM${e.length.toString()}x${n[0].length}x1`,d=[],T=H.getCurrentTimeInSeconds().toString();for(let a=0;a<o.length;a+=1){const{outputUtxos:v}=f.outputUtxoProcessing(t.userKeys,n[a],e[a],T);d.push(v)}const{zkCallData:m,circomData:x,dimData:g}=await w.constructZkProof("v1x1",t.merkleTreeHinkal,t.merkleTreeAccessToken,n,d,t.userKeys,p,r.externalActionId,r.externalAddress,r.externalActionMetadata,t.generateProofRemotely,P.zeroAddress,t.getCurrentChainId(),void 0,void 0,void 0,l,void 0,void 0,void 0,t.getContractWithFetcher(I.ContractType.HinkalHelperContract),i),y=await q.transactCallDirect(t,e,s,m,x,g,c,A),D=U.constructAdminData(M.AdminTransactionType.Onboarding,t.getCurrentChainId(),o,e,await t.getEthereumAddress());return S.emitTxPublicData(t.getCurrentChainId(),D),y},b=async(t,s,e,o)=>{const r=s.map(u=>u.erc20TokenAddress),[A,c,l]=o.split(",");if(!_.isValidPrivateAddress(o))throw Error(F.transactionErrorCodes.RECIPIENT_FORMAT_INCORRECT);const i=r.map(u=>[new C.Utxo({amount:0n,erc20TokenAddress:u,shieldedPrivateKey:t.userKeys.getShieldedPrivateKey()}),new C.Utxo({amount:0n,erc20TokenAddress:u,shieldedPrivateKey:t.userKeys.getShieldedPrivateKey()})]),n=`swapperM${e.length.toString()}x${i[0].length}x1`,p=r.map((u,E)=>[new C.Utxo({amount:e[E],erc20TokenAddress:u,randomization:BigInt(A),stealthAddress:c,encryptionKey:l})]),{externalActionData:d,contractTransaction:T,contractToApprove:m,patchAccessTokenMerkleTree:x}=await K(t,r,e),{zkCallData:g,circomData:y,dimData:D}=await w.constructZkProof("v1x1",t.merkleTreeHinkal,t.merkleTreeAccessToken,i,p,t.userKeys,n,d.externalActionId,d.externalAddress,d.externalActionMetadata,t.generateProofRemotely,P.zeroAddress,t.getCurrentChainId(),void 0,void 0,void 0,x,void 0,void 0,void 0,t.getContractWithFetcher(I.ContractType.HinkalHelperContract)),a=await q.transactCallDirect(t,e,s,g,y,D,m,T),v=U.constructAdminData(M.AdminTransactionType.PaymentLink,t.getCurrentChainId(),r,e,await t.getEthereumAddress());return S.emitTxPublicData(t.getCurrentChainId(),v),a};exports.hinkalDeposit=O;exports.hinkalDepositForOther=b;
@@ -39,18 +39,12 @@ const S = async (t, s, e) => {
39
39
  patchAccessTokenMerkleTree: o
40
40
  };
41
41
  }, et = async (t, s, e) => {
42
- console.log("deposit 1");
43
- const o = s.map((a) => a.erc20TokenAddress), { externalActionData: r, contractTransaction: p, contractToApprove: c, patchAccessTokenMerkleTree: A, signatureData: i } = await S(t, o, e);
44
- console.log("deposit 2");
45
- const n = [...await H(t, o, e)], u = `swapperM${e.length.toString()}x${n[0].length}x1`, d = [];
46
- console.log("deposit 3");
47
- const l = $().toString();
42
+ const o = s.map((a) => a.erc20TokenAddress), { externalActionData: r, contractTransaction: p, contractToApprove: c, patchAccessTokenMerkleTree: A, signatureData: i } = await S(t, o, e), n = [...await H(t, o, e)], u = `swapperM${e.length.toString()}x${n[0].length}x1`, d = [], x = $().toString();
48
43
  for (let a = 0; a < o.length; a += 1) {
49
- const { outputUtxos: f } = R(t.userKeys, n[a], e[a], l);
44
+ const { outputUtxos: f } = R(t.userKeys, n[a], e[a], x);
50
45
  d.push(f);
51
46
  }
52
- console.log("deposit 4");
53
- const { zkCallData: g, circomData: x, dimData: T } = await C(
47
+ const { zkCallData: T, circomData: g, dimData: y } = await C(
54
48
  "v1x1",
55
49
  t.merkleTreeHinkal,
56
50
  t.merkleTreeAccessToken,
@@ -73,28 +67,24 @@ const S = async (t, s, e) => {
73
67
  void 0,
74
68
  t.getContractWithFetcher(I.HinkalHelperContract),
75
69
  i
76
- );
77
- console.log("deposit 5");
78
- const y = await P(
70
+ ), l = await P(
79
71
  t,
80
72
  e,
81
73
  // for volotile tokens: amountChanges != amountOfTokenToApprove
82
74
  s,
83
- g,
84
- x,
85
75
  T,
76
+ g,
77
+ y,
86
78
  c,
87
79
  p
88
- );
89
- console.log("deposit 6");
90
- const v = E(
80
+ ), v = E(
91
81
  K.Onboarding,
92
82
  t.getCurrentChainId(),
93
83
  o,
94
84
  e,
95
85
  await t.getEthereumAddress()
96
86
  );
97
- return M(t.getCurrentChainId(), v), y;
87
+ return M(t.getCurrentChainId(), v), l;
98
88
  }, rt = async (t, s, e, o) => {
99
89
  const r = s.map((m) => m.erc20TokenAddress), [p, c, A] = o.split(",");
100
90
  if (!N(o))
@@ -110,7 +100,7 @@ const S = async (t, s, e) => {
110
100
  stealthAddress: c,
111
101
  encryptionKey: A
112
102
  })
113
- ]), { externalActionData: d, contractTransaction: l, contractToApprove: g, patchAccessTokenMerkleTree: x } = await S(t, r, e), { zkCallData: T, circomData: y, dimData: v } = await C(
103
+ ]), { externalActionData: d, contractTransaction: x, contractToApprove: T, patchAccessTokenMerkleTree: g } = await S(t, r, e), { zkCallData: y, circomData: l, dimData: v } = await C(
114
104
  "v1x1",
115
105
  t.merkleTreeHinkal,
116
106
  t.merkleTreeAccessToken,
@@ -127,7 +117,7 @@ const S = async (t, s, e) => {
127
117
  void 0,
128
118
  void 0,
129
119
  void 0,
130
- x,
120
+ g,
131
121
  void 0,
132
122
  void 0,
133
123
  void 0,
@@ -136,11 +126,11 @@ const S = async (t, s, e) => {
136
126
  t,
137
127
  e,
138
128
  s,
139
- T,
140
129
  y,
130
+ l,
141
131
  v,
142
- g,
143
- l
132
+ T,
133
+ x
144
134
  ), f = E(
145
135
  K.PaymentLink,
146
136
  t.getCurrentChainId(),
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("../../error-handling/error-codes.constants.cjs"),L=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),M=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),H=require("../../functions/web3/events/getShieldedBalance.cjs"),K=require("../../functions/web3/functionCalls/estimateGasRelayer.cjs"),N=require("../../functions/web3/functionCalls/transactCallRelayer.cjs"),W=require("../../functions/pre-transaction/getFeeStructure.cjs"),B=require("../../functions/pre-transaction/merge-with-fee-structure.cjs"),b=require("../../types/external-action.types.cjs"),G=require("../../types/hinkal.types.cjs"),O=require("../../functions/pre-transaction/outputApprovalDataProcessing.cjs"),V=require("../../types/ethereum-network.types.cjs"),Z=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),$=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),j=require("../../functions/pre-transaction/getExternalSwapAddress.cjs"),z=require("../../functions/utils/time.utils.cjs"),Y=require("../../constants/protocol.constants.cjs");require("../../types/circom-data.types.cjs");require("../../types/activities.types.cjs");require("../../constants/server.constants.cjs");require("../../constants/chains.constants.cjs");require("../../constants/vite.constants.cjs");require("../http/HttpClient.cjs");require("axios");require("ethers");require("../../constants/token-data/index.cjs");require("../../API/getServerURL.cjs");require("circomlibjs-hinkal-fork");require("libsodium-wrappers");require("process");require("buffer");require("../../constants/save-depths.cjs");require("../../constants/reorg-depths.constants.cjs");require("../../functions/utils/mutexes.utils.cjs");require("@coral-xyz/anchor");require("@solana/web3.js");require("../crypto-keys/keys.cjs");const J=require("../../functions/pre-transaction/constructAdminData.cjs");require("@solana/spl-token");const Q=async(e,c,t,i,A,C,k,x,l=!1,y=!1)=>{console.log("hinkalSwap 1");const o=c.map(r=>r.erc20TokenAddress);console.log("hinkalSwap 2");const u=await e.getEthereumAddress();console.log("hinkalSwap 3");const g=k??await W.getFeeStructure(e.getCurrentChainId(),C,o,b.ExternalActionId.Transact,void 0,Y.HINKAL_SWAP_VARIABLE_RATE);B.mergeWithFeeStructure(e.getCurrentChainId(),o,t,g),console.log("hinkalSwap 4");const T=j.getExternalSwapAddress(e,i),s={externalActionId:i,externalAddress:T,externalActionMetadata:A};console.log("hinkalSwap 5");const a=[...await H.addPaddingToUtxos(e,o,t)],m=`swapperM${t.length.toString()}x${a[0].length}x1`;console.log("hinkalSwap 6");const f=[!1,!0,!1].slice(0,t.length),p=[];console.log("hinkalSwap 7");const n=G.defaultHinkalLogicArgs(t.length,e.userKeys);console.log("hinkalSwap 8");const v=z.getCurrentTimeInSeconds().toString();for(let r=0;r<o.length;r+=1){console.log("hinkalSwap 9",{i:r});const{outputUtxos:U}=L.outputUtxoProcessing(e.userKeys,a[r],t[r],v,void 0,!1);console.log("hinkalSwap 10",{i:r}),p.push(U);const{useApprovalUtxoData:h}=O.outputApprovalDataProcessing(e,a[r],t[r]);console.log("hinkalSwap 11",{i:r}),h&&(n.useApprovalUtxoData[r]=h,n.doPreTxApproval=!0),console.log("hinkalSwap 12",{i:r})}console.log("hinkalSwap 13");const d=await e.getRandomRelay(!l);if(!d)throw Error(F.transactionErrorCodes.RELAYER_NOT_AVAILABLE);console.log("hinkalSwap 14");const{patchAccessTokenMerkleTree:D,kycRequired:P,hasAccessToken:R}=await Z.shouldPatchAccessTokenMerkleTree(e,o,t);console.log("hinkalSwap 15");const E=await $.getSignatureDataForTransact(e.getCurrentChainId(),u,e.userKeys,P,R);console.log("hinkalSwap 16");const{zkCallData:q,circomData:S,dimData:w}=await M.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,a,p,e.userKeys,m,s.externalActionId,s.externalAddress,s.externalActionMetadata,e.generateProofRemotely,d,e.getCurrentChainId(),f,void 0,void 0,D,n,void 0,g,e.getContractWithFetcher(V.ContractType.HinkalHelperContract),E);if(console.log("hinkalSwap 17"),l)return await K.estimateGasRelayer(e,q,w,S);console.log("hinkalSwap 18");const I=J.constructAdminData(x,e.getCurrentChainId(),o,t,u,c);console.log("hinkalSwap 19");const _=await N.transactCallRelayer(e.getCurrentChainId(),q,w,S,y,void 0,void 0,I);return console.log("hinkalSwap 20"),_};exports.hinkalSwap=Q;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const F=require("../../error-handling/error-codes.constants.cjs"),L=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),M=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),H=require("../../functions/web3/events/getShieldedBalance.cjs"),K=require("../../functions/web3/functionCalls/estimateGasRelayer.cjs"),N=require("../../functions/web3/functionCalls/transactCallRelayer.cjs"),W=require("../../functions/pre-transaction/getFeeStructure.cjs"),B=require("../../functions/pre-transaction/merge-with-fee-structure.cjs"),b=require("../../types/external-action.types.cjs"),k=require("../../types/hinkal.types.cjs"),G=require("../../functions/pre-transaction/outputApprovalDataProcessing.cjs"),O=require("../../types/ethereum-network.types.cjs"),V=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),Z=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),$=require("../../functions/pre-transaction/getExternalSwapAddress.cjs"),j=require("../../functions/utils/time.utils.cjs"),z=require("../../constants/protocol.constants.cjs");require("../../types/circom-data.types.cjs");require("../../types/activities.types.cjs");require("../../constants/server.constants.cjs");require("../../constants/chains.constants.cjs");require("../../constants/vite.constants.cjs");require("../http/HttpClient.cjs");require("axios");require("ethers");require("../../constants/token-data/index.cjs");require("../../API/getServerURL.cjs");require("circomlibjs-hinkal-fork");require("libsodium-wrappers");require("process");require("buffer");require("../../constants/save-depths.cjs");require("../../constants/reorg-depths.constants.cjs");require("../../functions/utils/mutexes.utils.cjs");require("@coral-xyz/anchor");require("@solana/web3.js");require("../crypto-keys/keys.cjs");const Y=require("../../functions/pre-transaction/constructAdminData.cjs");require("@solana/spl-token");const J=async(e,c,t,i,x,T,S,m,u=!1,w=!1)=>{const s=c.map(r=>r.erc20TokenAddress),d=await e.getEthereumAddress(),g=S??await W.getFeeStructure(e.getCurrentChainId(),T,s,b.ExternalActionId.Transact,void 0,z.HINKAL_SWAP_VARIABLE_RATE);B.mergeWithFeeStructure(e.getCurrentChainId(),s,t,g);const f=$.getExternalSwapAddress(e,i),o={externalActionId:i,externalAddress:f,externalActionMetadata:x},a=[...await H.addPaddingToUtxos(e,s,t)],v=`swapperM${t.length.toString()}x${a[0].length}x1`,D=[!1,!0,!1].slice(0,t.length),q=[],n=k.defaultHinkalLogicArgs(t.length,e.userKeys),R=j.getCurrentTimeInSeconds().toString();for(let r=0;r<s.length;r+=1){const{outputUtxos:U}=L.outputUtxoProcessing(e.userKeys,a[r],t[r],R,void 0,!1);q.push(U);const{useApprovalUtxoData:y}=G.outputApprovalDataProcessing(e,a[r],t[r]);y&&(n.useApprovalUtxoData[r]=y,n.doPreTxApproval=!0)}const l=await e.getRandomRelay(!u);if(!l)throw Error(F.transactionErrorCodes.RELAYER_NOT_AVAILABLE);const{patchAccessTokenMerkleTree:P,kycRequired:h,hasAccessToken:E}=await V.shouldPatchAccessTokenMerkleTree(e,s,t),I=await Z.getSignatureDataForTransact(e.getCurrentChainId(),d,e.userKeys,h,E),{zkCallData:p,circomData:A,dimData:C}=await M.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,a,q,e.userKeys,v,o.externalActionId,o.externalAddress,o.externalActionMetadata,e.generateProofRemotely,l,e.getCurrentChainId(),D,void 0,void 0,P,n,void 0,g,e.getContractWithFetcher(O.ContractType.HinkalHelperContract),I);if(u)return await K.estimateGasRelayer(e,p,C,A);const _=Y.constructAdminData(m,e.getCurrentChainId(),s,t,d,c);return await N.transactCallRelayer(e.getCurrentChainId(),p,C,A,w,void 0,void 0,_)};exports.hinkalSwap=J;
@@ -37,115 +37,92 @@ import "@solana/web3.js";
37
37
  import "../crypto-keys/keys.mjs";
38
38
  import { constructAdminData as J } from "../../functions/pre-transaction/constructAdminData.mjs";
39
39
  import "@solana/spl-token";
40
- const No = async (o, s, r, p, h, A, C, x, c = !1, T = !1) => {
41
- console.log("hinkalSwap 1");
42
- const e = s.map((t) => t.erc20TokenAddress);
43
- console.log("hinkalSwap 2");
44
- const l = await o.getEthereumAddress();
45
- console.log("hinkalSwap 3");
46
- const m = C ?? await B(
47
- o.getCurrentChainId(),
48
- A,
49
- e,
40
+ const Nt = async (t, m, e, p, l, T, y, w, c = !1, v = !1) => {
41
+ const o = m.map((r) => r.erc20TokenAddress), n = await t.getEthereumAddress(), d = y ?? await B(
42
+ t.getCurrentChainId(),
43
+ T,
44
+ o,
50
45
  $.Transact,
51
46
  void 0,
52
47
  G
53
48
  );
54
- V(o.getCurrentChainId(), e, r, m), console.log("hinkalSwap 4");
55
- const k = b(o, p), i = {
49
+ V(t.getCurrentChainId(), o, e, d);
50
+ const R = b(t, p), s = {
56
51
  externalActionId: p,
57
- externalAddress: k,
58
- externalActionMetadata: h
59
- };
60
- console.log("hinkalSwap 5");
61
- const a = [...await F(o, e, r)], y = `swapperM${r.length.toString()}x${a[0].length}x1`;
62
- console.log("hinkalSwap 6");
63
- const v = [!1, !0, !1].slice(0, r.length), g = [];
64
- console.log("hinkalSwap 7");
65
- const n = q(r.length, o.userKeys);
66
- console.log("hinkalSwap 8");
67
- const D = j().toString();
68
- for (let t = 0; t < e.length; t += 1) {
69
- console.log("hinkalSwap 9", { i: t });
52
+ externalAddress: R,
53
+ externalActionMetadata: l
54
+ }, a = [...await F(t, o, e)], D = `swapperM${e.length.toString()}x${a[0].length}x1`, E = [!1, !0, !1].slice(0, e.length), u = [], i = q(e.length, t.userKeys), I = j().toString();
55
+ for (let r = 0; r < o.length; r += 1) {
70
56
  const { outputUtxos: H } = M(
71
- o.userKeys,
72
- a[t],
73
- r[t],
74
- D,
57
+ t.userKeys,
58
+ a[r],
59
+ e[r],
60
+ I,
75
61
  void 0,
76
62
  !1
77
63
  );
78
- console.log("hinkalSwap 10", { i: t }), g.push(H);
79
- const { useApprovalUtxoData: S } = z(o, a[t], r[t]);
80
- console.log("hinkalSwap 11", { i: t }), S && (n.useApprovalUtxoData[t] = S, n.doPreTxApproval = !0), console.log("hinkalSwap 12", { i: t });
64
+ u.push(H);
65
+ const { useApprovalUtxoData: x } = z(t, a[r], e[r]);
66
+ x && (i.useApprovalUtxoData[r] = x, i.doPreTxApproval = !0);
81
67
  }
82
- console.log("hinkalSwap 13");
83
- const d = await o.getRandomRelay(!c);
84
- if (!d)
68
+ const g = await t.getRandomRelay(!c);
69
+ if (!g)
85
70
  throw Error(K.RELAYER_NOT_AVAILABLE);
86
- console.log("hinkalSwap 14");
87
- const { patchAccessTokenMerkleTree: E, kycRequired: I, hasAccessToken: R } = await Y(
71
+ const { patchAccessTokenMerkleTree: S, kycRequired: P, hasAccessToken: L } = await Y(
72
+ t,
88
73
  o,
89
- e,
90
- r
91
- );
92
- console.log("hinkalSwap 15");
93
- const P = await Z(
94
- o.getCurrentChainId(),
95
- l,
96
- o.userKeys,
97
- I,
98
- R
99
- );
100
- console.log("hinkalSwap 16");
101
- const { zkCallData: u, circomData: w, dimData: f } = await _(
74
+ e
75
+ ), U = await Z(
76
+ t.getCurrentChainId(),
77
+ n,
78
+ t.userKeys,
79
+ P,
80
+ L
81
+ ), { zkCallData: f, circomData: A, dimData: C } = await _(
102
82
  "v1x1",
103
- o.merkleTreeHinkal,
104
- o.merkleTreeAccessToken,
83
+ t.merkleTreeHinkal,
84
+ t.merkleTreeAccessToken,
105
85
  a,
86
+ u,
87
+ t.userKeys,
88
+ D,
89
+ s.externalActionId,
90
+ s.externalAddress,
91
+ s.externalActionMetadata,
92
+ t.generateProofRemotely,
106
93
  g,
107
- o.userKeys,
108
- y,
109
- i.externalActionId,
110
- i.externalAddress,
111
- i.externalActionMetadata,
112
- o.generateProofRemotely,
113
- d,
114
- o.getCurrentChainId(),
115
- v,
94
+ t.getCurrentChainId(),
95
+ E,
116
96
  void 0,
117
97
  void 0,
118
- E,
119
- n,
98
+ S,
99
+ i,
120
100
  void 0,
121
- m,
122
- o.getContractWithFetcher(O.HinkalHelperContract),
123
- P
101
+ d,
102
+ t.getContractWithFetcher(O.HinkalHelperContract),
103
+ U
124
104
  );
125
- if (console.log("hinkalSwap 17"), c)
126
- return await N(o, u, f, w);
127
- console.log("hinkalSwap 18");
128
- const L = J(
129
- x,
130
- o.getCurrentChainId(),
105
+ if (c)
106
+ return await N(t, f, C, A);
107
+ const h = J(
108
+ w,
109
+ t.getCurrentChainId(),
110
+ o,
131
111
  e,
132
- r,
133
- l,
134
- s
112
+ n,
113
+ m
135
114
  );
136
- console.log("hinkalSwap 19");
137
- const U = await W(
138
- o.getCurrentChainId(),
139
- u,
115
+ return await W(
116
+ t.getCurrentChainId(),
140
117
  f,
141
- w,
142
- T,
118
+ C,
119
+ A,
120
+ v,
143
121
  void 0,
144
122
  void 0,
145
- L
123
+ h
146
124
  );
147
- return console.log("hinkalSwap 20"), U;
148
125
  };
149
126
  export {
150
- No as hinkalSwap
127
+ Nt as hinkalSwap
151
128
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../../constants/protocol.constants.cjs"),h=require("../../crypto/poseidon.cjs"),A=require("../../functions/web3/etherFunctions.cjs"),l=require("../crypto-keys/keys.cjs"),p=require("../../functions/utils/time.utils.cjs"),g=require("../../constants/chains.constants.cjs");class n{amount;erc20TokenAddress;mintAddress;timeStamp;tokenId;shieldedPrivateKey;randomization;stealthAddress;encryptionKey;commitment;nullifier;isBlocked;constructor({amount:t,erc20TokenAddress:e,mintAddress:o,timeStamp:i,tokenId:r,shieldedPrivateKey:s,randomization:a,stealthAddress:c,encryptionKey:u,commitment:y=void 0,nullifier:f=void 0,isBlocked:k=!1,enableLogs:m=!1}){this.amount=t,this.erc20TokenAddress=e,this.mintAddress=o,this.timeStamp=i??p.getCurrentTimeInSeconds().toString(),this.tokenId=r??0,this.shieldedPrivateKey=s,m&&console.log({randomization:a}),this.randomization=a??n.findCorrectRandomization(A.randomBigInt(31),s),m&&console.log("randomization assigned"),this.stealthAddress=c,this.encryptionKey=u,this.commitment=y,this.nullifier=f,this.isBlocked=k}static createFrom(t,e){return new n({...t.getConstructableParams(),nullifier:void 0,commitment:void 0,...e})}getConstructableParams(){return{amount:this.amount,erc20TokenAddress:this.erc20TokenAddress,mintAddress:this.mintAddress,timeStamp:this.timeStamp,shieldedPrivateKey:this.shieldedPrivateKey,randomization:this.randomization,stealthAddress:this.stealthAddress,encryptionKey:this.encryptionKey,tokenId:this.tokenId,commitment:this.commitment,nullifier:this.nullifier,isBlocked:this.isBlocked}}getBasicUtxoParams(){return{amount:this.amount,erc20TokenAddress:this.erc20TokenAddress,mintAddress:this.mintAddress,timeStamp:this.timeStamp,randomization:this.randomization,stealthAddress:this.stealthAddress,tokenId:this.tokenId,commitment:this.commitment,nullifier:this.nullifier,isBlocked:this.isBlocked}}getCommitment(){if(!this.commitment){const t=[this.amount,this.erc20TokenAddress,BigInt(this.getStealthAddress()),this.timeStamp];this.tokenId>0&&t.push(this.tokenId.toString()),this.commitment=h.poseidonHash(...t)}return this.commitment}getNullifier(){if(!this.nullifier){if(!this.shieldedPrivateKey)throw new Error("No Nullifiers if private key is not provided");const t=h.poseidonHash(this.shieldedPrivateKey,this.getCommitment());this.nullifier=h.poseidonHash(this.commitment,t)}return this.nullifier}getStealthAddress(){if(!this.stealthAddress){if(!this.shieldedPrivateKey)throw Error("No stealth address in UTXO if private key is not provided");const t=l.UserKeys.getStealthAddress(this.randomization,this.shieldedPrivateKey);this.stealthAddress=t}return this.stealthAddress}getEncryptionKey(){if(!this.shieldedPrivateKey){if(!this.encryptionKey)throw Error("No encryption key provided in UTXO");return this.encryptionKey}return l.UserKeys.getEncryptionKeyPair(this.shieldedPrivateKey).publicKey}static findCorrectRandomization(t,e){if(console.log("initialRandomization",t,e),!e)throw Error("No Private Shielded Key Provided");const o=BigInt(e)%d.CIRCOM_P;let i,r,s=0n;do i=t*10n**s%d.CIRCOM_P,r=i*o%d.CIRCOM_P,s+=1n;while(r>=2n**253n||i>=2n**253n);return i}getTokenAddress(t){const e=g.isSolanaLike(t)?this.mintAddress:this.erc20TokenAddress;if(!e)throw new Error("No token address provided");return e}}exports.Utxo=n;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("../../constants/protocol.constants.cjs"),h=require("../../crypto/poseidon.cjs"),A=require("../../functions/web3/etherFunctions.cjs"),a=require("../crypto-keys/keys.cjs"),p=require("../../functions/utils/time.utils.cjs"),f=require("../../constants/chains.constants.cjs");class n{amount;erc20TokenAddress;mintAddress;timeStamp;tokenId;shieldedPrivateKey;randomization;stealthAddress;encryptionKey;commitment;nullifier;isBlocked;constructor({amount:t,erc20TokenAddress:e,mintAddress:o,timeStamp:i,tokenId:r,shieldedPrivateKey:s,randomization:m,stealthAddress:l,encryptionKey:c,commitment:u=void 0,nullifier:y=void 0,isBlocked:k=!1}){this.amount=t,this.erc20TokenAddress=e,this.mintAddress=o,this.timeStamp=i??p.getCurrentTimeInSeconds().toString(),this.tokenId=r??0,this.shieldedPrivateKey=s,this.randomization=m??n.findCorrectRandomization(A.randomBigInt(31),s),this.stealthAddress=l,this.encryptionKey=c,this.commitment=u,this.nullifier=y,this.isBlocked=k}static createFrom(t,e){return new n({...t.getConstructableParams(),nullifier:void 0,commitment:void 0,...e})}getConstructableParams(){return{amount:this.amount,erc20TokenAddress:this.erc20TokenAddress,mintAddress:this.mintAddress,timeStamp:this.timeStamp,shieldedPrivateKey:this.shieldedPrivateKey,randomization:this.randomization,stealthAddress:this.stealthAddress,encryptionKey:this.encryptionKey,tokenId:this.tokenId,commitment:this.commitment,nullifier:this.nullifier,isBlocked:this.isBlocked}}getBasicUtxoParams(){return{amount:this.amount,erc20TokenAddress:this.erc20TokenAddress,mintAddress:this.mintAddress,timeStamp:this.timeStamp,randomization:this.randomization,stealthAddress:this.stealthAddress,tokenId:this.tokenId,commitment:this.commitment,nullifier:this.nullifier,isBlocked:this.isBlocked}}getCommitment(){if(!this.commitment){const t=[this.amount,this.erc20TokenAddress,BigInt(this.getStealthAddress()),this.timeStamp];this.tokenId>0&&t.push(this.tokenId.toString()),this.commitment=h.poseidonHash(...t)}return this.commitment}getNullifier(){if(!this.nullifier){if(!this.shieldedPrivateKey)throw new Error("No Nullifiers if private key is not provided");const t=h.poseidonHash(this.shieldedPrivateKey,this.getCommitment());this.nullifier=h.poseidonHash(this.commitment,t)}return this.nullifier}getStealthAddress(){if(!this.stealthAddress){if(!this.shieldedPrivateKey)throw Error("No stealth address in UTXO if private key is not provided");const t=a.UserKeys.getStealthAddress(this.randomization,this.shieldedPrivateKey);this.stealthAddress=t}return this.stealthAddress}getEncryptionKey(){if(!this.shieldedPrivateKey){if(!this.encryptionKey)throw Error("No encryption key provided in UTXO");return this.encryptionKey}return a.UserKeys.getEncryptionKeyPair(this.shieldedPrivateKey).publicKey}static findCorrectRandomization(t,e){if(!e)throw Error("No Private Shielded Key Provided");const o=BigInt(e)%d.CIRCOM_P;let i,r,s=0n;do i=t*10n**s%d.CIRCOM_P,r=i*o%d.CIRCOM_P,s+=1n;while(r>=2n**253n||i>=2n**253n);return i}getTokenAddress(t){const e=f.isSolanaLike(t)?this.mintAddress:this.erc20TokenAddress;if(!e)throw new Error("No token address provided");return e}}exports.Utxo=n;
@@ -11,7 +11,6 @@ export type IUtxoConstructor<T = bigint> = {
11
11
  isBlocked?: boolean;
12
12
  commitment?: string;
13
13
  nullifier?: string;
14
- enableLogs?: boolean;
15
14
  };
16
15
  /**
17
16
  * UTXO class for transactions
@@ -42,7 +41,7 @@ export declare class Utxo {
42
41
  * @param commitment [optional] commitment value if already computed
43
42
  * @param nullifier [optional] nullifier value if already computed
44
43
  */
45
- constructor({ amount, erc20TokenAddress, mintAddress, timeStamp, tokenId, shieldedPrivateKey, randomization, stealthAddress, encryptionKey, commitment, nullifier, isBlocked, enableLogs, }: IUtxoConstructor);
44
+ constructor({ amount, erc20TokenAddress, mintAddress, timeStamp, tokenId, shieldedPrivateKey, randomization, stealthAddress, encryptionKey, commitment, nullifier, isBlocked, }: IUtxoConstructor);
46
45
  static createFrom(utxoToCreateFrom: Utxo, patch: Partial<IUtxoConstructor>): Utxo;
47
46
  getConstructableParams(): IUtxoConstructor;
48
47
  getBasicUtxoParams(): IUtxoConstructor;
@@ -1,9 +1,9 @@
1
1
  import { CIRCOM_P as o } from "../../constants/protocol.constants.mjs";
2
2
  import { poseidonHash as d } from "../../crypto/poseidon.mjs";
3
- import { randomBigInt as A } from "../../functions/web3/etherFunctions.mjs";
4
- import { UserKeys as l } from "../crypto-keys/keys.mjs";
5
- import { getCurrentTimeInSeconds as k } from "../../functions/utils/time.utils.mjs";
6
- import { isSolanaLike as g } from "../../constants/chains.constants.mjs";
3
+ import { randomBigInt as y } from "../../functions/web3/etherFunctions.mjs";
4
+ import { UserKeys as m } from "../crypto-keys/keys.mjs";
5
+ import { getCurrentTimeInSeconds as A } from "../../functions/utils/time.utils.mjs";
6
+ import { isSolanaLike as k } from "../../constants/chains.constants.mjs";
7
7
  class h {
8
8
  amount;
9
9
  erc20TokenAddress;
@@ -41,15 +41,14 @@ class h {
41
41
  timeStamp: i,
42
42
  tokenId: r,
43
43
  shieldedPrivateKey: s,
44
- randomization: m,
45
- stealthAddress: c,
46
- encryptionKey: u,
47
- commitment: f = void 0,
48
- nullifier: p = void 0,
49
- isBlocked: y = !1,
50
- enableLogs: a = !1
44
+ randomization: a,
45
+ stealthAddress: l,
46
+ encryptionKey: c,
47
+ commitment: u = void 0,
48
+ nullifier: f = void 0,
49
+ isBlocked: p = !1
51
50
  }) {
52
- this.amount = t, this.erc20TokenAddress = e, this.mintAddress = n, this.timeStamp = i ?? k().toString(), this.tokenId = r ?? 0, this.shieldedPrivateKey = s, a && console.log({ randomization: m }), this.randomization = m ?? h.findCorrectRandomization(A(31), s), a && console.log("randomization assigned"), this.stealthAddress = c, this.encryptionKey = u, this.commitment = f, this.nullifier = p, this.isBlocked = y;
51
+ this.amount = t, this.erc20TokenAddress = e, this.mintAddress = n, this.timeStamp = i ?? A().toString(), this.tokenId = r ?? 0, this.shieldedPrivateKey = s, this.randomization = a ?? h.findCorrectRandomization(y(31), s), this.stealthAddress = l, this.encryptionKey = c, this.commitment = u, this.nullifier = f, this.isBlocked = p;
53
52
  }
54
53
  static createFrom(t, e) {
55
54
  return new h({
@@ -118,7 +117,7 @@ class h {
118
117
  if (!this.stealthAddress) {
119
118
  if (!this.shieldedPrivateKey)
120
119
  throw Error("No stealth address in UTXO if private key is not provided");
121
- const t = l.getStealthAddress(this.randomization, this.shieldedPrivateKey);
120
+ const t = m.getStealthAddress(this.randomization, this.shieldedPrivateKey);
122
121
  this.stealthAddress = t;
123
122
  }
124
123
  return this.stealthAddress;
@@ -129,10 +128,10 @@ class h {
129
128
  throw Error("No encryption key provided in UTXO");
130
129
  return this.encryptionKey;
131
130
  }
132
- return l.getEncryptionKeyPair(this.shieldedPrivateKey).publicKey;
131
+ return m.getEncryptionKeyPair(this.shieldedPrivateKey).publicKey;
133
132
  }
134
133
  static findCorrectRandomization(t, e) {
135
- if (console.log("initialRandomization", t, e), !e)
134
+ if (!e)
136
135
  throw Error("No Private Shielded Key Provided");
137
136
  const n = BigInt(e) % o;
138
137
  let i, r, s = 0n;
@@ -142,7 +141,7 @@ class h {
142
141
  return i;
143
142
  }
144
143
  getTokenAddress(t) {
145
- const e = g(t) ? this.mintAddress : this.erc20TokenAddress;
144
+ const e = k(t) ? this.mintAddress : this.erc20TokenAddress;
146
145
  if (!e)
147
146
  throw new Error("No token address provided");
148
147
  return e;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("../../error-handling/error-codes.constants.cjs"),A=require("../../constants/conversion.constants.cjs"),I=require("../../types/hinkal.types.cjs"),T=require("../utils/processUseApprovalUtxoData.cjs"),E=require("../utils/amounts.utils.cjs"),P=require("../utils/caseInsensitive.utils.cjs"),C=(l,i,n,D,u)=>{if(console.log("outputApprovalDataProcessing 1",{inputUtxos:i,amountChange:n}),u&&u>0)throw new Error(O.transactionErrorCodes.INSUFFICIENT_FUNDS);console.log("outputApprovalDataProcessing 2");const p=E.countTotalAmountInUtxos(i);console.log("outputApprovalDataProcessing 3");const{erc20TokenAddress:d}=i[0];console.log("outputApprovalDataProcessing 4",{erc20TokenAddress:d});const c=l.getApprovedUtxosForToken(d).filter(r=>!P.caseInsensitiveEqual(r.interactionAddress,D));console.log("outputApprovalDataProcessing 5",{relevantApprovedUtxos:c});const o=I.defaultUseApprovalUTXOData(A.APPROVED_UTXO_CONVERSION_COUNT,0n);if(console.log("outputApprovalDataProcessing 6",{useApprovalUtxoData:o}),n<0n&&p+n<0n){let r=-(p+n);for(let t=0;t<Math.min(c.length,A.APPROVED_UTXO_CONVERSION_COUNT)&&r!==0n;t+=1){const a=c[t],v=a.amount>=r?-r:-a.amount;r+=v,o.approvalChanges[t]=v,o.externalApprovalAddresses[t]=a.interactionAddress,o.conversionInHinkalAddress[t]=a.inHinkalAddress}if(r!==0n)throw new Error(O.transactionErrorCodes.INSUFFICIENT_FUNDS)}return{useApprovalUtxoData:T.isUseApprovalDataEmpty(o)?void 0:o}},f=(l,i,n,D,u,p)=>{if(p&&p>0)throw new Error(O.transactionErrorCodes.INSUFFICIENT_FUNDS);const d=E.countTotalAmountInUtxos(i),{erc20TokenAddress:c}=i[0],o=I.defaultUseApprovalUTXOData(A.APPROVED_UTXO_CONVERSION_COUNT,0n),r=l.userKeys.getInHinkalAddress(n),t=l.getApprovedUtxosForToken(c).sort((e,s)=>e.inHinkalAddress===r?-1:s.inHinkalAddress===r?1:e.amount===s.amount?0:e.amount<s.amount?-1:1),a=t[0]?.inHinkalAddress===r,v=a?t[0].amount:0n,_=D-v;o.approvalChanges[0]=_,o.externalApprovalAddresses[0]=n,o.conversionInHinkalAddress[0]=l.userKeys.getInHinkalAddress(n);const g=a?1:0,U=g===0?1:0;let N=u;for(let e=g;e<Math.min(A.APPROVED_UTXO_CONVERSION_COUNT,t.length)&&!(e+U>=A.APPROVED_UTXO_CONVERSION_COUNT);e+=1){const s=t[e];N+=s.amount,o.approvalChanges[e+U]=-s.amount,o.externalApprovalAddresses[e+U]=s.interactionAddress,o.conversionInHinkalAddress[e+U]=s.inHinkalAddress}if(d+N<0n)throw new Error(O.transactionErrorCodes.INSUFFICIENT_FUNDS);return{useApprovalUtxoData:o,deltaAmountOverride:N}};exports.outputApprovalDataProcessing=C;exports.outputApprovalDataProcessingForHinkalApprove=f;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("../../error-handling/error-codes.constants.cjs"),p=require("../../constants/conversion.constants.cjs"),_=require("../../types/hinkal.types.cjs"),D=require("../utils/processUseApprovalUtxoData.cjs"),T=require("../utils/amounts.utils.cjs"),f=require("../utils/caseInsensitive.utils.cjs"),m=(i,d,s,O,A)=>{if(A&&A>0)throw new Error(U.transactionErrorCodes.INSUFFICIENT_FUNDS);const l=T.countTotalAmountInUtxos(d),{erc20TokenAddress:N}=d[0],c=i.getApprovedUtxosForToken(N).filter(n=>!f.caseInsensitiveEqual(n.interactionAddress,O)),r=_.defaultUseApprovalUTXOData(p.APPROVED_UTXO_CONVERSION_COUNT,0n);if(s<0n&&l+s<0n){let n=-(l+s);for(let t=0;t<Math.min(c.length,p.APPROVED_UTXO_CONVERSION_COUNT)&&n!==0n;t+=1){const a=c[t],u=a.amount>=n?-n:-a.amount;n+=u,r.approvalChanges[t]=u,r.externalApprovalAddresses[t]=a.interactionAddress,r.conversionInHinkalAddress[t]=a.inHinkalAddress}if(n!==0n)throw new Error(U.transactionErrorCodes.INSUFFICIENT_FUNDS)}return{useApprovalUtxoData:D.isUseApprovalDataEmpty(r)?void 0:r}},k=(i,d,s,O,A,l)=>{if(l&&l>0)throw new Error(U.transactionErrorCodes.INSUFFICIENT_FUNDS);const N=T.countTotalAmountInUtxos(d),{erc20TokenAddress:c}=d[0],r=_.defaultUseApprovalUTXOData(p.APPROVED_UTXO_CONVERSION_COUNT,0n),n=i.userKeys.getInHinkalAddress(s),t=i.getApprovedUtxosForToken(c).sort((e,o)=>e.inHinkalAddress===n?-1:o.inHinkalAddress===n?1:e.amount===o.amount?0:e.amount<o.amount?-1:1),a=t[0]?.inHinkalAddress===n,u=a?t[0].amount:0n,C=O-u;r.approvalChanges[0]=C,r.externalApprovalAddresses[0]=s,r.conversionInHinkalAddress[0]=i.userKeys.getInHinkalAddress(s);const E=a?1:0,v=E===0?1:0;let I=A;for(let e=E;e<Math.min(p.APPROVED_UTXO_CONVERSION_COUNT,t.length)&&!(e+v>=p.APPROVED_UTXO_CONVERSION_COUNT);e+=1){const o=t[e];I+=o.amount,r.approvalChanges[e+v]=-o.amount,r.externalApprovalAddresses[e+v]=o.interactionAddress,r.conversionInHinkalAddress[e+v]=o.inHinkalAddress}if(N+I<0n)throw new Error(U.transactionErrorCodes.INSUFFICIENT_FUNDS);return{useApprovalUtxoData:r,deltaAmountOverride:I}};exports.outputApprovalDataProcessing=m;exports.outputApprovalDataProcessingForHinkalApprove=k;
@@ -1,46 +1,39 @@
1
- import { transactionErrorCodes as f } from "../../error-handling/error-codes.constants.mjs";
2
- import { APPROVED_UTXO_CONVERSION_COUNT as A } from "../../constants/conversion.constants.mjs";
3
- import { defaultUseApprovalUTXOData as I } from "../../types/hinkal.types.mjs";
4
- import { isUseApprovalDataEmpty as N } from "../utils/processUseApprovalUtxoData.mjs";
5
- import { countTotalAmountInUtxos as k } from "../utils/amounts.utils.mjs";
6
- import { caseInsensitiveEqual as x } from "../utils/caseInsensitive.utils.mjs";
7
- const h = (l, p, e, g, c) => {
8
- if (console.log("outputApprovalDataProcessing 1", { inputUtxos: p, amountChange: e }), c && c > 0)
9
- throw new Error(f.INSUFFICIENT_FUNDS);
10
- console.log("outputApprovalDataProcessing 2");
11
- const i = k(p);
12
- console.log("outputApprovalDataProcessing 3");
13
- const { erc20TokenAddress: u } = p[0];
14
- console.log("outputApprovalDataProcessing 4", { erc20TokenAddress: u });
15
- const d = l.getApprovedUtxosForToken(u).filter((r) => !x(r.interactionAddress, g));
16
- console.log("outputApprovalDataProcessing 5", { relevantApprovedUtxos: d });
17
- const o = I(A, 0n);
18
- if (console.log("outputApprovalDataProcessing 6", { useApprovalUtxoData: o }), e < 0n && i + e < 0n) {
19
- let r = -(i + e);
20
- for (let t = 0; t < Math.min(d.length, A) && r !== 0n; t += 1) {
21
- const a = d[t], v = a.amount >= r ? -r : -a.amount;
22
- r += v, o.approvalChanges[t] = v, o.externalApprovalAddresses[t] = a.interactionAddress, o.conversionInHinkalAddress[t] = a.inHinkalAddress;
1
+ import { transactionErrorCodes as v } from "../../error-handling/error-codes.constants.mjs";
2
+ import { APPROVED_UTXO_CONVERSION_COUNT as l } from "../../constants/conversion.constants.mjs";
3
+ import { defaultUseApprovalUTXOData as F } from "../../types/hinkal.types.mjs";
4
+ import { isUseApprovalDataEmpty as D } from "../utils/processUseApprovalUtxoData.mjs";
5
+ import { countTotalAmountInUtxos as N } from "../utils/amounts.utils.mjs";
6
+ import { caseInsensitiveEqual as E } from "../utils/caseInsensitive.utils.mjs";
7
+ const S = (i, d, s, f, A) => {
8
+ if (A && A > 0)
9
+ throw new Error(v.INSUFFICIENT_FUNDS);
10
+ const p = N(d), { erc20TokenAddress: U } = d[0], c = i.getApprovedUtxosForToken(U).filter((n) => !E(n.interactionAddress, f)), r = F(l, 0n);
11
+ if (s < 0n && p + s < 0n) {
12
+ let n = -(p + s);
13
+ for (let o = 0; o < Math.min(c.length, l) && n !== 0n; o += 1) {
14
+ const a = c[o], u = a.amount >= n ? -n : -a.amount;
15
+ n += u, r.approvalChanges[o] = u, r.externalApprovalAddresses[o] = a.interactionAddress, r.conversionInHinkalAddress[o] = a.inHinkalAddress;
23
16
  }
24
- if (r !== 0n)
25
- throw new Error(f.INSUFFICIENT_FUNDS);
17
+ if (n !== 0n)
18
+ throw new Error(v.INSUFFICIENT_FUNDS);
26
19
  }
27
- return { useApprovalUtxoData: N(o) ? void 0 : o };
28
- }, C = (l, p, e, g, c, i) => {
29
- if (i && i > 0)
30
- throw new Error(f.INSUFFICIENT_FUNDS);
31
- const u = k(p), { erc20TokenAddress: d } = p[0], o = I(A, 0n), r = l.userKeys.getInHinkalAddress(e), t = l.getApprovedUtxosForToken(d).sort((n, s) => n.inHinkalAddress === r ? -1 : s.inHinkalAddress === r ? 1 : n.amount === s.amount ? 0 : n.amount < s.amount ? -1 : 1), a = t[0]?.inHinkalAddress === r, v = a ? t[0].amount : 0n, F = g - v;
32
- o.approvalChanges[0] = F, o.externalApprovalAddresses[0] = e, o.conversionInHinkalAddress[0] = l.userKeys.getInHinkalAddress(e);
33
- const D = a ? 1 : 0, m = D === 0 ? 1 : 0;
34
- let U = c;
35
- for (let n = D; n < Math.min(A, t.length) && !(n + m >= A); n += 1) {
36
- const s = t[n];
37
- U += s.amount, o.approvalChanges[n + m] = -s.amount, o.externalApprovalAddresses[n + m] = s.interactionAddress, o.conversionInHinkalAddress[n + m] = s.inHinkalAddress;
20
+ return { useApprovalUtxoData: D(r) ? void 0 : r };
21
+ }, O = (i, d, s, f, A, p) => {
22
+ if (p && p > 0)
23
+ throw new Error(v.INSUFFICIENT_FUNDS);
24
+ const U = N(d), { erc20TokenAddress: c } = d[0], r = F(l, 0n), n = i.userKeys.getInHinkalAddress(s), o = i.getApprovedUtxosForToken(c).sort((t, e) => t.inHinkalAddress === n ? -1 : e.inHinkalAddress === n ? 1 : t.amount === e.amount ? 0 : t.amount < e.amount ? -1 : 1), a = o[0]?.inHinkalAddress === n, u = a ? o[0].amount : 0n, x = f - u;
25
+ r.approvalChanges[0] = x, r.externalApprovalAddresses[0] = s, r.conversionInHinkalAddress[0] = i.userKeys.getInHinkalAddress(s);
26
+ const k = a ? 1 : 0, m = k === 0 ? 1 : 0;
27
+ let I = A;
28
+ for (let t = k; t < Math.min(l, o.length) && !(t + m >= l); t += 1) {
29
+ const e = o[t];
30
+ I += e.amount, r.approvalChanges[t + m] = -e.amount, r.externalApprovalAddresses[t + m] = e.interactionAddress, r.conversionInHinkalAddress[t + m] = e.inHinkalAddress;
38
31
  }
39
- if (u + U < 0n)
40
- throw new Error(f.INSUFFICIENT_FUNDS);
41
- return { useApprovalUtxoData: o, deltaAmountOverride: U };
32
+ if (U + I < 0n)
33
+ throw new Error(v.INSUFFICIENT_FUNDS);
34
+ return { useApprovalUtxoData: r, deltaAmountOverride: I };
42
35
  };
43
36
  export {
44
- h as outputApprovalDataProcessing,
45
- C as outputApprovalDataProcessingForHinkalApprove
37
+ S as outputApprovalDataProcessing,
38
+ O as outputApprovalDataProcessingForHinkalApprove
46
39
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("../../../data-structures/utxo/Utxo.cjs"),k=require("../../utils/upToDateState.cjs"),O=require("../../utils/cacheFunctions.cjs"),K=require("../../utils/caseInsensitive.utils.cjs"),P=require("../../utils/encodeTokenWithId.cjs"),M=require("./getInputUtxosEnclave.cjs"),F=require("../../../error-handling/logger.cjs"),H=require("../../utils/solanaMint.utils.cjs"),_=require("../../../constants/chains.constants.cjs"),j=require("../../utils/addresses.cjs"),G=require("../../../API/scheduled-transactions-calls.cjs"),b=async(t,o,e,n,c,r,u,a,s)=>{s+=1;const l=r.slice(s),{lastOutput:w,additionalEncryptedOutputs:f}=await t.utxoUtils.batchProcess(l,a,o,e),i=[...u,...f];return await k.checkChainOrAddressNotUpdated(t,e,n),O.setHinkalCache({lastOutput:w,encryptedOutputs:i},t,e,c),await t.utxoUtils.buildBatchProcess(i,o,e)},q=async(t,o,e,n)=>{const{utxos:c,encryptedOutputs:r,lastOutput:u}=await M.getInputUtxosEnclave(t,e,o);return O.setHinkalCache({encryptedOutputs:r,lastOutput:u},t,e,n),c},S=async(t,o,e,n,c,r,u,a,s)=>{try{return await q(t,o,e,c)}catch{return b(t,o,e,n,c,r,u,a,s)}},D=t=>{if(Array.isArray(t))return t;if(t!==void 0)return[t]},J=async(t,o,e)=>await t.utxoUtils.batchFilterUtxosWithNullifier(o,e),W=(t,o,e,n,c,r,u)=>{for(t.sort((a,s)=>a.amount<=s.amount?1:-1),console.log("sorted utxos");t.length<o||t.length>o&&t.length<6;)if(console.log("before pushing"),console.log("aaa",c,u,n,r),t.push(new R.Utxo({amount:0n,erc20TokenAddress:c,mintAddress:u,shieldedPrivateKey:n,tokenId:r,enableLogs:!0})),console.log("after pushing"),e)for(;t.length>6;)t.splice(t.length-1);console.log("completed sorting utxos")},C=async({hinkal:t,chainId:o=void 0,passedShieldedPublicKey:e=void 0,ethAddress:n=void 0,resetCacheBefore:c=!1,allowRemoteDecryption:r=!1,useBlockedUtxos:u=!1})=>{if(!t.getCurrentChainId||!t.getSelectedNetwork())return F.Logger.log("returning empty balance"),{inputUtxos:[]};const a=n??await t.getEthereumAddress(),s=o??t.getCurrentChainId(),l=e??t.userKeys.getShieldedPublicKey(),{encryptedOutputs:w,nullifiers:f,userKeys:i}=t,g=Array.from(w);console.log("getInputUtxoAndBalance 1"),c&&O.resetCache(t,s,l);let{encryptedOutputs:h,lastOutput:x}=O.getHinkalCache(t,s,l);console.log("getInputUtxoAndBalance 2"),await k.checkChainOrAddressNotUpdated(t,s,a),console.log("getInputUtxoAndBalance 3");const p=x!=="",d=g.findIndex(m=>m.value===x);console.log("getInputUtxoAndBalance 4");const y=d>-1,T=!p&&d===-1;console.log("getInputUtxoAndBalance 5");const I=t.areMerkleTreeUpdatesDisabled();console.log("getInputUtxoAndBalance 6");const v=!I&&(y||!r&&T),B=!I&&r&&T,U=!v&&!B;let A=[];v?A=await b(t,i,s,a,l,g,h,x,d):B?A=await S(t,i,s,a,l,g,h,x,d):U&&(A=await t.utxoUtils.buildBatchProcess(h,i,s)),console.log("getInputUtxoAndBalance 7"),await k.checkChainOrAddressNotUpdated(t,s,a);const E=await J(t,A,f);console.log("getInputUtxoAndBalance 8");const L=u?E:E.filter(m=>!m.isBlocked);return console.log("getInputUtxoAndBalance 9"),console.trace(),{inputUtxos:L}},N=async({hinkal:t,chainId:o=void 0,passedShieldedPublicKey:e=void 0,ethAddress:n=void 0,resetCacheBefore:c=!1,allowRemoteDecryption:r=!1})=>{const u=o??t.getCurrentChainId(),a=n??await t.getEthereumAddress(),s=j.hashEthereumAddress(a),{inputUtxos:l}=await C({hinkal:t,chainId:u,passedShieldedPublicKey:e,ethAddress:a,resetCacheBefore:c,allowRemoteDecryption:r,useBlockedUtxos:!0});if(!l.length)return{inputUtxos:[]};const w=l.map(g=>g.getNullifier()),{indexes:f}=await G.getScheduledTransactionsNullifierIndexes(u,{hashedEthereumAddress:s,nullifiers:w});return{inputUtxos:f.map(g=>l[g]).filter(g=>!!g)}},z=async({hinkal:t,tokenWithId:o,minInput:e=2,sliceIfMore6:n=!0,chainId:c=void 0,passedShieldedPrivateKey:r=void 0,passedShieldedPublicKey:u=void 0,ethAddress:a=void 0,resetCacheBefore:s=!1,ensuredTokensWithId:l,useBlockedUtxos:w=!1})=>{const f=r??t.userKeys.getShieldedPrivateKey(),i=c??t.getCurrentChainId();console.log("getInputUtxoAndBalancePerToken 1");const{inputUtxos:g}=w?await N({hinkal:t,chainId:c,ethAddress:a,passedShieldedPrivateKey:r,resetCacheBefore:s}):await C({hinkal:t,tokenWithId:o,minInput:e,sliceIfMore6:n,chainId:c,passedShieldedPrivateKey:r,passedShieldedPublicKey:u,ethAddress:a,resetCacheBefore:s});console.log("getInputUtxoAndBalancePerToken 2");const h=D(o),x=new Map;console.log("getInputUtxoAndBalancePerToken 3"),g.forEach(p=>{const d=p.getTokenAddress(i);if(h&&!h.some(I=>K.caseInsensitiveEqual(I.erc20TokenAddress,d)&&I.tokenId===p.tokenId))return;const y=P.encodeTokenWithId(i,{erc20TokenAddress:d,tokenId:p.tokenId}),T=x.get(y)??[];x.set(y,[...T,p])}),console.log("getInputUtxoAndBalancePerToken 4"),l?.forEach(p=>{const d=P.encodeTokenWithId(i,{erc20TokenAddress:p.erc20TokenAddress,tokenId:p.tokenId});x.set(d,x.get(d)??[])}),console.log("getInputUtxoAndBalancePerToken 5");for(const[p,d]of x){const y=p.split("-")[0],T=Number(p.split("-")[1]),I=_.isSolanaLike(i),v=I?y:void 0,B=I?H.formatMintAddress(y).compressedAddress.toLowerCase():y.toLowerCase(),U=A=>A===null?"null":typeof A!="object"?typeof A:A.constructor.name;console.log("types",JSON.stringify({value:U(d),minInput:U(e),sliceIfMore6:U(n),shieldedPrivateKey:U(f),modifiedErc20TokenAddress:U(B),tokenId:U(T),mintAddress:U(v)})),console.log("started padding"),W(d,e,n,f,B,T,v),console.log("done padding")}return console.log("getInputUtxoAndBalancePerToken 6"),x};exports.attemptGetInputUtxosRemotely=S;exports.getInputUtxoAndBalance=C;exports.getInputUtxoAndBalanceOfStuckUtxos=N;exports.getInputUtxoAndBalancePerToken=z;exports.getInputUtxosRemotely=q;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("../../../data-structures/utxo/Utxo.cjs"),C=require("../../utils/upToDateState.cjs"),m=require("../../utils/cacheFunctions.cjs"),R=require("../../utils/caseInsensitive.utils.cjs"),k=require("../../utils/encodeTokenWithId.cjs"),K=require("./getInputUtxosEnclave.cjs"),M=require("../../../error-handling/logger.cjs"),F=require("../../utils/solanaMint.utils.cjs"),H=require("../../../constants/chains.constants.cjs"),_=require("../../utils/addresses.cjs"),G=require("../../../API/scheduled-transactions-calls.cjs"),S=async(t,s,e,a,n,r,u,c,o)=>{o+=1;const d=r.slice(o),{lastOutput:y,additionalEncryptedOutputs:A}=await t.utxoUtils.batchProcess(d,c,s,e),i=[...u,...A];return await C.checkChainOrAddressNotUpdated(t,e,a),m.setHinkalCache({lastOutput:y,encryptedOutputs:i},t,e,n),await t.utxoUtils.buildBatchProcess(i,s,e)},b=async(t,s,e,a)=>{const{utxos:n,encryptedOutputs:r,lastOutput:u}=await K.getInputUtxosEnclave(t,e,s);return m.setHinkalCache({encryptedOutputs:r,lastOutput:u},t,e,a),n},B=async(t,s,e,a,n,r,u,c,o)=>{try{return await b(t,s,e,n)}catch{return S(t,s,e,a,n,r,u,c,o)}},j=t=>{if(Array.isArray(t))return t;if(t!==void 0)return[t]},D=async(t,s,e)=>await t.utxoUtils.batchFilterUtxosWithNullifier(s,e),W=(t,s,e,a,n,r,u)=>{for(t.sort((c,o)=>c.amount<=o.amount?1:-1);t.length<s||t.length>s&&t.length<6;)if(t.push(new L.Utxo({amount:0n,erc20TokenAddress:n,mintAddress:u,shieldedPrivateKey:a,tokenId:r})),e)for(;t.length>6;)t.splice(t.length-1)},E=async({hinkal:t,chainId:s=void 0,passedShieldedPublicKey:e=void 0,ethAddress:a=void 0,resetCacheBefore:n=!1,allowRemoteDecryption:r=!1,useBlockedUtxos:u=!1})=>{if(!t.getCurrentChainId||!t.getSelectedNetwork())return M.Logger.log("returning empty balance"),{inputUtxos:[]};const c=a??await t.getEthereumAddress(),o=s??t.getCurrentChainId(),d=e??t.userKeys.getShieldedPublicKey(),{encryptedOutputs:y,nullifiers:A,userKeys:i}=t,l=Array.from(y);n&&m.resetCache(t,o,d);let{encryptedOutputs:w,lastOutput:U}=m.getHinkalCache(t,o,d);await C.checkChainOrAddressNotUpdated(t,o,c);const p=U!=="",x=l.findIndex(T=>T.value===U),g=x>-1,I=!p&&x===-1,f=t.areMerkleTreeUpdatesDisabled(),h=!f&&(g||!r&&I),v=!f&&r&&I,P=!h&&!v;let O=[];h?O=await S(t,i,o,c,d,l,w,U,x):v?O=await B(t,i,o,c,d,l,w,U,x):P&&(O=await t.utxoUtils.buildBatchProcess(w,i,o)),await C.checkChainOrAddressNotUpdated(t,o,c);const q=await D(t,O,A);return{inputUtxos:u?q:q.filter(T=>!T.isBlocked)}},N=async({hinkal:t,chainId:s=void 0,passedShieldedPublicKey:e=void 0,ethAddress:a=void 0,resetCacheBefore:n=!1,allowRemoteDecryption:r=!1})=>{const u=s??t.getCurrentChainId(),c=a??await t.getEthereumAddress(),o=_.hashEthereumAddress(c),{inputUtxos:d}=await E({hinkal:t,chainId:u,passedShieldedPublicKey:e,ethAddress:c,resetCacheBefore:n,allowRemoteDecryption:r,useBlockedUtxos:!0});if(!d.length)return{inputUtxos:[]};const y=d.map(l=>l.getNullifier()),{indexes:A}=await G.getScheduledTransactionsNullifierIndexes(u,{hashedEthereumAddress:o,nullifiers:y});return{inputUtxos:A.map(l=>d[l]).filter(l=>!!l)}},z=async({hinkal:t,tokenWithId:s,minInput:e=2,sliceIfMore6:a=!0,chainId:n=void 0,passedShieldedPrivateKey:r=void 0,passedShieldedPublicKey:u=void 0,ethAddress:c=void 0,resetCacheBefore:o=!1,ensuredTokensWithId:d,useBlockedUtxos:y=!1})=>{const A=r??t.userKeys.getShieldedPrivateKey(),i=n??t.getCurrentChainId(),{inputUtxos:l}=y?await N({hinkal:t,chainId:n,ethAddress:c,passedShieldedPrivateKey:r,resetCacheBefore:o}):await E({hinkal:t,tokenWithId:s,minInput:e,sliceIfMore6:a,chainId:n,passedShieldedPrivateKey:r,passedShieldedPublicKey:u,ethAddress:c,resetCacheBefore:o}),w=j(s),U=new Map;l.forEach(p=>{const x=p.getTokenAddress(i);if(w&&!w.some(f=>R.caseInsensitiveEqual(f.erc20TokenAddress,x)&&f.tokenId===p.tokenId))return;const g=k.encodeTokenWithId(i,{erc20TokenAddress:x,tokenId:p.tokenId}),I=U.get(g)??[];U.set(g,[...I,p])}),d?.forEach(p=>{const x=k.encodeTokenWithId(i,{erc20TokenAddress:p.erc20TokenAddress,tokenId:p.tokenId});U.set(x,U.get(x)??[])});for(const[p,x]of U){const g=p.split("-")[0],I=Number(p.split("-")[1]),f=H.isSolanaLike(i),h=f?g:void 0,v=f?F.formatMintAddress(g).compressedAddress.toLowerCase():g.toLowerCase();W(x,e,a,A,v,I,h)}return U};exports.attemptGetInputUtxosRemotely=B;exports.getInputUtxoAndBalance=E;exports.getInputUtxoAndBalanceOfStuckUtxos=N;exports.getInputUtxoAndBalancePerToken=z;exports.getInputUtxosRemotely=b;
@@ -1,60 +1,60 @@
1
- import { Utxo as S } from "../../../data-structures/utxo/Utxo.mjs";
2
- import { checkChainOrAddressNotUpdated as h } from "../../utils/upToDateState.mjs";
3
- import { setHinkalCache as C, resetCache as L, getHinkalCache as K } from "../../utils/cacheFunctions.mjs";
4
- import { caseInsensitiveEqual as R } from "../../utils/caseInsensitive.utils.mjs";
5
- import { encodeTokenWithId as P } from "../../utils/encodeTokenWithId.mjs";
6
- import { getInputUtxosEnclave as F } from "./getInputUtxosEnclave.mjs";
7
- import { Logger as H } from "../../../error-handling/logger.mjs";
8
- import { formatMintAddress as M } from "../../utils/solanaMint.utils.mjs";
9
- import { isSolanaLike as j } from "../../../constants/chains.constants.mjs";
1
+ import { Utxo as B } from "../../../data-structures/utxo/Utxo.mjs";
2
+ import { checkChainOrAddressNotUpdated as T } from "../../utils/upToDateState.mjs";
3
+ import { setHinkalCache as b, resetCache as L, getHinkalCache as k } from "../../utils/cacheFunctions.mjs";
4
+ import { caseInsensitiveEqual as K } from "../../utils/caseInsensitive.utils.mjs";
5
+ import { encodeTokenWithId as C } from "../../utils/encodeTokenWithId.mjs";
6
+ import { getInputUtxosEnclave as R } from "./getInputUtxosEnclave.mjs";
7
+ import { Logger as F } from "../../../error-handling/logger.mjs";
8
+ import { formatMintAddress as H } from "../../utils/solanaMint.utils.mjs";
9
+ import { isSolanaLike as M } from "../../../constants/chains.constants.mjs";
10
10
  import { hashEthereumAddress as q } from "../../utils/addresses.mjs";
11
11
  import { getScheduledTransactionsNullifierIndexes as G } from "../../../API/scheduled-transactions-calls.mjs";
12
- const b = async (t, o, e, n, r, c, l, a, s) => {
13
- s += 1;
14
- const u = c.slice(s), { lastOutput: I, additionalEncryptedOutputs: A } = await t.utxoUtils.batchProcess(
15
- u,
12
+ const N = async (t, s, e, d, r, n, u, c, o) => {
13
+ o += 1;
14
+ const a = n.slice(o), { lastOutput: U, additionalEncryptedOutputs: g } = await t.utxoUtils.batchProcess(
16
15
  a,
17
- o,
16
+ c,
17
+ s,
18
18
  e
19
- ), i = [...l, ...A];
20
- return await h(t, e, n), C(
19
+ ), i = [...u, ...g];
20
+ return await T(t, e, d), b(
21
21
  {
22
- lastOutput: I,
22
+ lastOutput: U,
23
23
  encryptedOutputs: i
24
24
  },
25
25
  t,
26
26
  e,
27
27
  r
28
- ), await t.utxoUtils.buildBatchProcess(i, o, e);
29
- }, J = async (t, o, e, n) => {
28
+ ), await t.utxoUtils.buildBatchProcess(i, s, e);
29
+ }, j = async (t, s, e, d) => {
30
30
  const {
31
31
  utxos: r,
32
- encryptedOutputs: c,
33
- lastOutput: l
34
- } = await F(t, e, o);
35
- return C(
32
+ encryptedOutputs: n,
33
+ lastOutput: u
34
+ } = await R(t, e, s);
35
+ return b(
36
36
  {
37
- encryptedOutputs: c,
38
- lastOutput: l
37
+ encryptedOutputs: n,
38
+ lastOutput: u
39
39
  },
40
40
  t,
41
41
  e,
42
- n
42
+ d
43
43
  ), r;
44
- }, z = async (t, o, e, n, r, c, l, a, s) => {
44
+ }, z = async (t, s, e, d, r, n, u, c, o) => {
45
45
  try {
46
- return await J(t, o, e, r);
46
+ return await j(t, s, e, r);
47
47
  } catch {
48
- return b(
48
+ return N(
49
49
  t,
50
- o,
50
+ s,
51
51
  e,
52
- n,
52
+ d,
53
53
  r,
54
+ n,
55
+ u,
54
56
  c,
55
- l,
56
- a,
57
- s
57
+ o
58
58
  );
59
59
  }
60
60
  }, D = (t) => {
@@ -62,160 +62,134 @@ const b = async (t, o, e, n, r, c, l, a, s) => {
62
62
  return t;
63
63
  if (t !== void 0)
64
64
  return [t];
65
- }, Q = async (t, o, e) => await t.utxoUtils.batchFilterUtxosWithNullifier(o, e), V = (t, o, e, n, r, c, l) => {
66
- for (t.sort((a, s) => a.amount <= s.amount ? 1 : -1), console.log("sorted utxos"); t.length < o || t.length > o && t.length < 6; )
67
- if (console.log("before pushing"), console.log("aaa", r, l, n, c), t.push(
68
- new S({ amount: 0n, erc20TokenAddress: r, mintAddress: l, shieldedPrivateKey: n, tokenId: c, enableLogs: !0 })
69
- ), console.log("after pushing"), e)
65
+ }, J = async (t, s, e) => await t.utxoUtils.batchFilterUtxosWithNullifier(s, e), Q = (t, s, e, d, r, n, u) => {
66
+ for (t.sort((c, o) => c.amount <= o.amount ? 1 : -1); t.length < s || t.length > s && t.length < 6; )
67
+ if (t.push(new B({ amount: 0n, erc20TokenAddress: r, mintAddress: u, shieldedPrivateKey: d, tokenId: n })), e)
70
68
  for (; t.length > 6; )
71
69
  t.splice(t.length - 1);
72
- console.log("completed sorting utxos");
73
- }, k = async ({
70
+ }, P = async ({
74
71
  hinkal: t,
75
- chainId: o = void 0,
72
+ chainId: s = void 0,
76
73
  passedShieldedPublicKey: e = void 0,
77
- ethAddress: n = void 0,
74
+ ethAddress: d = void 0,
78
75
  resetCacheBefore: r = !1,
79
- allowRemoteDecryption: c = !1,
80
- useBlockedUtxos: l = !1
76
+ allowRemoteDecryption: n = !1,
77
+ useBlockedUtxos: u = !1
81
78
  }) => {
82
79
  if (!t.getCurrentChainId || !t.getSelectedNetwork())
83
- return H.log("returning empty balance"), { inputUtxos: [] };
84
- const a = n ?? await t.getEthereumAddress(), s = o ?? t.getCurrentChainId(), u = e ?? t.userKeys.getShieldedPublicKey(), { encryptedOutputs: I, nullifiers: A, userKeys: i } = t, p = Array.from(I);
85
- console.log("getInputUtxoAndBalance 1"), r && L(t, s, u);
86
- let { encryptedOutputs: v, lastOutput: f } = K(
80
+ return F.log("returning empty balance"), { inputUtxos: [] };
81
+ const c = d ?? await t.getEthereumAddress(), o = s ?? t.getCurrentChainId(), a = e ?? t.userKeys.getShieldedPublicKey(), { encryptedOutputs: U, nullifiers: g, userKeys: i } = t, l = Array.from(U);
82
+ r && L(t, o, a);
83
+ let { encryptedOutputs: w, lastOutput: m } = k(
87
84
  t,
88
- s,
89
- u
85
+ o,
86
+ a
90
87
  );
91
- console.log("getInputUtxoAndBalance 2"), await h(t, s, a), console.log("getInputUtxoAndBalance 3");
92
- const g = f !== "", d = p.findIndex((O) => O.value === f);
93
- console.log("getInputUtxoAndBalance 4");
94
- const m = d > -1, w = !g && d === -1;
95
- console.log("getInputUtxoAndBalance 5");
96
- const y = t.areMerkleTreeUpdatesDisabled();
97
- console.log("getInputUtxoAndBalance 6");
98
- const B = !y && (m || !c && w), T = !y && c && w, x = !B && !T;
99
- let U = [];
100
- B ? U = await b(
88
+ await T(t, o, c);
89
+ const p = m !== "", f = l.findIndex((E) => E.value === m), x = f > -1, A = !p && f === -1, y = t.areMerkleTreeUpdatesDisabled(), v = !y && (x || !n && A), O = !y && n && A, S = !v && !O;
90
+ let I = [];
91
+ v ? I = await N(
101
92
  t,
102
93
  i,
103
- s,
94
+ o,
95
+ c,
104
96
  a,
105
- u,
106
- p,
107
- v,
108
- f,
109
- d
110
- ) : T ? U = await z(
97
+ l,
98
+ w,
99
+ m,
100
+ f
101
+ ) : O ? I = await z(
111
102
  t,
112
103
  i,
113
- s,
104
+ o,
105
+ c,
114
106
  a,
115
- u,
116
- p,
117
- v,
118
- f,
119
- d
120
- ) : x && (U = await t.utxoUtils.buildBatchProcess(v, i, s)), console.log("getInputUtxoAndBalance 7"), await h(t, s, a);
121
- const E = await Q(t, U, A);
122
- console.log("getInputUtxoAndBalance 8");
123
- const N = l ? E : E.filter((O) => !O.isBlocked);
124
- return console.log("getInputUtxoAndBalance 9"), console.trace(), { inputUtxos: N };
125
- }, X = async ({
107
+ l,
108
+ w,
109
+ m,
110
+ f
111
+ ) : S && (I = await t.utxoUtils.buildBatchProcess(w, i, o)), await T(t, o, c);
112
+ const h = await J(t, I, g);
113
+ return { inputUtxos: u ? h : h.filter((E) => !E.isBlocked) };
114
+ }, V = async ({
126
115
  hinkal: t,
127
- chainId: o = void 0,
116
+ chainId: s = void 0,
128
117
  passedShieldedPublicKey: e = void 0,
129
- ethAddress: n = void 0,
118
+ ethAddress: d = void 0,
130
119
  resetCacheBefore: r = !1,
131
- allowRemoteDecryption: c = !1
120
+ allowRemoteDecryption: n = !1
132
121
  }) => {
133
- const l = o ?? t.getCurrentChainId(), a = n ?? await t.getEthereumAddress(), s = q(a), { inputUtxos: u } = await k({
122
+ const u = s ?? t.getCurrentChainId(), c = d ?? await t.getEthereumAddress(), o = q(c), { inputUtxos: a } = await P({
134
123
  hinkal: t,
135
- chainId: l,
124
+ chainId: u,
136
125
  passedShieldedPublicKey: e,
137
- ethAddress: a,
126
+ ethAddress: c,
138
127
  resetCacheBefore: r,
139
- allowRemoteDecryption: c,
128
+ allowRemoteDecryption: n,
140
129
  useBlockedUtxos: !0
141
130
  });
142
- if (!u.length)
131
+ if (!a.length)
143
132
  return { inputUtxos: [] };
144
- const I = u.map((p) => p.getNullifier()), { indexes: A } = await G(l, {
145
- hashedEthereumAddress: s,
146
- nullifiers: I
133
+ const U = a.map((l) => l.getNullifier()), { indexes: g } = await G(u, {
134
+ hashedEthereumAddress: o,
135
+ nullifiers: U
147
136
  });
148
- return { inputUtxos: A.map((p) => u[p]).filter((p) => !!p) };
137
+ return { inputUtxos: g.map((l) => a[l]).filter((l) => !!l) };
149
138
  }, ct = async ({
150
139
  hinkal: t,
151
- tokenWithId: o,
140
+ tokenWithId: s,
152
141
  minInput: e = 2,
153
- sliceIfMore6: n = !0,
142
+ sliceIfMore6: d = !0,
154
143
  chainId: r = void 0,
155
- passedShieldedPrivateKey: c = void 0,
156
- passedShieldedPublicKey: l = void 0,
157
- ethAddress: a = void 0,
158
- resetCacheBefore: s = !1,
159
- ensuredTokensWithId: u,
160
- useBlockedUtxos: I = !1
144
+ passedShieldedPrivateKey: n = void 0,
145
+ passedShieldedPublicKey: u = void 0,
146
+ ethAddress: c = void 0,
147
+ resetCacheBefore: o = !1,
148
+ ensuredTokensWithId: a,
149
+ useBlockedUtxos: U = !1
161
150
  }) => {
162
- const A = c ?? t.userKeys.getShieldedPrivateKey(), i = r ?? t.getCurrentChainId();
163
- console.log("getInputUtxoAndBalancePerToken 1");
164
- const { inputUtxos: p } = I ? await X({
151
+ const g = n ?? t.userKeys.getShieldedPrivateKey(), i = r ?? t.getCurrentChainId(), { inputUtxos: l } = U ? await V({
165
152
  hinkal: t,
166
153
  chainId: r,
167
- ethAddress: a,
168
- passedShieldedPrivateKey: c,
169
- resetCacheBefore: s
170
- }) : await k({
154
+ ethAddress: c,
155
+ passedShieldedPrivateKey: n,
156
+ resetCacheBefore: o
157
+ }) : await P({
171
158
  hinkal: t,
172
- tokenWithId: o,
159
+ tokenWithId: s,
173
160
  minInput: e,
174
- sliceIfMore6: n,
161
+ sliceIfMore6: d,
175
162
  chainId: r,
176
- passedShieldedPrivateKey: c,
177
- passedShieldedPublicKey: l,
178
- ethAddress: a,
179
- resetCacheBefore: s
180
- });
181
- console.log("getInputUtxoAndBalancePerToken 2");
182
- const v = D(o), f = /* @__PURE__ */ new Map();
183
- console.log("getInputUtxoAndBalancePerToken 3"), p.forEach((g) => {
184
- const d = g.getTokenAddress(i);
185
- if (v && !v.some(
186
- (y) => R(y.erc20TokenAddress, d) && y.tokenId === g.tokenId
163
+ passedShieldedPrivateKey: n,
164
+ passedShieldedPublicKey: u,
165
+ ethAddress: c,
166
+ resetCacheBefore: o
167
+ }), w = D(s), m = /* @__PURE__ */ new Map();
168
+ l.forEach((p) => {
169
+ const f = p.getTokenAddress(i);
170
+ if (w && !w.some(
171
+ (y) => K(y.erc20TokenAddress, f) && y.tokenId === p.tokenId
187
172
  ))
188
173
  return;
189
- const m = P(i, { erc20TokenAddress: d, tokenId: g.tokenId }), w = f.get(m) ?? [];
190
- f.set(m, [...w, g]);
191
- }), console.log("getInputUtxoAndBalancePerToken 4"), u?.forEach((g) => {
192
- const d = P(i, {
193
- erc20TokenAddress: g.erc20TokenAddress,
194
- tokenId: g.tokenId
174
+ const x = C(i, { erc20TokenAddress: f, tokenId: p.tokenId }), A = m.get(x) ?? [];
175
+ m.set(x, [...A, p]);
176
+ }), a?.forEach((p) => {
177
+ const f = C(i, {
178
+ erc20TokenAddress: p.erc20TokenAddress,
179
+ tokenId: p.tokenId
195
180
  });
196
- f.set(d, f.get(d) ?? []);
197
- }), console.log("getInputUtxoAndBalancePerToken 5");
198
- for (const [g, d] of f) {
199
- const m = g.split("-")[0], w = Number(g.split("-")[1]), y = j(i), B = y ? m : void 0, T = y ? M(m).compressedAddress.toLowerCase() : m.toLowerCase(), x = (U) => U === null ? "null" : typeof U != "object" ? typeof U : U.constructor.name;
200
- console.log(
201
- "types",
202
- JSON.stringify({
203
- value: x(d),
204
- minInput: x(e),
205
- sliceIfMore6: x(n),
206
- shieldedPrivateKey: x(A),
207
- modifiedErc20TokenAddress: x(T),
208
- tokenId: x(w),
209
- mintAddress: x(B)
210
- })
211
- ), console.log("started padding"), V(d, e, n, A, T, w, B), console.log("done padding");
181
+ m.set(f, m.get(f) ?? []);
182
+ });
183
+ for (const [p, f] of m) {
184
+ const x = p.split("-")[0], A = Number(p.split("-")[1]), y = M(i), v = y ? x : void 0, O = y ? H(x).compressedAddress.toLowerCase() : x.toLowerCase();
185
+ Q(f, e, d, g, O, A, v);
212
186
  }
213
- return console.log("getInputUtxoAndBalancePerToken 6"), f;
187
+ return m;
214
188
  };
215
189
  export {
216
190
  z as attemptGetInputUtxosRemotely,
217
- k as getInputUtxoAndBalance,
218
- X as getInputUtxoAndBalanceOfStuckUtxos,
191
+ P as getInputUtxoAndBalance,
192
+ V as getInputUtxoAndBalanceOfStuckUtxos,
219
193
  ct as getInputUtxoAndBalancePerToken,
220
- J as getInputUtxosRemotely
194
+ j as getInputUtxosRemotely
221
195
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h_test_1",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "homepage": "hinkal.io",
5
5
  "author": {
6
6
  "name": "Hinkal Protocol"
@@ -1 +1 @@
1
- "use strict";const e=""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/../../assets/utxoWorkerLauncher-RoJ0StvR.js").href:new URL("../../assets/utxoWorkerLauncher-RoJ0StvR.js",document.currentScript&&document.currentScript.src||document.baseURI).href);module.exports=e;
1
+ "use strict";const e=""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/../../assets/utxoWorkerLauncher-DIu_LMBb.js").href:new URL("../../assets/utxoWorkerLauncher-DIu_LMBb.js",document.currentScript&&document.currentScript.src||document.baseURI).href);module.exports=e;
@@ -1,4 +1,4 @@
1
- const e = "" + new URL("../../assets/utxoWorkerLauncher-RoJ0StvR.js", import.meta.url).href;
1
+ const e = "" + new URL("../../assets/utxoWorkerLauncher-DIu_LMBb.js", import.meta.url).href;
2
2
  export {
3
3
  e as default
4
4
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("../../crypto/preProcessing.cjs"),l=require("../../data-structures/crypto-keys/keys.cjs"),f=require("../../data-structures/utxo/Utxo.cjs"),h=require("../../data-structures/crypto-keys/encryptDecryptUtxo.cjs"),y=require("../../data-structures/crypto-keys/decodeUTXO.cjs"),T=require("../workerProxy.cjs"),d=require("./utxoWorker.types.cjs"),n=new T.WorkerProxy,p=async({data:e})=>{const{utxos:t,nullifiers:s}=e,c=t.filter(r=>{const i=new f.Utxo(r);return!s.has(i.getNullifier())});n.postMessageToMainThread({utxoConstructors:c,stealthPairCache:l.stealthPairCacheDevice.serialize(),stealthAddressCache:l.stealthAddressCacheDevice.serialize()})},x=async({data:e})=>{const t=new l.UserKeys(e.signature),s=t.getShieldedPrivateKey(),c=e.encryptedOutputs.map(r=>{try{const i=r.isPositive?h.decryptUtxoConstructorArgs(Buffer.from(r.value.slice(2),"hex"),t):y.decodeUtxoConstructorArgs(r.value,s,e.chainId);return i.isBlocked=r.isBlocked,i}catch{return}}).filter(r=>r!==void 0&&r.amount!==0n);n.postMessageToMainThread(c)},g=async({data:e})=>{const t=new l.UserKeys(e.signature),s=[],{encryptedOutputs:c}=e;let{lastOutput:r}=e;const i=t.getShieldedPrivateKey();for(let u=0;u<c.length;u+=1){const a=c[u];if(r=a.value,a.isPositive)try{const o=h.decryptUtxo(Buffer.from(r.slice(2),"hex"),t);if(o.isBlocked=a.isBlocked,!o.erc20TokenAddress||!o.amount||!o.stealthAddress)throw Error("bruh");s.push(a)}catch{}else try{y.checkUtxoSignature(r,i,e.chainId)&&s.push(a)}catch{}}n.postMessageToMainThread({additionalEncryptedOutputs:s,lastOutput:r})},U=async e=>{try{await k.preProcessing();const{type:t}=e.payload;switch(t){case d.UtxoWorkerActionType.BATCH_FILTER_UTXOS_WITH_NULLIFIER:await p(e.payload);return;case d.UtxoWorkerActionType.BUILD_UTXOS:await x(e.payload);return;case d.UtxoWorkerActionType.DECIPHER_OUTPUTS:await g(e.payload);return;default:throw Error(`Unknown worker message type ${t}`)}}catch(t){console.log("utxo worker message failed",t,e),n.postErrorToMainThread(t)}};n.attachWorkerSideOnMessage(U);exports.default=n;exports.handleBuildUtxosMessage=x;exports.handleDecipherMessage=g;exports.handleFilterUtxosWithNullifier=p;exports.onWorkerMessage=U;
1
+ "use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const k=require("../../crypto/preProcessing.cjs"),l=require("../../data-structures/crypto-keys/keys.cjs"),f=require("../../data-structures/utxo/Utxo.cjs"),h=require("../../data-structures/crypto-keys/encryptDecryptUtxo.cjs"),y=require("../../data-structures/crypto-keys/decodeUTXO.cjs"),T=require("../../error-handling/logger.cjs"),w=require("../workerProxy.cjs"),d=require("./utxoWorker.types.cjs"),n=new w.WorkerProxy,p=async({data:e})=>{const{utxos:t,nullifiers:s}=e,i=t.filter(r=>{const c=new f.Utxo(r);return!s.has(c.getNullifier())});n.postMessageToMainThread({utxoConstructors:i,stealthPairCache:l.stealthPairCacheDevice.serialize(),stealthAddressCache:l.stealthAddressCacheDevice.serialize()})},g=async({data:e})=>{const t=new l.UserKeys(e.signature),s=t.getShieldedPrivateKey(),i=e.encryptedOutputs.map(r=>{try{const c=r.isPositive?h.decryptUtxoConstructorArgs(Buffer.from(r.value.slice(2),"hex"),t):y.decodeUtxoConstructorArgs(r.value,s,e.chainId);return c.isBlocked=r.isBlocked,c}catch{return}}).filter(r=>r!==void 0&&r.amount!==0n);n.postMessageToMainThread(i)},x=async({data:e})=>{const t=new l.UserKeys(e.signature),s=[],{encryptedOutputs:i}=e;let{lastOutput:r}=e;const c=t.getShieldedPrivateKey();for(let u=0;u<i.length;u+=1){const a=i[u];if(r=a.value,a.isPositive)try{const o=h.decryptUtxo(Buffer.from(r.slice(2),"hex"),t);if(o.isBlocked=a.isBlocked,!o.erc20TokenAddress||!o.amount||!o.stealthAddress)throw Error("bruh");s.push(a)}catch{}else try{y.checkUtxoSignature(r,c,e.chainId)&&s.push(a)}catch{}}n.postMessageToMainThread({additionalEncryptedOutputs:s,lastOutput:r})},U=async e=>{try{await k.preProcessing();const{type:t}=e.payload;switch(t){case d.UtxoWorkerActionType.BATCH_FILTER_UTXOS_WITH_NULLIFIER:await p(e.payload);return;case d.UtxoWorkerActionType.BUILD_UTXOS:await g(e.payload);return;case d.UtxoWorkerActionType.DECIPHER_OUTPUTS:await x(e.payload);return;default:throw Error(`Unknown worker message type ${t}`)}}catch(t){T.Logger.error("utxo worker message failed",t,e),n.postErrorToMainThread(t)}};n.attachWorkerSideOnMessage(U);exports.default=n;exports.handleBuildUtxosMessage=g;exports.handleDecipherMessage=x;exports.handleFilterUtxosWithNullifier=p;exports.onWorkerMessage=U;
@@ -3,9 +3,10 @@ import { stealthPairCacheDevice as p, stealthAddressCacheDevice as y, UserKeys a
3
3
  import { Utxo as f } from "../../data-structures/utxo/Utxo.mjs";
4
4
  import { decryptUtxoConstructorArgs as m, decryptUtxo as g } from "../../data-structures/crypto-keys/encryptDecryptUtxo.mjs";
5
5
  import { decodeUtxoConstructorArgs as x, checkUtxoSignature as U } from "../../data-structures/crypto-keys/decodeUTXO.mjs";
6
- import { WorkerProxy as T } from "../workerProxy.mjs";
6
+ import { Logger as T } from "../../error-handling/logger.mjs";
7
+ import { WorkerProxy as k } from "../workerProxy.mjs";
7
8
  import { UtxoWorkerActionType as d } from "./utxoWorker.types.mjs";
8
- const n = new T(), k = async ({ data: e }) => {
9
+ const n = new k(), w = async ({ data: e }) => {
9
10
  const { utxos: t, nullifiers: o } = e, i = t.filter((r) => {
10
11
  const c = new f(r);
11
12
  return !o.has(c.getNullifier());
@@ -15,7 +16,7 @@ const n = new T(), k = async ({ data: e }) => {
15
16
  stealthPairCache: p.serialize(),
16
17
  stealthAddressCache: y.serialize()
17
18
  });
18
- }, w = async ({ data: e }) => {
19
+ }, P = async ({ data: e }) => {
19
20
  const t = new h(e.signature), o = t.getShieldedPrivateKey(), i = e.encryptedOutputs.map((r) => {
20
21
  try {
21
22
  const c = r.isPositive ? m(Buffer.from(r.value.slice(2), "hex"), t) : x(r.value, o, e.chainId);
@@ -25,7 +26,7 @@ const n = new T(), k = async ({ data: e }) => {
25
26
  }
26
27
  }).filter((r) => r !== void 0 && r.amount !== 0n);
27
28
  n.postMessageToMainThread(i);
28
- }, P = async ({ data: e }) => {
29
+ }, v = async ({ data: e }) => {
29
30
  const t = new h(e.signature), o = [], { encryptedOutputs: i } = e;
30
31
  let { lastOutput: r } = e;
31
32
  const c = t.getShieldedPrivateKey();
@@ -46,32 +47,32 @@ const n = new T(), k = async ({ data: e }) => {
46
47
  }
47
48
  }
48
49
  n.postMessageToMainThread({ additionalEncryptedOutputs: o, lastOutput: r });
49
- }, v = async (e) => {
50
+ }, M = async (e) => {
50
51
  try {
51
52
  await u();
52
53
  const { type: t } = e.payload;
53
54
  switch (t) {
54
55
  case d.BATCH_FILTER_UTXOS_WITH_NULLIFIER:
55
- await k(e.payload);
56
+ await w(e.payload);
56
57
  return;
57
58
  case d.BUILD_UTXOS:
58
- await w(e.payload);
59
+ await P(e.payload);
59
60
  return;
60
61
  case d.DECIPHER_OUTPUTS:
61
- await P(e.payload);
62
+ await v(e.payload);
62
63
  return;
63
64
  default:
64
65
  throw Error(`Unknown worker message type ${t}`);
65
66
  }
66
67
  } catch (t) {
67
- console.log("utxo worker message failed", t, e), n.postErrorToMainThread(t);
68
+ T.error("utxo worker message failed", t, e), n.postErrorToMainThread(t);
68
69
  }
69
70
  };
70
- n.attachWorkerSideOnMessage(v);
71
+ n.attachWorkerSideOnMessage(M);
71
72
  export {
72
73
  n as default,
73
- w as handleBuildUtxosMessage,
74
- P as handleDecipherMessage,
75
- k as handleFilterUtxosWithNullifier,
76
- v as onWorkerMessage
74
+ P as handleBuildUtxosMessage,
75
+ v as handleDecipherMessage,
76
+ w as handleFilterUtxosWithNullifier,
77
+ M as onWorkerMessage
77
78
  };
@@ -1 +1 @@
1
- "use strict";const e=""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/../../assets/zkProofWorkerLauncher-BJidEELM.js").href:new URL("../../assets/zkProofWorkerLauncher-BJidEELM.js",document.currentScript&&document.currentScript.src||document.baseURI).href);module.exports=e;
1
+ "use strict";const e=""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/../../assets/zkProofWorkerLauncher-EF0nGZ3A.js").href:new URL("../../assets/zkProofWorkerLauncher-EF0nGZ3A.js",document.currentScript&&document.currentScript.src||document.baseURI).href);module.exports=e;
@@ -1,4 +1,4 @@
1
- const r = "" + new URL("../../assets/zkProofWorkerLauncher-BJidEELM.js", import.meta.url).href;
1
+ const r = "" + new URL("../../assets/zkProofWorkerLauncher-EF0nGZ3A.js", import.meta.url).href;
2
2
  export {
3
3
  r as default
4
4
  };