@vechain/sdk-network
Version:
This module serves as the standard interface connecting decentralized applications (dApps) and users to the VeChainThor blockchain
5 lines • 104 kB
JavaScript
import {HttpNetworkError,InvalidHTTPRequest,InvalidHTTPParams,InvalidDataType,PollExecution,CannotFindTransaction,ContractDeploymentFailed,InvalidAbiItem,InvalidTransactionField,NotDelegatedTransaction,JSONRPCInvalidParams,SignerMethodError,InvalidSecp256k1PrivateKey,stringifyData,JSONRPCInvalidDefaultBlock,JSONRPCInternalError,JSONRPCTransactionRevertError,JSONRPCMethodNotImplemented,JSONRPCServerError,JSONRPCMethodNotFound,VechainSDKError,ContractCallError}from'@vechain/sdk-errors';import {Keccak256,Txt,SOLO_NETWORK,TESTNET_NETWORK,MAINNET_NETWORK,HexUInt,VET,Units,FixedPointNumber,VTHO,ABIEvent,Address,ABIItem,ABIFunction,ZERO_ADDRESS,Revision,ABIContract,Clause,Transaction,Hex,ThorId,ABI,dataUtils,Secp256k1,HDKey,Quantity,ZERO_BYTES,HexInt,fromTransactionType,TransactionType}from'@vechain/sdk-core';import {EventEmitter}from'events';import {Interface,ErrorFragment,JsonRpcApiProvider}from'ethers';import {concatBytes}from'@noble/curves/abstract/utils';import {hashTypedData}from'viem';import {VeChainSDKLogger}from'@vechain/sdk-logging';var zr=Object.defineProperty;var Yr=(n,e)=>{for(var t in e)zr(n,t,{get:e[t],enumerable:true});};var Kr={};Yr(Kr,{AccountDetail:()=>Z,AccountsModule:()=>te,BUILT_IN_CONTRACTS:()=>xe,BlocksModule:()=>ne,CHAIN_ID:()=>Fe,CHAIN_TAG:()=>De,Contract:()=>N,ContractFactory:()=>q,ContractsModule:()=>re,DebugModule:()=>oe,DefaultBlockToRevision:()=>b,DelegationHandler:()=>j,ERROR_SELECTOR:()=>Re,ForkDetector:()=>W,GasModule:()=>ie,HTTPS_REGEX:()=>Xe,HTTP_REGEX:()=>ve,HardhatVeChainProvider:()=>wn,HttpMethod:()=>k,JSONRPCEthersProvider:()=>bt,LogsModule:()=>ae,MAINNET_URL:()=>ao,NODE_HEALTHCHECK_TOLERANCE_IN_SECONDS:()=>Ze,NodesModule:()=>se,PANIC_SELECTOR:()=>ke,POLLING_INTERVAL:()=>Tt,Poll:()=>A,ProviderInternalBaseWallet:()=>me,ProviderInternalHDWallet:()=>yt,RPCMethodsMap:()=>bn,RPC_DOCUMENTATION_URL:()=>u,RPC_METHODS:()=>M,SimpleHttpClient:()=>D,TESTNET_URL:()=>so,THOR_SOLO_URL:()=>co,ThorClient:()=>le,TransactionsModule:()=>ce,VeChainAbstractSigner:()=>de,VeChainPrivateKeySigner:()=>pe,VeChainProvider:()=>Y,blocksFormatter:()=>w,buildQuery:()=>T,chainTagToChainId:()=>Ct,debugFormatter:()=>he,debugTraceBlockByHash:()=>Bt,debugTraceBlockByNumber:()=>St,debugTraceCall:()=>At,debugTraceTransaction:()=>H,engineGetPayloadBodiesByHashV1:()=>Ki,engineGetPayloadBodiesByRangeV1:()=>Yi,ethAccounts:()=>ye,ethBlockNumber:()=>Et,ethCall:()=>Nt,ethChainId:()=>h,ethEstimateGas:()=>Ot,ethFeeHistory:()=>Ft,ethGasPrice:()=>Dt,ethGetBalance:()=>Mt,ethGetBlockByHash:()=>C,ethGetBlockByNumber:()=>R,ethGetBlockReceipts:()=>Lt,ethGetBlockTransactionCountByHash:()=>Gt,ethGetBlockTransactionCountByNumber:()=>Ut,ethGetCode:()=>Vt,ethGetFilterChanges:()=>Ca,ethGetFilterLogs:()=>xa,ethGetLogs:()=>be,ethGetStorageAt:()=>Ht,ethGetTransactionByBlockHashAndIndex:()=>$t,ethGetTransactionByBlockNumberAndIndex:()=>qt,ethGetTransactionByHash:()=>$,ethGetTransactionCount:()=>Jt,ethGetTransactionReceipt:()=>V,ethGetUncleByBlockHashAndIndex:()=>jt,ethGetUncleByBlockNumberAndIndex:()=>Wt,ethGetUncleCountByBlockHash:()=>Kt,ethGetUncleCountByBlockNumber:()=>zt,ethMaxPriorityFeePerGas:()=>Yt,ethRequestAccounts:()=>Qt,ethSendRawTransaction:()=>Xt,ethSendTransaction:()=>Zt,ethSignTransaction:()=>tn,ethSignTypedDataV4:()=>nn,ethSubscribe:()=>on,ethSyncing:()=>an,ethUnsubscribe:()=>sn,evmMine:()=>je,formatToLogsRPC:()=>vt,formatToRPCStandard:()=>xt,getCachedChainId:()=>kt,getCachedChainTag:()=>Ii,getCriteriaSetForInput:()=>Rt,getNumberOfLogsAheadOfTransactionIntoBlockExpanded:()=>Pt,getTransactionIndexIntoBlock:()=>F,isTraceEnabled:()=>Pe,logError:()=>Ye,logRequest:()=>Ke,logResponse:()=>ze,netListening:()=>ln,netPeerCount:()=>un,netVersion:()=>dn,sanitizeWebsocketBaseURL:()=>_,signerUtils:()=>Qe,subscriptions:()=>ho,thorest:()=>m,toQueryString:()=>E,transactionsFormatter:()=>U,txPoolContent:()=>pn,txPoolContentFrom:()=>mn,txPoolInspect:()=>fn,txPoolStatus:()=>gn,vnsUtils:()=>I,web3ClientVersion:()=>hn,web3Sha3:()=>yn});var k=(t=>(t.GET="GET",t.POST="POST",t))(k||{});var Pe=()=>{let n=process?.env?.SDK_TRACE?.toLowerCase();return n==="true"||n==="1"},Ke=(n,e,t,r)=>{if(!Pe())return Date.now();let o=Date.now(),i={category:"HTTP Request",method:n,url:e,requestHeaders:t,requestBody:r,timestamp:o};if(console.log(`
\u26A1 [TRACE] HTTP Request (${new Date(o).toISOString()})`),console.log(`\u27A1\uFE0F ${JSON.stringify(i,null,2)}`),t!=null&&Object.keys(t).length>0&&(console.log("\u{1F4CB} Headers:"),Object.entries(t).forEach(([a,s])=>{console.log(` ${a}: ${s}`);})),r!==void 0){console.log("\u{1F4E6} Body:");try{console.log(typeof r=="string"?r:JSON.stringify(r,null,2));}catch{console.log("[Complex body object]");}}return o},ze=(n,e,t,r)=>{if(!Pe())return;let o=Date.now(),i=o-n,a={category:"HTTP Response",url:e,responseHeaders:t,responseBody:r,timestamp:o,duration:i};if(console.log(`
\u26A1 [TRACE] HTTP Response (${new Date(o).toISOString()})`),console.log(`\u27A1\uFE0F ${JSON.stringify(a,null,2)}`),console.log(`\u2B05\uFE0F ${e} (${i}ms)`),t!=null&&Object.keys(t).length>0&&(console.log("\u{1F4CB} Headers:"),Object.entries(t).forEach(([s,l])=>{console.log(` ${s}: ${l}`);})),r!==null){console.log("\u{1F4E6} Body:");try{console.log(typeof r=="string"?r:JSON.stringify(r,null,2));}catch{console.log("[Complex response body]");}}},Ye=(n,e,t,r)=>{if(!Pe())return;let o=Date.now(),i=o-n,a={category:"HTTP Error",method:t,url:e,error:r,timestamp:o,duration:i};console.log(`
\u26A1 [TRACE] HTTP Error (${new Date(o).toISOString()})`),console.log(`\u27A1\uFE0F ${JSON.stringify(a,null,2)}`),console.log(`\u274C ${t} ${e} (${i}ms)`),console.log("\u26D4 Error:"),r!=null&&r instanceof Error?(console.log(` ${r.name}: ${r.message}`),r.stack!=null&&console.log(` Stack: ${r.stack}`),"cause"in r&&r.cause!=null&&(console.log(" Cause:"),console.log(r.cause))):console.log(r);};var D=class n{static DEFAULT_TIMEOUT=1e4;baseURL;headers;timeout;constructor(e,t=new Headers,r=n.DEFAULT_TIMEOUT){this.baseURL=e,this.timeout=r,this.headers=t;}async get(e,t){return await this.http("GET",e,t)}isValidUrl(e){try{return new URL(e),!0}catch{return false}}async http(e,t,r){let o=new AbortController,i=setTimeout(()=>{o.abort();},this.timeout),a,s=Date.now(),l={};try{t.startsWith("/")&&(t=t.slice(1));let d=this.baseURL;d.endsWith("/")||(d+="/"),/^https?:\/\//.exec(t)?a=new URL(t):a=new URL(t,d),r?.query&&a!==void 0&&Object.entries(r.query).forEach(([y,x])=>{a.searchParams.append(y,String(x));}),r?.query!==void 0&&r?.query!=null&&a!==void 0&&Object.entries(r.query).forEach(([y,x])=>{a.searchParams.append(y,String(x));});let p=new Headers(this.headers);r?.headers!==void 0&&r?.headers!=null&&Object.entries(r.headers).forEach(([y,x])=>{p.append(y,String(x));}),l=Object.fromEntries(p.entries()),s=Ke(e,a.toString(),l,e!=="GET"?r?.body:void 0);let g=await fetch(a.toString(),{method:e,headers:p,body:e!=="GET"?r?.rawBody!==void 0?r.rawBody:JSON.stringify(r?.body):void 0,signal:o.signal}),B=Object.fromEntries(g.headers.entries());if(g.ok){r?.validateResponseHeader!=null&&B!=null&&r.validateResponseHeader(B);let y=await g.json();return ze(s,a.toString(),B,y),y}let we;try{we=await g.clone().text();}catch{we=void 0;}let S=`HTTP ${g.status} ${g.statusText}`;if(we?.trim()){let y=we.trim();if(!y.includes("<!DOCTYPE html>")){if(y.startsWith("{")||y.startsWith("["))try{let x=JSON.parse(y);if(x.error&&typeof x.error=="object"&&x.error!==null){let v=x.error,Q=v.code??"",X=v.message??v.msg??"";Q&&(S+=` [${Q}]`),X&&(S+=` - ${X}`);let Ce=v.data;Ce&&typeof Ce=="string"&&Ce.trim()&&(S+=` (${Ce})`);}}catch{}else if(!y.includes("<!DOCTYPE html>")){let v=y.split(`
`)[0].trim();if(v.includes(": ")){let[Q,X]=v.split(": ",2);Q&&X?S+=` - ${Q}: ${X}`:S+=` - ${v}`;}else v.includes(" - ")?S+=` - ${v}`:S+=` - ${v}`;}}}throw new Error(S,{cause:g})}catch(d){if(a){let p=a.toString();throw Ye(s,p,e,d),d instanceof TypeError?new HttpNetworkError("HttpClient.http()",d.message,{method:e,url:p,networkErrorType:"TypeError"},d):new InvalidHTTPRequest("HttpClient.http()",d.message,{method:e,url:p},d)}else {let p=this.isValidUrl(this.baseURL)?new URL(t,this.baseURL).toString():t;throw new InvalidHTTPParams("HttpClient.http()",d.message,{method:e,url:p},d)}}finally{clearTimeout(i);}}async post(e,t){return await this.http("POST",e,t)}};function Cn(n,e){if(n.nonce!==void 0&&(typeof n.nonce=="string"?parseInt(n.nonce,10):n.nonce)<0)throw new Error("Transaction nonce must be a positive number");return {from:e,chainTag:n.chainTag,blockRef:n.blockRef,expiration:n.expiration,clauses:n.clauses,gasPriceCoef:n.gasPriceCoef,gas:n.gas,dependsOn:n.dependsOn??void 0,nonce:n.nonce,reserved:n.reserved,maxPriorityFeePerGas:n.maxPriorityFeePerGas??void 0,maxFeePerGas:n.maxFeePerGas??void 0}}var Qe={transactionBodyToTransactionRequestInput:Cn};var M=(c=>(c.eth_blockNumber="eth_blockNumber",c.eth_chainId="eth_chainId",c.eth_getBalance="eth_getBalance",c.eth_getCode="eth_getCode",c.eth_getStorageAt="eth_getStorageAt",c.eth_estimateGas="eth_estimateGas",c.eth_call="eth_call",c.eth_sendRawTransaction="eth_sendRawTransaction",c.eth_getLogs="eth_getLogs",c.eth_getBlockByHash="eth_getBlockByHash",c.eth_getBlockByNumber="eth_getBlockByNumber",c.eth_accounts="eth_accounts",c.eth_requestAccounts="eth_requestAccounts",c.eth_gasPrice="eth_gasPrice",c.eth_getTransactionByHash="eth_getTransactionByHash",c.eth_getTransactionCount="eth_getTransactionCount",c.eth_getTransactionReceipt="eth_getTransactionReceipt",c.eth_getTransactionByBlockNumberAndIndex="eth_getTransactionByBlockNumberAndIndex",c.eth_getTransactionByBlockHashAndIndex="eth_getTransactionByBlockHashAndIndex",c.eth_getBlockTransactionCountByHash="eth_getBlockTransactionCountByHash",c.eth_getBlockTransactionCountByNumber="eth_getBlockTransactionCountByNumber",c.eth_sendTransaction="eth_sendTransaction",c.eth_syncing="eth_syncing",c.net_version="net_version",c.web3_clientVersion="web3_clientVersion",c.eth_subscribe="eth_subscribe",c.eth_unsubscribe="eth_unsubscribe",c.debug_traceTransaction="debug_traceTransaction",c.debug_traceCall="debug_traceCall",c.evm_mine="evm_mine",c.evm_increaseTime="evm_increaseTime",c.web3_sha3="web3_sha3",c.net_peerCount="net_peerCount",c.net_listening="net_listening",c.eth_getUncleByBlockNumberAndIndex="eth_getUncleByBlockNumberAndIndex",c.eth_getUncleByBlockHashAndIndex="eth_getUncleByBlockHashAndIndex",c.txpool_inspect="txpool_inspect",c.txpool_contentFrom="txpool_contentFrom",c.txpool_content="txpool_content",c.txpool_status="txpool_status",c.eth_signTransaction="eth_signTransaction",c.debug_traceBlockByHash="debug_traceBlockByHash",c.debug_traceBlockByNumber="debug_traceBlockByNumber",c.eth_getUncleCountByBlockHash="eth_getUncleCountByBlockHash",c.eth_getUncleCountByBlockNumber="eth_getUncleCountByBlockNumber",c.eth_signTypedData_v4="eth_signTypedData_v4",c.eth_getBlockReceipts="eth_getBlockReceipts",c.eth_coinbase="eth_coinbase",c.eth_feeHistory="eth_feeHistory",c.eth_getWork="eth_getWork",c.eth_mining="eth_mining",c.eth_hashrate="eth_hashrate",c.eth_protocolVersion="eth_protocolVersion",c.eth_sign="eth_sign",c.eth_submitWork="eth_submitWork",c.parity_nextNonce="parity_nextNonce",c.eth_newFilter="eth_newFilter",c.eth_newBlockFilter="eth_newBlockFilter",c.eth_newPendingTransactionFilter="eth_newPendingTransactionFilter",c.eth_getFilterLogs="eth_getFilterLogs",c.eth_getFilterChanges="eth_getFilterChanges",c.eth_uninstallFilter="eth_uninstallFilter",c.debug_getBadBlocks="debug_getBadBlocks",c.debug_getRawBlock="debug_getRawBlock",c.debug_getRawHeader="debug_getRawHeader",c.debug_getRawReceipts="debug_getRawReceipts",c.debug_getRawTransaction="debug_getRawTransaction",c.engine_exchangeCapabilities="engine_exchangeCapabilities",c.engine_exchangeTransitionConfigurationV1="engine_exchangeTransitionConfigurationV1",c.engine_forkchoiceUpdatedV1="engine_forkchoiceUpdatedV1",c.engine_forkchoiceUpdatedV2="engine_forkchoiceUpdatedV2",c.engine_forkchoiceUpdatedV3="engine_forkchoiceUpdatedV3",c.engine_getPayloadBodiesByHashV1="engine_getPayloadBodiesByHashV1",c.engine_getPayloadBodiesByRangeV1="engine_getPayloadBodiesByRangeV1",c.engine_getPayloadV1="engine_getPayloadV1",c.engine_getPayloadV2="engine_getPayloadV2",c.engine_getPayloadV3="engine_getPayloadV3",c.engine_newPayloadV1="engine_newPayloadV1",c.engine_newPayloadV2="engine_newPayloadV2",c.engine_newPayloadV3="engine_newPayloadV3",c.eth_createAccessList="eth_createAccessList",c.eth_getProof="eth_getProof",c.eth_maxPriorityFeePerGas="eth_maxPriorityFeePerGas",c))(M||{});var Z=class{balance;energy;hasCode;get vet(){return VET.of(Units.formatEther(FixedPointNumber.of(this.balance)))}get vtho(){return VTHO.of(Units.formatEther(FixedPointNumber.of(this.energy)))}constructor(e){this.balance=e.balance,this.energy=e.energy,this.hasCode=e.hasCode;}};var no="0x0000000000000000000000000000506172616d73",ro="0x0000000000000000000000000000456e65726779",oo=[{constant:false,inputs:[{name:"_key",type:"bytes32"},{name:"_value",type:"uint256"}],name:"set",outputs:[],payable:false,stateMutability:"nonpayable",type:"function"},{constant:true,inputs:[{name:"_key",type:"bytes32"}],name:"get",outputs:[{name:"",type:"uint256"}],payable:false,stateMutability:"view",type:"function"},{constant:true,inputs:[],name:"executor",outputs:[{name:"",type:"address"}],payable:false,stateMutability:"view",type:"function"},{anonymous:false,inputs:[{indexed:true,name:"key",type:"bytes32"},{indexed:false,name:"value",type:"uint256"}],name:"Set",type:"event"}],io=[{constant:true,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:false,stateMutability:"pure",type:"function"},{constant:false,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"success",type:"bool"}],payable:false,stateMutability:"nonpayable",type:"function"},{constant:true,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:false,stateMutability:"view",type:"function"},{constant:false,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"transferFrom",outputs:[{name:"success",type:"bool"}],payable:false,stateMutability:"nonpayable",type:"function"},{constant:true,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:false,stateMutability:"pure",type:"function"},{constant:true,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:false,stateMutability:"view",type:"function"},{constant:true,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:false,stateMutability:"pure",type:"function"},{constant:false,inputs:[{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"transfer",outputs:[{name:"success",type:"bool"}],payable:false,stateMutability:"nonpayable",type:"function"},{constant:false,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"move",outputs:[{name:"success",type:"bool"}],payable:false,stateMutability:"nonpayable",type:"function"},{constant:true,inputs:[],name:"totalBurned",outputs:[{name:"",type:"uint256"}],payable:false,stateMutability:"view",type:"function"},{constant:true,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"remaining",type:"uint256"}],payable:false,stateMutability:"view",type:"function"},{anonymous:false,inputs:[{indexed:true,name:"_from",type:"address"},{indexed:true,name:"_to",type:"address"},{indexed:false,name:"_value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:false,inputs:[{indexed:true,name:"_owner",type:"address"},{indexed:true,name:"_spender",type:"address"},{indexed:false,name:"_value",type:"uint256"}],name:"Approval",type:"event"}],xe={PARAMS_ABI:oo,PARAMS_ADDRESS:no,ENERGY_ABI:io,ENERGY_ADDRESS:ro};var ve=/^http:\/\//,Xe=/^https:\/\//;var Ze=30;var Re=Keccak256.of(Txt.of("Error(string)").bytes).toString().slice(0,10),ke=Keccak256.of(Txt.of("Panic(uint256)").bytes).toString().slice(0,10);var ao="https://mainnet.vechain.org",so="https://testnet.vechain.org",co="http://127.0.0.1:8669";var u="https://ethereum.github.io/execution-apis/api-documentation/";var T=n=>{let e={};for(let t in n)n[t]!==void 0&&(e[t]=n[t]);return e};var kn=1e3;async function In(n){await new Promise(e=>setTimeout(e,n));}function Bn(n,e){if(e?.requestIntervalInMilliseconds!==void 0&&(e.requestIntervalInMilliseconds<=0||!Number.isInteger(e.requestIntervalInMilliseconds)))throw new InvalidDataType("SyncPoll()",'Polling failed: Invalid input for field "options?.requestIntervalInMilliseconds" it must be a positive number',{requestIntervalInMilliseconds:e.requestIntervalInMilliseconds});if(e?.maximumIterations!==void 0&&(e.maximumIterations<=0||!Number.isInteger(e.maximumIterations)))throw new InvalidDataType("SyncPoll()",'Polling failed: Invalid input for field "options?.maximumIterations" it must be a positive number',{maximumIterations:e.maximumIterations});if(e?.maximumWaitingTimeInMilliseconds!==void 0&&(e.maximumWaitingTimeInMilliseconds<=0||!Number.isInteger(e.maximumWaitingTimeInMilliseconds)))throw new InvalidDataType("SyncPoll()",'Polling failed: Invalid input for field "options?.maximumWaitingTimeInMilliseconds" it must be a positive number',{maximumWaitingTimeInMilliseconds:e.maximumWaitingTimeInMilliseconds});let t=0,r,o=false,i=Date.now();return {waitUntil:async a=>{let s=0,l=10,d=false;try{do{try{if(r=await n(),s=0,d=a(r),d)return r}catch(B){if(B instanceof HttpNetworkError){if(s++,s>=l)throw new PollExecution("SyncPoll.waitUntil()","Polling failed: Too many consecutive network errors.",{functionName:n.name},B);await In(e?.requestIntervalInMilliseconds??1e3);continue}else throw B}await In(e?.requestIntervalInMilliseconds??1e3),t=t+1;let p=e?.maximumIterations!==void 0?t>=e.maximumIterations:t>=kn,g=e?.maximumWaitingTimeInMilliseconds!==void 0&&Date.now()-i>=e.maximumWaitingTimeInMilliseconds;if(o=!(d||p||g),t>=kn)throw new PollExecution("SyncPoll.waitUntil()","Polling failed: Maximum safe iterations reached.",{functionName:n.name})}while(o);return r}catch(p){throw new PollExecution("SyncPoll.waitUntil()","Polling failed: Function execution error encountered during synchronous polling.",{functionName:n.name},p)}}}}var nt=class extends EventEmitter{currentIteration=0;error;hasToStopOnError;intervalId;pollingFunction;requestIntervalInMilliseconds;constructor(e,t,r){if(super(),this.pollingFunction=e,this.hasToStopOnError=r,t!==void 0&&(t<=0||!Number.isInteger(t)))throw new InvalidDataType("SyncPoll()",'Polling failed: Invalid input for field "options?.maximumWaitingTimeInMilliseconds" it must be a positive number',{requestIntervalInMilliseconds:t});this.requestIntervalInMilliseconds=t;}get getCurrentIteration(){return this.currentIteration}async _intervalLoop(){try{let e=await this.pollingFunction();this.emit("data",{data:e,eventPoll:this});}catch(e){e instanceof HttpNetworkError?(console.warn("Network error during polling, continuing:",e.message),this.emit("error",{error:e}),this.hasToStopOnError&&this.stopListen()):(this.error=new PollExecution("EventPoll - main interval loop function",`Error during the execution of the poll ${e.message}`,{functionName:this.pollingFunction.name}),this.emit("error",{error:this.error}),this.hasToStopOnError&&this.stopListen());}this.currentIteration=this.currentIteration+1;}onData(e){return this.on("data",t=>{e(t.data,t.eventPoll);}),this}onError(e){return this.on("error",t=>{e(t.error);}),this}onStart(e){return this.on("start",t=>{e(t.eventPoll);}),this}onStop(e){return this.on("stop",t=>{e(t.eventPoll);}),this}startListen(){this.emit("start",{eventPoll:this}),this._intervalLoop().then(()=>{this.intervalId=setInterval(()=>{(async()=>{try{await this._intervalLoop();}catch(e){console.error("EventPoll interval error:",e),this.hasToStopOnError&&this.stopListen();}})();},this.requestIntervalInMilliseconds);});}stopListen(){clearInterval(this.intervalId),this.emit("stop",{eventPoll:this});}};function Sn(n,e,t=true){return new nt(n,e,t)}var A={SyncPoll:Bn,createEventPoll:Sn};var E=n=>{let e=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`);return e.length>0?`?${e.join("&")}`:""},_=n=>{n=n.trim();let e=/^(https?:\/\/)([a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*)(:\d+)?\/?$/;if(!e.test(n))throw new InvalidDataType("sanitizeWebsocketBaseURL()",`Invalid url: ${n}. Must adhere to the regex: ${e}.`,{url:n,urlRegex:e});return n=n.replace(/\/$/,""),n=ve.exec(n)!==null?n.replace(ve,"ws://"):n.replace(Xe,"wss://"),n};var m={accounts:{get:{ACCOUNT_DETAIL:n=>`/accounts/${n}`,ACCOUNT_BYTECODE:n=>`/accounts/${n}/code`,STORAGE_AT:(n,e)=>`/accounts/${n}/storage/${e}`},post:{SIMULATE_TRANSACTION:n=>n!=null?`/accounts/*?revision=${n}`:"/accounts/*"}},blocks:{get:{BLOCK_DETAIL:n=>`/blocks/${n}`}},nodes:{get:{NODES:()=>"/node/network/peers"}},logs:{post:{EVENT_LOGS:()=>"/logs/event",TRANSFER_LOGS:()=>"/logs/transfer"}},transactions:{get:{TRANSACTION:n=>`/transactions/${n}`,TRANSACTION_RECEIPT:n=>`/transactions/${n}/receipt`},post:{TRANSACTION:()=>"/transactions"}},subscriptions:{get:{BLOCK:(n,e)=>{let t=E({pos:e});return `${_(n)}/subscriptions/block${t}`},EVENT:(n,e)=>{let t=E({pos:e?.position,addr:e?.contractAddress,t0:e?.topic0,t1:e?.topic1,t2:e?.topic2,t3:e?.topic3,t4:e?.topic4});return `${_(n)}/subscriptions/event${t}`},VET_TRANSFER:(n,e)=>{let t=E({pos:e?.position,txOrigin:e?.signerAddress,sender:e?.sender,recipient:e?.receiver});return `${_(n)}/subscriptions/transfer${t}`},BEAT_LEGACY:(n,e)=>{let t=E({pos:e});return `${_(n)}/subscriptions/beat${t}`},BEAT:(n,e)=>{let t=E({pos:e});return `${_(n)}/subscriptions/beat2${t}`},NEW_TRANSACTIONS:n=>`${_(n)}/subscriptions/txpool`}},debug:{post:{TRACE_TRANSACTION_CLAUSE:()=>"/debug/tracers",TRACE_CONTRACT_CALL:()=>"/debug/tracers/call",RETRIEVE_STORAGE_RANGE:()=>"/debug/storage-range"}},fees:{get:{FEES_HISTORY:(n,e,t)=>`/fees/history${E({blockCount:n,newestBlock:e,rewardPercentiles:t?.join(",")})}`}}};var An=(n,e)=>m.subscriptions.get.BEAT_LEGACY(n,e?.blockID),En=(n,e)=>m.subscriptions.get.BEAT(n,e?.blockID);var _n=(n,e)=>m.subscriptions.get.BLOCK(n,e?.blockID);var On=(n,e,t,r)=>{let i=(typeof e=="string"?new ABIEvent(e):new ABIEvent(e)).encodeFilterTopicsNoNull(t??[]);return m.subscriptions.get.EVENT(n,{position:r?.blockID,contractAddress:r?.address,topic0:i[0],topic1:i[1],topic2:i[2],topic3:i[3],topic4:i[4]})};var Fn=n=>m.subscriptions.get.NEW_TRANSACTIONS(n);var Dn=(n,e)=>m.subscriptions.get.VET_TRANSFER(n,{position:e?.blockID,signerAddress:e?.signerAddress,sender:e?.sender,receiver:e?.recipient});var ho={getEventSubscriptionUrl:On,getBlockSubscriptionUrl:_n,getNewTransactionsSubscriptionUrl:Fn,getVETtransfersSubscriptionUrl:Dn,getLegacyBeatSubscriptionUrl:An,getBeatSubscriptionUrl:En};var ee={[MAINNET_NETWORK.genesisBlock.id]:{registry:"0xa9231da8BF8D10e2df3f6E03Dd5449caD600129b",resolveUtils:"0xA11413086e163e41901bb81fdc5617c975Fa5a1A"},[TESTNET_NETWORK.genesisBlock.id]:{registry:"0xcBFB30c1F267914816668d53AcBA7bA7c9806D13",resolveUtils:"0xc403b8EA53F707d7d4de095f0A20bC491Cf2bc94"},[SOLO_NETWORK.genesisBlock.id]:{registry:"0x1c4a602ed21f3d1dddd1142c81f231ef1a08c921",resolveUtils:"0xb2f08bbfa8a42b1fbe63feec604cb147385203d7"}};var Co=async(n,e)=>{let[t]=await I.resolveNames(n.blocks,n.transactions,[e]);return t??null},Po=async(n,e,t)=>{let r=await n.getGenesisBlock();if(r===null||!Address.isValid(ee[r.id]?.resolveUtils))return t.map(()=>null);let o=ee[r.id].resolveUtils,i=await e.executeCall(o,ABIItem.ofSignature(ABIFunction,"function getAddresses(string[] names) returns (address[] addresses)"),[t]),[a]=i.result.array;return a.map(s=>s===ZERO_ADDRESS||!Address.isValid(s)?null:s)},xo=async(n,e)=>{let[t]=await I.lookupAddresses(n,[e]);return t??null},vo=async(n,e)=>{let t=await n.blocks.getGenesisBlock();if(t===null||!Address.isValid(ee[t.id]?.resolveUtils))return e.map(()=>null);let r=ee[t.id].resolveUtils,o=await n.contracts.executeCall(r,ABIItem.ofSignature(ABIFunction,"function getNames(address[] addresses) returns (string[] names)"),[e]),[i]=o.result.array;return i.map(a=>a===""?null:a)},I={resolveName:Co,resolveNames:Po,lookupAddress:xo,lookupAddresses:vo};var te=class{constructor(e){this.httpClient=e;}async getAccount(e,t){let r=t?.revision?.toString();return new Z(await this.httpClient.get(m.accounts.get.ACCOUNT_DETAIL(e.toString()),{query:T({revision:r})}))}async getBytecode(e,t){let r=t?.revision?.toString(),o=await this.httpClient.get(m.accounts.get.ACCOUNT_BYTECODE(e.toString()),{query:T({revision:r})});return HexUInt.of(o.code)}async getStorageAt(e,t,r){let o=t.toString(),i=r?.revision?.toString(),a=await this.httpClient.get(m.accounts.get.STORAGE_AT(e.toString(),o),{query:T({pos:o,revision:i})});return HexUInt.of(a.value)}};var ne=class{constructor(e,t){this.httpClient=e;this.onBlockError=t?.onBlockError,t?.isPollingEnabled===true&&this.setupPolling();}headBlock=null;onBlockError;pollInstance;destroy(){this.pollInstance!=null&&this.pollInstance.stopListen();}setupPolling(){this.pollInstance=A.createEventPoll(async()=>await this.getBestBlockCompressed(),1e4).onData(e=>{this.headBlock=e;}).onError(this.onBlockError??(()=>{})),this.pollInstance.startListen();}async getBlockCompressed(e){if(e!=null&&!Revision.isValid(e))throw new InvalidDataType("BlocksModule.getBlockCompressed()",'Invalid revision. The revision must be a string representing a block number or block id (also "best" is accepted which represents the best block & "finalized" for the finalized block).',{revision:e});return await this.httpClient.http("GET",m.blocks.get.BLOCK_DETAIL(e))}async getBlockExpanded(e){if(e!=null&&!Revision.isValid(e))throw new InvalidDataType("BlocksModule.getBlockExpanded()",'Invalid revision. The revision must be a string representing a block number or block id (also "best" is accepted which represents the best block & "finalized" for the finalized block).',{revision:e});return await this.httpClient.http("GET",m.blocks.get.BLOCK_DETAIL(e),{query:T({expanded:true})})}async getBestBlockCompressed(){return await this.getBlockCompressed("best")}async getBestBlockExpanded(){return await this.getBlockExpanded("best")}async getBestBlockBaseFeePerGas(){let e=await this.getBestBlockCompressed();return e===null?null:e.baseFeePerGas??null}async getBestBlockRef(){let e=await this.getBestBlockCompressed();return e===null?null:e.id.slice(0,18)}async getFinalBlockCompressed(){return await this.getBlockCompressed("finalized")}async getFinalBlockExpanded(){return await this.getBlockExpanded("finalized")}async _waitForBlock(e,t,r){if(e!=null&&e<=0)throw new InvalidDataType("BlocksModule.waitForBlock()","Invalid blockNumber. The blockNumber must be a number representing a block number.",{blockNumber:e});return await A.SyncPoll(async()=>t?await this.getBlockExpanded(e):await this.getBlockCompressed(e),{requestIntervalInMilliseconds:r?.intervalMs,maximumWaitingTimeInMilliseconds:r?.timeoutMs}).waitUntil(o=>o!=null&&o.number==e)}async waitForBlockCompressed(e,t){return await this._waitForBlock(e,false,t)}async waitForBlockExpanded(e,t){return await this._waitForBlock(e,true,t)}getHeadBlock(){return this.headBlock}async getGenesisBlock(){return await this.getBlockCompressed(0)}getAllAddressesIntoABlock(e){let t=new Set;return t.add(e.beneficiary),t.add(e.signer),e.transactions.forEach(r=>{r.clauses.forEach(o=>{typeof o.to=="string"&&t.add(o.to);}),t.add(r.gasPayer),t.add(r.origin),r.outputs.forEach(o=>{typeof o.contractAddress=="string"&&t.add(o.contractAddress),o.events.forEach(i=>{t.add(i.address);}),o.transfers.forEach(i=>{t.add(i.recipient),t.add(i.sender);});});}),Array.from(t)}};var Ie=class{contract;criteriaSet;constructor(e,t){this.contract=e,this.criteriaSet=t;}async get(e){let t={range:e?.range??{unit:"block",from:0,to:(await this.contract.contractsModule.transactionsModule.blocksModule.getBestBlockCompressed())?.number},criteriaSet:this.criteriaSet,options:e?.options,order:e?.order??"asc"};return await this.contract.contractsModule.transactionsModule.logsModule.filterEventLogs(t)}};function Vn(n){return new Proxy(n.read,{get:(e,t)=>async(...r)=>{let o=it(r),i=o.clauseAdditionalOptions,a=n.getFunctionAbi(t),s={caller:n.getSigner()!==void 0?await n.getSigner()?.getAddress():void 0,...n.getContractReadOptions(),includeABI:true};i?.comment!==void 0&&(s.comment=i.comment),i?.revision!==void 0&&(s.revision=Revision.of(i.revision));let l=await n.contractsModule.executeCall(n.address,a,o.args,s);if(!l.success)throw new ContractCallError(a.stringSignature,l.result.errorMessage,{contractAddress:n.address});return l.result.array??[]}})}function Hn(n){return new Proxy(n.transact,{get:(e,t)=>async(...r)=>{if(n.getSigner()===void 0)throw new InvalidTransactionField("getTransactProxy()","Caller signer is required to transact with the contract.",{fieldName:"signer",prop:t});let o=n.getContractTransactOptions(),i=it(r),a=i.clauseAdditionalOptions?.value,s=i.clauseAdditionalOptions?.comment;return r=i.args,await n.contractsModule.executeTransaction(n.getSigner(),n.address,n.getFunctionAbi(t),r,{...o,value:o.value??a??"0x0",comment:s,includeABI:true})}})}function $n(n){return new Proxy(n.filters,{get:(e,t)=>r=>{let o=jn(n,t,r);return new Ie(n,[o])}})}function qn(n){return new Proxy(n.clause,{get:(e,t)=>(...r)=>{let o=n.getContractTransactOptions(),i=it(r),a=i.clauseAdditionalOptions?.value,s=i.clauseAdditionalOptions?.comment;return r=i.args,{clause:Clause.callFunction(Address.of(n.address),n.getFunctionAbi(t),r,VET.of(o.value??a??0,Units.wei),{comment:s,includeABI:true}),functionAbi:n.getFunctionAbi(t)}}})}function Jn(n){return new Proxy(n.criteria,{get:(e,t)=>r=>jn(n,t,r)})}function jn(n,e,t){let r=n.getEventAbi(e),o=new Map(r.encodeFilterTopicsNoNull(t).map((i,a)=>[a,i]));return {criteria:{address:n.address,topic0:o.get(0),topic1:o.has(1)?o.get(1):void 0,topic2:o.has(2)?o.get(2):void 0,topic3:o.has(3)?o.get(3):void 0,topic4:o.has(4)?o.get(4):void 0},eventAbi:r}}function it(n){let e=_o(n),t=No(n),r=Oo(n);return (e!==void 0||t!==void 0||r!==void 0)&&(n=n.filter(o=>!(Wn(o)||Kn(o)||zn(o)))),{args:n,clauseAdditionalOptions:{value:e?.value,comment:t?.comment,revision:r?.revision}}}function _o(n){let e=n.find(t=>Wn(t));if(e)return {value:e.value.toString()}}function No(n){return n.find(e=>Kn(e))}function Oo(n){return n.find(e=>zn(e))}function Wn(n){return n.value!==void 0}function Kn(n){return n.comment!==void 0}function zn(n){return n.revision!==void 0}var N=class{contractsModule;address;abi;signer;deployTransactionReceipt;read={};transact={};filters={};clause={};criteria={};contractCallOptions={};contractTransactionOptions={};constructor(e,t,r,o,i){this.abi=t,this.address=e,this.contractsModule=r,this.deployTransactionReceipt=i,this.signer=o,this.read=Vn(this),this.transact=Hn(this),this.filters=$n(this),this.clause=qn(this),this.criteria=Jn(this);}setContractReadOptions(e){return this.contractCallOptions=e,this.contractCallOptions}getContractReadOptions(){return this.contractCallOptions}clearContractReadOptions(){this.contractCallOptions={};}setContractTransactOptions(e){return this.contractTransactionOptions=e,this.contractTransactionOptions}getContractTransactOptions(){return this.contractTransactionOptions}clearContractTransactOptions(){this.contractTransactionOptions={};}setSigner(e){return this.signer=e,this.signer}getSigner(){return this.signer}getFunctionAbi(e){return ABIContract.ofAbi(this.abi).getFunction(e.toString())}getEventAbi(e){return ABIContract.ofAbi(this.abi).getEvent(e.toString())}};var q=class{abi;bytecode;signer;deployTransaction;contractsModule;constructor(e,t,r,o){this.abi=e,this.bytecode=t,this.signer=r,this.contractsModule=o;}async startDeployment(e,t){let r=Clause.deployContract(HexUInt.of(this.bytecode),e),o=await this.contractsModule.transactionsModule.estimateGas([r],await this.signer.getAddress(),t),i=await this.contractsModule.transactionsModule.buildTransactionBody([r],o.totalGas,t),a=await this.signer.signTransaction(Qe.transactionBodyToTransactionRequestInput(i,await this.signer.getAddress()));return this.deployTransaction=await this.contractsModule.transactionsModule.sendTransaction(Transaction.decode(HexUInt.of(a.slice(2)).bytes,true)),this}async waitForDeployment(){if(this.deployTransaction?.id===void 0)throw new CannotFindTransaction("ContractFactory.waitForDeployment()","Cannot find a contract deployment transaction",{networkUrl:this.contractsModule.transactionsModule.blocksModule.httpClient.baseURL});let e=await this.deployTransaction.wait();if(e?.outputs[0]?.contractAddress===null||e?.outputs[0]?.contractAddress===void 0)throw new ContractDeploymentFailed("ContractFactory.waitForDeployment()","Contract deployment failed.",{deployTransaction:this.deployTransaction});return new N(e?.outputs[0].contractAddress,this.abi,this.contractsModule,this.signer,e)}getDeployTransaction(){return this.deployTransaction}};var re=class{constructor(e){this.transactionsModule=e;}createContractFactory(e,t,r){return new q(e,t,r,this)}load(e,t,r){return new N(e,t,this,r)}async executeCall(e,t,r,o){return await this.transactionsModule.executeCall(e,t,r,o)}async executeMultipleClausesCall(e,t){return e.every(r=>"clause"in r)?await this.transactionsModule.executeMultipleClausesCall(e,t):await this.transactionsModule.executeMultipleClausesCall(e,t)}async executeTransaction(e,t,r,o,i){return await this.transactionsModule.executeTransaction(e,t,r,o,i)}async executeMultipleClausesTransaction(e,t,r){return await this.transactionsModule.executeMultipleClausesTransaction(e,t,r)}async getLegacyBaseGasPrice(){return await this.transactionsModule.getLegacyBaseGasPrice()}};var oe=class{constructor(e){this.httpClient=e;}async retrieveStorageRange(e){this.validateTarget(e.target,"retrieveStorageRange");let t=`${e.target.blockId}/${e.target.transaction}/${e.target.clauseIndex}`;return await this.httpClient.post(m.debug.post.RETRIEVE_STORAGE_RANGE(),{query:{},body:{target:t,address:e.options?.address?.toString(),keyStart:e.options?.keyStart?.toString(),maxResult:e.options?.maxResult},headers:{}})}async traceContractCall(e,t){return await this.httpClient.post(m.debug.post.TRACE_CONTRACT_CALL(),{query:{},body:{to:e.target?.to?.toString(),data:e.target?.data?.toString(),value:typeof e.target?.value?.wei=="bigint"?HexUInt.of(e.target.value.wei).toString():void 0,name:t,gas:e.options?.gas,gasPrice:e.options?.gasPrice,caller:e.options?.caller,provedWork:e.options?.provedWork,gasPayer:e.options?.gasPayer,expiration:e.options?.expiration,blockRef:e.options?.blockRef,config:e.config},headers:{}})}async traceTransactionClause(e,t){this.validateTarget(e.target,"traceTransactionClause");let r=`${e.target.blockId}/${e.target.transaction}/${e.target.clauseIndex}`;return await this.httpClient.post(m.debug.post.TRACE_TRANSACTION_CLAUSE(),{query:{},body:{target:r,name:t,config:e.config},headers:{}})}validateTarget(e,t){if(typeof e.transaction=="number"&&e.transaction<0)throw new InvalidDataType("DebugModule.validateTarget()",`invalid transaction index '${e.transaction}' given as input for ${t}.`,{transaction:e.transaction,functionName:t});if(e.clauseIndex<0)throw new InvalidDataType("DebugModule.validateTarget()",`invalid clause index '${e.clauseIndex}' given as input for ${t}.`,{clauseIndex:e.clauseIndex,functionName:t})}};var ie=class{httpClient;transactionsModule;constructor(e){this.httpClient=e,this.transactionsModule=null;}setTransactionsModule(e){this.transactionsModule=e;}async estimateGas(e,t,r){if(this.transactionsModule==null)throw new InvalidDataType("estimateGas()","Transactions module not set",{});return await this.transactionsModule.estimateGas(e,t,r)}async getMaxPriorityFeePerGas(){let e=await this.httpClient.get("/fees/priority");if(e==null||typeof e!="object")throw new InvalidDataType("getMaxPriorityFeePerGas()","Invalid response format from /fees/priority endpoint",{response:e});if(e.maxPriorityFeePerGas===void 0||e.maxPriorityFeePerGas===null||e.maxPriorityFeePerGas===""||typeof e.maxPriorityFeePerGas!="string")throw new InvalidDataType("getMaxPriorityFeePerGas()","Missing or invalid maxPriorityFeePerGas in response",{response:e});return e.maxPriorityFeePerGas}async getFeeHistory(e){if(e==null||typeof e.blockCount!="number"||!Number.isFinite(e.blockCount)||e.blockCount<=0)throw new InvalidDataType("getFeeHistory()","Invalid blockCount parameter",{options:e});if(e.newestBlock!==null&&e.newestBlock!==void 0&&!Revision.isValid(e.newestBlock))throw new InvalidDataType("getFeeHistory()",'Invalid revision. The revision must be a string representing a block number or block id (also "best" is accepted which represents the best block & "finalized" for the finalized block).',{options:e});let t=await this.httpClient.http("GET",m.fees.get.FEES_HISTORY(e.blockCount,e.newestBlock,e.rewardPercentiles));if(t==null||typeof t!="object")throw new InvalidDataType("getFeeHistory()","Invalid response format from /fees/history endpoint",{response:t});return t}async getNextBlockBaseFeePerGas(){let e={blockCount:1,newestBlock:"next"},t=await this.getFeeHistory(e);return t.baseFeePerGas===null||t.baseFeePerGas===void 0||t.baseFeePerGas.length===0?null:HexUInt.of(t.baseFeePerGas[0]).bi}};var ae=class{blocksModule;constructor(e){this.blocksModule=e;}async filterRawEventLogs(e){return await this.blocksModule.httpClient.http("POST",m.logs.post.EVENT_LOGS(),{query:{},body:e,headers:{}})}async filterEventLogs(e){let t=e.criteriaSet?.map(i=>i.eventAbi),r=await this.getRawEventLogs(e),o=[];if(t!==void 0){let i=this.removeDuplicatedAbis(t);r.forEach(a=>{let s=i.get(a.topics[0]);if(s==null)throw new InvalidAbiItem("LogsModule.filterEventLogs","Topic not found in the provided ABIs.",{type:"event",value:a.topics[0]});a.decodedData=s.decodeEventLogAsArray({data:Hex.of(a.data),topics:a.topics.map(l=>Hex.of(l))}),o.push(a);});}return o}async filterGroupedEventLogs(e){let t=e.criteriaSet?.map(i=>i.eventAbi),r=await this.getRawEventLogs(e),o=new Map;if(t!==void 0){let i=this.removeDuplicatedAbis(t);i.forEach(a=>o.set(a.signatureHash,[])),r.forEach(a=>{let s=i.get(a.topics[0]);if(s==null)throw new InvalidAbiItem("LogsModule.filterGroupedEventLogs","Topic not found in the provided ABIs.",{type:"event",value:a.topics[0]});a.decodedData=s.decodeEventLogAsArray({data:Hex.of(a.data),topics:a.topics.map(l=>Hex.of(l))}),o.get(a.topics[0])?.push(a);});}return Array.from(o.values())}async getRawEventLogs(e){let t=e.criteriaSet?.map(o=>o.criteria),r={range:e.range??{unit:"block",from:0,to:(await this.blocksModule.getBestBlockCompressed())?.number},criteriaSet:t,options:e.options,order:e.order??"asc"};return await this.filterRawEventLogs(r)}removeDuplicatedAbis(e){let t=new Map;return e.forEach(r=>{t.has(r.signatureHash)||t.set(r.signatureHash,r);}),t}async filterTransferLogs(e){return await this.blocksModule.httpClient.http("POST",m.logs.post.TRANSFER_LOGS(),{query:{},body:e,headers:{}})}};var er=new WeakMap,se=class{blocksModule;constructor(e){this.blocksModule=e;}async getNodes(){return await this.blocksModule.httpClient.http("GET",m.nodes.get.NODES())??[]}async isHealthy(){let e=await this.blocksModule.getBestBlockCompressed(),t=this.getTimestampFromBlock(e),r=Math.floor(Date.now()/1e3)-t;return Math.abs(r)<30}getTimestampFromBlock=e=>{if(e==null||typeof e!="object"||!("timestamp"in e)||typeof e.timestamp!="number")throw new InvalidDataType("NodesModule.getTimestampFromBlock()","Sending failed: Input must be a valid raw transaction in hex format.",{response:e});return e?.timestamp};async getChaintag(){let e=er.get(this.blocksModule);if(e!==void 0)return e;let t=await this.blocksModule.getGenesisBlock();if(!t?.id)throw new InvalidDataType("NodesModule.getChaintag()","The genesis block id is null or undefined. Unable to get the chain tag.",{url:this.blocksModule.httpClient.baseURL});let r=+`0x${t.id.slice(-2)}`;if(Number.isNaN(r))throw new InvalidDataType("NodesModule.getChaintag()","Invalid genesis block id. Unable to derive chain tag.",{id:t.id});return er.set(this.blocksModule,r),r}};var st=Keccak256.of(Txt.of("Error(string)").bytes).toString().slice(0,10),ct=Keccak256.of(Txt.of("Panic(uint256)").bytes).toString().slice(0,10);function lt(n){if(n.startsWith(st))return ABI.ofEncoded("string","0x"+n.slice(st.length)).getFirstDecodedValue();if(n.startsWith(ct)){let e=ABI.ofEncoded("uint256","0x"+n.slice(ct.length)).getFirstDecodedValue();return `Panic(0x${parseInt(e).toString(16).padStart(2,"0")})`}}var ce=class{blocksModule;debugModule;logsModule;gasModule;forkDetector;constructor(e,t,r,o,i){this.blocksModule=e,this.debugModule=t,this.logsModule=r,this.gasModule=o,this.forkDetector=i;}async getTransaction(e,t){if(!ThorId.isValid(e))throw new InvalidDataType("TransactionsModule.getTransaction()","Invalid transaction ID given as input. Input must be an hex string of length 64.",{id:e});if(t?.head!==void 0&&!ThorId.isValid(t.head))throw new InvalidDataType("TransactionsModule.getTransaction()","Invalid head given as input. Input must be an hex string of length 64.",{head:t?.head});return await this.blocksModule.httpClient.http("GET",m.transactions.get.TRANSACTION(e),{query:T({raw:false,head:t?.head,pending:t?.pending})})}async getTransactionRaw(e,t){if(!ThorId.isValid(e))throw new InvalidDataType("TransactionsModule.getTransactionRaw()","Invalid transaction ID given as input. Input must be an hex string of length 64.",{id:e});if(t?.head!==void 0&&!ThorId.isValid(t.head))throw new InvalidDataType("TransactionsModule.getTransaction()","Invalid head given as input. Input must be an hex string of length 64.",{head:t?.head});return await this.blocksModule.httpClient.http("GET",m.transactions.get.TRANSACTION(e),{query:T({raw:true,head:t?.head,pending:t?.pending})})}async getTransactionReceipt(e,t){if(!ThorId.isValid(e))throw new InvalidDataType("TransactionsModule.getTransactionReceipt()","Invalid transaction ID given as input. Input must be an hex string of length 64.",{id:e});if(t?.head!==void 0&&!ThorId.isValid(t.head))throw new InvalidDataType("TransactionsModule.getTransaction()","Invalid head given as input. Input must be an hex string of length 64.",{head:t?.head});try{return await this.blocksModule.httpClient.http("GET",m.transactions.get.TRANSACTION_RECEIPT(e),{query:T({head:t?.head})})}catch(r){if(r instanceof HttpNetworkError)return null;throw r}}async sendRawTransaction(e){if(!Hex.isValid0x(e))throw new InvalidDataType("TransactionsModule.sendRawTransaction()","Sending failed: Input must be a valid raw transaction in hex format.",{raw:e});try{Transaction.decode(HexUInt.of(e.slice(2)).bytes,!0);}catch(r){throw new InvalidDataType("TransactionsModule.sendRawTransaction()","Sending failed: Input must be a valid raw transaction in hex format. Decoding error encountered.",{raw:e},r)}let t=await this.blocksModule.httpClient.http("POST",m.transactions.post.TRANSACTION(),{body:{raw:e}});return {id:t.id,wait:async r=>await this.waitForTransaction(t.id,r)}}async sendTransaction(e){if(!e.isSigned)throw new InvalidDataType("TransactionsModule.sendTransaction()","Invalid transaction given as input. Transaction must be signed.",{signedTx:e});let t=Hex.of(e.encoded).toString();return await this.sendRawTransaction(t)}async waitForTransaction(e,t){if(!ThorId.isValid(e))throw new InvalidDataType("TransactionsModule.waitForTransaction()","Invalid transaction ID given as input. Input must be an hex string of length 64.",{txID:e});let r=t?.timeoutMs??3e4,o=t?.intervalMs??1e3,a=Date.now()+r;for(;;){if(Date.now()>=a)return null;let s=await this.getTransactionReceipt(e).catch(()=>null);if(s!==null)return s;await new Promise(l=>setTimeout(l,o));}}async buildTransactionBody(e,t,r){let o=await this.blocksModule.getBlockCompressed(0);if(o===null)throw new InvalidTransactionField("TransactionsModule.buildTransactionBody()","Error while building transaction body: Cannot get genesis block.",{fieldName:"genesisBlock",genesisBlock:o,clauses:e,options:r});let i=r?.blockRef??await this.blocksModule.getBestBlockRef();if(i===null)throw new InvalidTransactionField("TransactionsModule.buildTransactionBody()","Error while building transaction body: Cannot get blockRef.",{fieldName:"blockRef",blockRef:i,clauses:e,options:r});let a=r?.chainTag??+`0x${o.id.slice(-2)}`,s=await this.fillDefaultBodyOptions(r),l;return Array.isArray(e)?l=e.map(d=>({to:d.to,data:d.data,value:d.value})):l=[{to:e.to,data:e.data,value:e.value}],{blockRef:i,chainTag:a,clauses:await this.resolveNamesInClauses(l),dependsOn:r?.dependsOn??null,expiration:r?.expiration??32,gas:r?.gas!==void 0?Number(r.gas):t,gasPriceCoef:s?.gasPriceCoef,maxFeePerGas:s?.maxFeePerGas,maxPriorityFeePerGas:s?.maxPriorityFeePerGas,nonce:r?.nonce??Hex.random(8).toString(),reserved:r?.isDelegated===true?{features:1}:void 0}}async fillTransactionBody(e){let t={maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,gasPriceCoef:e.gasPriceCoef},r=await this.fillDefaultBodyOptions(t);return {...e,...r}}async fillDefaultBodyOptions(e){e??={};let t=e.maxFeePerGas!==void 0,r=e.maxPriorityFeePerGas!==void 0,o=e.gasPriceCoef!==void 0;if(r&&o&&!t)throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid parameter combination: maxPriorityFeePerGas and gasPriceCoef cannot be used together without maxFeePerGas.",{options:e});if(t&&o&&!r)throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid parameter combination: maxFeePerGas and gasPriceCoef cannot be used together without maxPriorityFeePerGas.",{options:e});if(r&&t&&o)e.gasPriceCoef=void 0;else if(r&&t)e.gasPriceCoef=void 0;else if(o&&!r&&!t)return e.maxFeePerGas=void 0,e.maxPriorityFeePerGas=void 0,e;let i=await this.forkDetector.isGalacticaForked("best");if(!i&&(t||r))throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid transaction body options. Dynamic fee tx is not allowed before Galactica fork.",{options:e});if(!i&&!o)return e.gasPriceCoef=0,e;if(i&&t&&r)return e;e.gasPriceCoef=void 0;let a=await this.gasModule.getNextBlockBaseFeePerGas();if(a==null)throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid transaction body options. Unable to get next block base fee per gas.",{options:e});if(e.maxPriorityFeePerGas===void 0||e.maxPriorityFeePerGas===null){let s=await this.calculateDefaultMaxPriorityFeePerGas(a);e.maxPriorityFeePerGas=s;}if(e.maxFeePerGas===void 0||e.maxFeePerGas===null){let s=HexUInt.of(e.maxPriorityFeePerGas).bi,l=112n*a/100n+s;e.maxFeePerGas=HexUInt.of(l).toString();}return e}async calculateDefaultMaxPriorityFeePerGas(e){let t=await this.gasModule.getFeeHistory({blockCount:10,newestBlock:"best",rewardPercentiles:[25,50,75]}),r;if(t.reward!==null&&t.reward!==void 0&&t.reward.length>0){let a=t.reward[t.reward.length-1];if(new Set(a).size===3)r=HexUInt.of(a[2]).bi;else {let l=0n,d=0;for(let p of t.reward)p.length!==null&&p.length>2&&p[2]!==null&&p[2]!==void 0&&(l+=HexUInt.of(p[2]).bi,d++);r=d>0?l/BigInt(d):0n;}}else r=HexUInt.of(await this.gasModule.getMaxPriorityFeePerGas()).bi;let o=e*46n/1000n,i=o<r?o:r;return HexUInt.of(i).toString()}async resolveNamesInClauses(e){let t=e.reduce((i,a)=>(typeof a.to=="string"&&!i.has(a.to)&&a.to.includes(".")&&i.set(a.to,a.to),i),new Map),r=[...t.keys()];return t.size===0?e:((await I.resolveNames(this.blocksModule,this,r)).forEach((i,a)=>{i!==null&&t.set(r[a],i);}),e.map(i=>typeof i.to!="string"?i:{to:t.get(i.to)??i.to,data:i.data,value:i.value}))}async simulateTransaction(e,t){let{revision:r,caller:o,gasPrice:i,gasPayer:a,gas:s,blockRef:l,expiration:d,provedWork:p}=t??{};if(r!=null&&!Revision.isValid(r.toString()))throw new InvalidDataType("TransactionsModule.simulateTransaction()","Invalid revision given as input. Input must be a valid revision (i.e., a block number or block ID).",{revision:r});return await this.blocksModule.httpClient.http("POST",m.accounts.post.SIMULATE_TRANSACTION(r?.toString()),{query:T({revision:r?.toString()}),body:{clauses:await this.resolveNamesInClauses(e.map(g=>({to:g.to,data:g.data,value:BigInt(g.value).toString()}))),gas:s,gasPrice:i,caller:o,provedWork:p,gasPayer:a,expiration:d,blockRef:l}})}decodeRevertReason(e,t){if(e.startsWith(Re))return ABI.ofEncoded("string",`0x${e.slice(Re.length)}`).getFirstDecodedValue();if(e.startsWith(ke)){let r=ABI.ofEncoded("uint256",`0x${e.slice(ke.length)}`).getFirstDecodedValue();return `Panic(0x${parseInt(r).toString(16).padStart(2,"0")})`}else if(t!==void 0)return new Interface([ErrorFragment.from(t)]).decodeErrorResult(ErrorFragment.from(t),e).toArray()[0];return ""}async getRevertReason(e,t){let r=this.blocksModule,o=this.debugModule,i=await this.getTransaction(e),a=i!==null?await r.getBlockExpanded(i.meta.blockID):null;if(a===null||i===null)return null;let s=F(w.formatToRPCStandard(a,""),e);for(let l=0;l<i.clauses.length;l++){let d=await o.traceTransactionClause({target:{blockId:ThorId.of(a.id),transaction:s,clauseIndex:l},config:{OnlyTopCall:true}},"call");if(d.output!==void 0)return this.decodeRevertReason(d.output,t)}return null}async estimateGas(e,t,r){let o=e.map(p=>{if(p===void 0)throw new InvalidDataType("TransactionsModule.estimateGas()","Invalid ContractClause provided: missing inner clause.",{clause:p});return "clause"in p?p.clause:p});if(o.length===0)throw new InvalidDataType("TransactionsModule.estimateGas()","Invalid clauses. Clauses must be an array with at least one clause.",{clauses:e,caller:t,options:r});if(r?.gasPadding!==void 0&&(r.gasPadding<=0||r.gasPadding>1))throw new InvalidDataType("GasModule.estimateGas()","Invalid gasPadding. gasPadding must be a number between (0, 1].",{gasPadding:r?.gasPadding});let i=await this.simulateTransaction(o,{caller:t,...r}),a=i.some(p=>p.reverted),s=Number(Transaction.intrinsicGas(o).wei),l=i.reduce((p,g)=>p+g.gasUsed,0),d=Math.ceil((s+(l!==0?l+15e3:0))*(1+(r?.gasPadding??0)));return a?{totalGas:d,reverted:true,revertReasons:i.map(p=>lt(p.data)??""),vmErrors:i.map(p=>p.vmError)}:{totalGas:d,reverted: