@vechain/sdk-network
Version:
This module serves as the standard interface connecting decentralized applications (dApps) and users to the VeChainThor blockchain
10 lines (9 loc) • 96.6 kB
JavaScript
import { InvalidHTTPParams, InvalidHTTPRequest, InvalidDataType, CannotFindTransaction, ContractDeploymentFailed, InvalidAbiItem, InvalidTransactionField, NotDelegatedTransaction, JSONRPCInvalidParams, SignerMethodError, InvalidSecp256k1PrivateKey, stringifyData, JSONRPCInvalidDefaultBlock, JSONRPCInternalError, JSONRPCMethodNotImplemented, JSONRPCServerError, JSONRPCMethodNotFound, VechainSDKError, PollExecution, ContractCallError } from '@vechain/sdk-errors';
import { Keccak256, Txt, MAINNET_NETWORK, TESTNET_NETWORK, SOLO_NETWORK, VET, Units, FixedPointNumber, VTHO, HexUInt, Revision, ABIContract, Clause, Transaction, Hex, ThorId, ABI, Address, dataUtils, Secp256k1, HDKey, HexInt, ABIEvent, ABIItem, ABIFunction, ZERO_ADDRESS, Quantity, ZERO_BYTES, 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 Ir=Object.defineProperty;var Br=(n,e)=>{for(var t in e)Ir(n,t,{get:e[t],enumerable:!0});};var Rr={};Br(Rr,{AccountDetail:()=>j,AccountsModule:()=>K,BUILT_IN_CONTRACTS:()=>ge,BlocksModule:()=>z,CHAIN_ID:()=>Ie,CHAIN_TAG:()=>Be,Contract:()=>I,ContractFactory:()=>G,ContractsModule:()=>X,DebugModule:()=>Z,DefaultBlockToRevision:()=>h,DelegationHandler:()=>V,ERROR_SELECTOR:()=>ye,ForkDetector:()=>H,GasModule:()=>ee,HTTPS_REGEX:()=>Ge,HTTP_REGEX:()=>he,HardhatVeChainProvider:()=>on,HttpMethod:()=>C,JSONRPCEthersProvider:()=>nt,LogsModule:()=>te,MAINNET_URL:()=>Mr,NODE_HEALTHCHECK_TOLERANCE_IN_SECONDS:()=>Le,NodesModule:()=>ne,PANIC_SELECTOR:()=>be,POLLING_INTERVAL:()=>rt,Poll:()=>x,ProviderInternalBaseWallet:()=>ce,ProviderInternalHDWallet:()=>tt,RPCMethodsMap:()=>nn,RPC_DOCUMENTATION_URL:()=>l,RPC_METHODS:()=>N,SimpleHttpClient:()=>E,TESTNET_URL:()=>Ur,THOR_SOLO_URL:()=>Gr,ThorClient:()=>oe,TransactionsModule:()=>re,VeChainAbstractSigner:()=>ae,VeChainPrivateKeySigner:()=>se,VeChainProvider:()=>$,blocksFormatter:()=>b,buildQuery:()=>y,chainTagToChainId:()=>it,debugFormatter:()=>de,debugTraceBlockByHash:()=>pt,debugTraceBlockByNumber:()=>mt,debugTraceCall:()=>ft,debugTraceTransaction:()=>M,engineGetPayloadBodiesByHashV1:()=>Ci,engineGetPayloadBodiesByRangeV1:()=>vi,ethAccounts:()=>pe,ethBlockNumber:()=>gt,ethCall:()=>bt,ethChainId:()=>f,ethEstimateGas:()=>Tt,ethFeeHistory:()=>Pt,ethGasPrice:()=>wt,ethGetBalance:()=>Ct,ethGetBlockByHash:()=>P,ethGetBlockByNumber:()=>w,ethGetBlockReceipts:()=>xt,ethGetBlockTransactionCountByHash:()=>vt,ethGetBlockTransactionCountByNumber:()=>Rt,ethGetCode:()=>kt,ethGetFilterChanges:()=>Wi,ethGetFilterLogs:()=>zi,ethGetLogs:()=>me,ethGetStorageAt:()=>It,ethGetTransactionByBlockHashAndIndex:()=>Bt,ethGetTransactionByBlockNumberAndIndex:()=>At,ethGetTransactionByHash:()=>U,ethGetTransactionCount:()=>St,ethGetTransactionReceipt:()=>D,ethGetUncleByBlockHashAndIndex:()=>_t,ethGetUncleByBlockNumberAndIndex:()=>Et,ethGetUncleCountByBlockHash:()=>Nt,ethGetUncleCountByBlockNumber:()=>Ot,ethMaxPriorityFeePerGas:()=>Ft,ethRequestAccounts:()=>Dt,ethSendRawTransaction:()=>Mt,ethSendTransaction:()=>Ut,ethSignTransaction:()=>Lt,ethSignTypedDataV4:()=>Vt,ethSubscribe:()=>qt,ethSyncing:()=>Jt,ethUnsubscribe:()=>$t,evmMine:()=>De,formatToLogsRPC:()=>ct,formatToRPCStandard:()=>st,getCachedChainId:()=>ut,getCachedChainTag:()=>ti,getCriteriaSetForInput:()=>lt,getNumberOfLogsAheadOfTransactionIntoBlockExpanded:()=>at,getTransactionIndexIntoBlock:()=>S,netListening:()=>Wt,netPeerCount:()=>Kt,netVersion:()=>zt,sanitizeWebsocketBaseURL:()=>k,signerUtils:()=>Ue,subscriptions:()=>jr,thorest:()=>u,toQueryString:()=>R,transactionsFormatter:()=>F,txPoolContent:()=>Yt,txPoolContentFrom:()=>Qt,txPoolInspect:()=>Xt,txPoolStatus:()=>Zt,vnsUtils:()=>v,web3ClientVersion:()=>en,web3Sha3:()=>tn});var C=(t=>(t.GET="GET",t.POST="POST",t))(C||{});var E=class n{static DEFAULT_TIMEOUT=3e4;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 !1}}async http(e,t,r){let o=new AbortController,i=setTimeout(()=>{o.abort();},this.timeout),a;try{t.startsWith("/")&&(t=t.slice(1));let s=this.baseURL;s.endsWith("/")||(s+="/"),a=new URL(t,s),r?.query!=null&&Object.entries(r.query).forEach(([d,m])=>{a.searchParams.append(d,String(m));});let p=new Headers(this.headers);r?.headers!==void 0&&r?.headers!=null&&Object.entries(r.headers).forEach(([d,m])=>{p.append(d,String(m));});}catch(s){throw new InvalidHTTPParams("HttpClient.http()",s.message,{method:e,url:this.isValidUrl(this.baseURL)?new URL(t,this.baseURL).toString():t},s)}try{let s=await fetch(a,{method:e,headers:r?.headers,body:e!=="GET"?JSON.stringify(r?.body):void 0,signal:o.signal});if(s.ok){let d=Object.fromEntries(s.headers.entries());return r?.validateResponseHeader!=null&&d!=null&&r.validateResponseHeader(d),await s.json()}let p=await s.clone().text();throw new Error(`HTTP ${s.status} ${s.statusText} ${p}`,{cause:s})}catch(s){throw new InvalidHTTPRequest("HttpClient.http()",s.message,{method:e,url:this.isValidUrl(this.baseURL)?new URL(t,this.baseURL).toString():t},s)}finally{clearTimeout(i);}}async post(e,t){return await this.http("POST",e,t)}};function an(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 Ue={transactionBodyToTransactionRequestInput:an};var N=(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))(N||{});var j=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 Nr="0x0000000000000000000000000000506172616d73",Or="0x0000000000000000000000000000456e65726779",Fr=[{constant:!1,inputs:[{name:"_key",type:"bytes32"},{name:"_value",type:"uint256"}],name:"set",outputs:[],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_key",type:"bytes32"}],name:"get",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"executor",outputs:[{name:"",type:"address"}],payable:!1,stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"key",type:"bytes32"},{indexed:!1,name:"value",type:"uint256"}],name:"Set",type:"event"}],Dr=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"pure",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"success",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"transferFrom",outputs:[{name:"success",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"pure",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"pure",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"transfer",outputs:[{name:"success",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_amount",type:"uint256"}],name:"move",outputs:[{name:"success",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalBurned",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"remaining",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,name:"_from",type:"address"},{indexed:!0,name:"_to",type:"address"},{indexed:!1,name:"_value",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"_owner",type:"address"},{indexed:!0,name:"_spender",type:"address"},{indexed:!1,name:"_value",type:"uint256"}],name:"Approval",type:"event"}],ge={PARAMS_ABI:Fr,PARAMS_ADDRESS:Nr,ENERGY_ABI:Dr,ENERGY_ADDRESS:Or};var he=/^http:\/\//,Ge=/^https:\/\//;var Le=30;var ye=Keccak256.of(Txt.of("Error(string)").bytes).toString().slice(0,10),be=Keccak256.of(Txt.of("Panic(uint256)").bytes).toString().slice(0,10);var Mr="https://mainnet.vechain.org",Ur="https://testnet.vechain.org",Gr="http://localhost:8669";var l="https://ethereum.github.io/execution-apis/api-documentation/";var y=n=>{let e={};for(let t in n)n[t]!==void 0&&(e[t]=n[t]);return e};async function Vr(n){await new Promise(e=>setTimeout(e,n));}function dn(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=!1,i=Date.now();return {waitUntil:async a=>{try{do{r=await n(),await Vr(e?.requestIntervalInMilliseconds??1e3),t=t+1;let s=a(r),p=e?.maximumIterations!==void 0?t>=e.maximumIterations:!1,d=e?.maximumWaitingTimeInMilliseconds!==void 0&&Date.now()-i>=e.maximumWaitingTimeInMilliseconds;o=!(s||p||d);}while(o);return r}catch(s){throw new PollExecution("SyncPoll.waitUntil()","Polling failed: Function execution error encountered during synchronous polling.",{functionName:n.name},s)}}}}var He=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){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()=>await this._intervalLoop())();},this.requestIntervalInMilliseconds);});}stopListen(){clearInterval(this.intervalId),this.emit("stop",{eventPoll:this});}};function pn(n,e,t=!0){return new He(n,e,t)}var x={SyncPoll:dn,createEventPoll:pn};var R=n=>{let e=Object.entries(n).filter(([,t])=>t!==void 0).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`);return e.length>0?`?${e.join("&")}`:""},k=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=he.exec(n)!==null?n.replace(he,"ws://"):n.replace(Ge,"wss://"),n};var u={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=R({pos:e});return `${k(n)}/subscriptions/block${t}`},EVENT:(n,e)=>{let t=R({pos:e?.position,addr:e?.contractAddress,t0:e?.topic0,t1:e?.topic1,t2:e?.topic2,t3:e?.topic3,t4:e?.topic4});return `${k(n)}/subscriptions/event${t}`},VET_TRANSFER:(n,e)=>{let t=R({pos:e?.position,txOrigin:e?.signerAddress,sender:e?.sender,recipient:e?.receiver});return `${k(n)}/subscriptions/transfer${t}`},BEAT_LEGACY:(n,e)=>{let t=R({pos:e});return `${k(n)}/subscriptions/beat${t}`},BEAT:(n,e)=>{let t=R({pos:e});return `${k(n)}/subscriptions/beat2${t}`},NEW_TRANSACTIONS:n=>`${k(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${R({blockCount:n,newestBlock:e,rewardPercentiles:t?.join(",")})}`}}};var mn=(n,e)=>u.subscriptions.get.BEAT_LEGACY(n,e?.blockID),fn=(n,e)=>u.subscriptions.get.BEAT(n,e?.blockID);var gn=(n,e)=>u.subscriptions.get.BLOCK(n,e?.blockID);var yn=(n,e,t,r)=>{let i=(typeof e=="string"?new ABIEvent(e):new ABIEvent(e)).encodeFilterTopicsNoNull(t??[]);return u.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 bn=n=>u.subscriptions.get.NEW_TRANSACTIONS(n);var Tn=(n,e)=>u.subscriptions.get.VET_TRANSFER(n,{position:e?.blockID,signerAddress:e?.signerAddress,sender:e?.sender,receiver:e?.recipient});var jr={getEventSubscriptionUrl:yn,getBlockSubscriptionUrl:gn,getNewTransactionsSubscriptionUrl:bn,getVETtransfersSubscriptionUrl:Tn,getLegacyBeatSubscriptionUrl:mn,getBeatSubscriptionUrl:fn};var W={[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 Qr=async(n,e)=>{let[t]=await v.resolveNames(n.blocks,n.transactions,[e]);return t??null},Xr=async(n,e,t)=>{let r=await n.getGenesisBlock();if(r===null||!Address.isValid(W[r.id]?.resolveUtils))return t.map(()=>null);let o=W[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)},Zr=async(n,e)=>{let[t]=await v.lookupAddresses(n,[e]);return t??null},eo=async(n,e)=>{let t=await n.blocks.getGenesisBlock();if(t===null||!Address.isValid(W[t.id]?.resolveUtils))return e.map(()=>null);let r=W[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)},v={resolveName:Qr,resolveNames:Xr,lookupAddress:Zr,lookupAddresses:eo};var K=class{constructor(e){this.httpClient=e;}async getAccount(e,t){let r=t?.revision?.toString();return new j(await this.httpClient.get(u.accounts.get.ACCOUNT_DETAIL(e.toString()),{query:y({revision:r})}))}async getBytecode(e,t){let r=t?.revision?.toString(),o=await this.httpClient.get(u.accounts.get.ACCOUNT_BYTECODE(e.toString()),{query:y({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(u.accounts.get.STORAGE_AT(e.toString(),o),{query:y({pos:o,revision:i})});return HexUInt.of(a.value)}};var z=class{constructor(e,t){this.httpClient=e;this.onBlockError=t?.onBlockError,t?.isPollingEnabled===!0&&this.setupPolling();}headBlock=null;onBlockError;pollInstance;destroy(){this.pollInstance!=null&&this.pollInstance.stopListen();}setupPolling(){this.pollInstance=x.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",u.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",u.blocks.get.BLOCK_DETAIL(e),{query:y({expanded:!0})})}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 x.SyncPoll(async()=>t?await this.getBestBlockCompressed():await this.getBestBlockExpanded(),{requestIntervalInMilliseconds:r?.intervalMs,maximumWaitingTimeInMilliseconds:r?.timeoutMs}).waitUntil(o=>o!=null&&o?.number>=e)}async waitForBlockCompressed(e,t){return await this._waitForBlock(e,!1,t)}async waitForBlockExpanded(e,t){return await this._waitForBlock(e,!0,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 Te=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 Y(n){return new Proxy(n.read,{get:(e,t)=>async(...r)=>{let o=$e(r),i=o.clauseAdditionalOptions?.comment,a=o.clauseAdditionalOptions?.revision,s=n.getFunctionAbi(t),p=await n.contractsModule.executeCall(n.address,s,o.args,{caller:n.getSigner()!==void 0?await n.getSigner()?.getAddress():void 0,...n.getContractReadOptions(),comment:i,revision:a,includeABI:!0});if(!p.success)throw new ContractCallError(s.stringSignature,p.result.errorMessage,{contractAddress:n.address});return p.result.array}})}function Q(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=$e(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:!0})}})}function vn(n){return new Proxy(n.filters,{get:(e,t)=>r=>{let o=In(n,t,r);return new Te(n,[o])}})}function Rn(n){return new Proxy(n.clause,{get:(e,t)=>(...r)=>{let o=n.getContractTransactOptions(),i=$e(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:!0}),functionAbi:n.getFunctionAbi(t)}}})}function kn(n){return new Proxy(n.criteria,{get:(e,t)=>r=>In(n,t,r)})}function In(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 $e(n){let e=so(n),t=co(n),r=lo(n);return (e!==void 0||t!==void 0||r!==void 0)&&(n=n.filter(o=>!(Bn(o)||An(o)||Sn(o)))),{args:n,clauseAdditionalOptions:{value:e?.value,comment:t?.comment,revision:r?.revision}}}function so(n){return n.find(e=>Bn(e))}function co(n){return n.find(e=>An(e))}function lo(n){return n.find(e=>Sn(e))}function Bn(n){return n.value!==void 0}function An(n){return n.comment!==void 0}function Sn(n){return n.revision!==void 0}var I=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=Y(this),this.transact=Q(this),this.filters=vn(this),this.clause=Rn(this),this.criteria=kn(this);}setContractReadOptions(e){return this.contractCallOptions=e,this.read=Y(this),this.contractCallOptions}getContractReadOptions(){return this.contractCallOptions}clearContractReadOptions(){this.contractCallOptions={},this.read=Y(this);}setContractTransactOptions(e){return this.contractTransactionOptions=e,this.transact=Q(this),this.contractTransactionOptions}getContractTransactOptions(){return this.contractTransactionOptions}clearContractTransactOptions(){this.contractTransactionOptions={},this.transact=Q(this);}setSigner(e){return this.signer=e,this.transact=Q(this),this.read=Y(this),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 G=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()),i=await this.contractsModule.transactionsModule.buildTransactionBody([r],o.totalGas,t),a=await this.signer.signTransaction(Ue.transactionBodyToTransactionRequestInput(i,await this.signer.getAddress()));return this.deployTransaction=await this.contractsModule.transactionsModule.sendTransaction(Transaction.decode(HexUInt.of(a.slice(2)).bytes,!0)),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 I(e?.outputs[0].contractAddress,this.abi,this.contractsModule,this.signer,e)}getDeployTransaction(){return this.deployTransaction}};var X=class{constructor(e){this.transactionsModule=e;}createContractFactory(e,t,r){return new G(e,t,r,this)}load(e,t,r){return new I(e,t,this,r)}async executeCall(e,t,r,o){return await this.transactionsModule.executeCall(e,t,r,o)}async executeMultipleClausesCall(e,t){return 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 Z=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(u.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(u.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(u.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 ee=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",u.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}};var te=class{blocksModule;constructor(e){this.blocksModule=e;}async filterRawEventLogs(e){return await this.blocksModule.httpClient.http("POST",u.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(p=>Hex.of(p))}),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(p=>Hex.of(p))}),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",u.logs.post.TRANSFER_LOGS(),{query:{},body:e,headers:{}})}};var ne=class{blocksModule;constructor(e){this.blocksModule=e;}async getNodes(){return await this.blocksModule.httpClient.http("GET",u.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}};var je=Keccak256.of(Txt.of("Error(string)").bytes).toString().slice(0,10),We=Keccak256.of(Txt.of("Panic(uint256)").bytes).toString().slice(0,10);function Ke(n){if(n.startsWith(je))return ABI.ofEncoded("string","0x"+n.slice(je.length)).getFirstDecodedValue();if(n.startsWith(We)){let e=ABI.ofEncoded("uint256","0x"+n.slice(We.length)).getFirstDecodedValue();return `Panic(0x${parseInt(e).toString(16).padStart(2,"0")})`}}var re=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",u.transactions.get.TRANSACTION(e),{query:y({raw:!1,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",u.transactions.get.TRANSACTION(e),{query:y({raw:!0,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});return await this.blocksModule.httpClient.http("GET",u.transactions.get.TRANSACTION_RECEIPT(e),{query:y({head:t?.head})})}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",u.transactions.post.TRANSACTION(),{body:{raw:e}});return {id:t.id,wait:async()=>await this.waitForTransaction(t.id)}}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});return await x.SyncPoll(async()=>await this.getTransactionReceipt(e),{requestIntervalInMilliseconds:t?.intervalMs,maximumWaitingTimeInMilliseconds:t?.timeoutMs}).waitUntil(r=>r!==null)}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(64)}`,s=await this.fillDefaultBodyOptions(r);return {blockRef:i,chainTag:a,clauses:await this.resolveNamesInClauses(e),dependsOn:r?.dependsOn??null,expiration:r?.expiration??32,gas:t,gasPriceCoef:s?.gasPriceCoef,maxFeePerGas:s?.maxFeePerGas,maxPriorityFeePerGas:s?.maxPriorityFeePerGas,nonce:r?.nonce??Hex.random(8).toString(),reserved:r?.isDelegated===!0?{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){if(e??={},e.gasPriceCoef!==void 0)return e.maxFeePerGas=void 0,e.maxPriorityFeePerGas=void 0,e;if(e.gasPriceCoef!==void 0&&(e.maxFeePerGas!==void 0||e.maxPriorityFeePerGas!==void 0))throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid transaction body options. Cannot specify both legacy and dynamic fee type options.",{options:e});let t=await this.forkDetector.isGalacticaForked("best");if(!t&&(e.maxFeePerGas!==void 0||e.maxPriorityFeePerGas!==void 0))throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid transaction body options. Dynamic fee tx is not allowed before Galactica fork.",{options:e});if(!t&&(e.gasPriceCoef===void 0||e.gasPriceCoef===null))return e.gasPriceCoef=0,e;if(t&&e.maxFeePerGas!==void 0&&e.maxPriorityFeePerGas!==void 0)return e;e.gasPriceCoef=void 0;let r=await this.blocksModule.getBestBlockBaseFeePerGas();if(r==null)throw new InvalidDataType("TransactionsModule.fillDefaultBodyOptions()","Invalid transaction body options. Unable to get best block base fee per gas.",{options:e});let o=HexUInt.of(r).bi;if(e.maxPriorityFeePerGas===void 0||e.maxPriorityFeePerGas===null){let i=await this.calculateDefaultMaxPriorityFeePerGas(o);e.maxPriorityFeePerGas=i;}if(e.maxFeePerGas===void 0||e.maxFeePerGas===null){let i=HexUInt.of(e.maxPriorityFeePerGas).bi,a=o+i;e.maxFeePerGas=HexUInt.of(a).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 p=0n,d=0;for(let m of t.reward)m.length!==null&&m.length>2&&m[2]!==null&&m[2]!==void 0&&(p+=HexUInt.of(m[2]).bi,d++);r=d>0?p/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 v.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:p,expiration:d,provedWork:m}=t??{};if(r!=null&&!Revision.isValid(r))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",u.accounts.post.SIMULATE_TRANSACTION(r),{query:y({revision:r}),body:{clauses:await this.resolveNamesInClauses(e.map(_=>({to:_.to,data:_.data,value:BigInt(_.value).toString()}))),gas:s,gasPrice:i,caller:o,provedWork:m,gasPayer:a,expiration:d,blockRef:p}})}decodeRevertReason(e,t){if(e.startsWith(ye))return ABI.ofEncoded("string",`0x${e.slice(ye.length)}`).getFirstDecodedValue();if(e.startsWith(be)){let r=ABI.ofEncoded("uint256",`0x${e.slice(be.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=S(b.formatToRPCStandard(a,""),e);for(let p=0;p<i.clauses.length;p++){let d=await o.traceTransactionClause({target:{blockId:ThorId.of(a.id),transaction:s,clauseIndex:p},config:{OnlyTopCall:!0}},"call");if(d.output!==void 0)return this.decodeRevertReason(d.output,t)}return null}async estimateGas(e,t,r){if(e.length<=0)throw new InvalidDataType("GasModule.estimateGas()","Invalid clauses. Clauses must be an array of clauses 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 o=await this.simulateTransaction(e,{caller:t,...r}),i=o.some(d=>d.reverted),a=Number(Transaction.intrinsicGas(e).wei),s=o.reduce((d,m)=>d+m.gasUsed,0),p=Math.ceil((a+(s!==0?s+15e3:0))*(1+(r?.gasPadding??0)));return i?{totalGas:p,reverted:!0,revertReasons:o.map(d=>Ke(d.data)??""),vmErrors:o.map(d=>d.vmError)}:{totalGas:p,reverted:!1,revertReasons:[],vmErrors:[]}}async executeCall(e,t,r,o){let i=await this.simulateTransaction([{to:e,value:"0",data:t.encodeData(r).toString()}],o);return this.getContractCallResult(i[0].data,t,i[0].reverted)}async executeMultipleClausesCall(e,t){return (await this.simulateTransaction(e.map(o=>o.clause),t)).map((o,i)=>this.getContractCallResult(o.data,e[i].functionAbi,o.reverted))}async executeTransaction(e,t,r,o,i){let a=await e.sendTransaction({clauses:[Clause.callFunction(Address.of(t),r,o,VET.of(i?.value??0,Units.wei))],gas:i?.gas,gasLimit:i?.gasLimit,gasPrice:i?.gasPrice,gasPriceCoef:i?.gasPriceCoef,maxFeePerGas:i?.maxFeePerGas,maxPriorityFeePerGas:i?.maxPriorityFeePerGas,nonce:i?.nonce,value:i?.value,dependsOn:i?.dependsOn,expiration:i?.expiration,chainTag:i?.chainTag,blockRef:i?.blockRef,delegationUrl:i?.delegationUrl,comment:i?.comment});return {id:a,wait:async()=>await this.waitForTransaction(a)}}async executeMultipleClausesTransaction(e,t,r){let o=await t.sendTransaction({clauses:e.map(i=>i.clause),gas:r?.gas,gasLimit:r?.gasLimit,gasPrice:r?.gasPrice,gasPriceCoef:r?.gasPriceCoef,maxFeePerGas:r?.maxFeePerGas,maxPriorityFeePerGas:r?.maxPriorityFeePerGas,nonce:r?.nonce,value:r?.value,dependsOn:r?.dependsOn,expiration:r?.expiration,chainTag:r?.chainTag,blockRef:r?.blockRef,delegationUrl:r?.delegationUrl,comment:r?.comment});return {id:o,wait:async()=>await this.waitForTransaction(o)}}async getLegacyBaseGasPrice(){return await this.executeCall(ge.PARAMS_ADDRESS,ABIContract.ofAbi(ge.PARAMS_ABI).getFunction("get"),[dataUtils.encodeBytes32String("base-gas-price","left")])}getContractCallResult(e,t,r){if(r)return {success:!1,result:{errorMessage:Ke(e)??""}};let o=Hex.of(e),i=t.decodeResult(o),a=t.decodeOutputAsArray(o);return {success:!0,result:{plain:i,array:a}}}};var Bo=async(n,e,t,r)=>{let o=Hex.of(n.encoded).toString(),i={origin:t,raw:o};try{let a=await r.http("POST",e,{body:i,headers:{"Content-Type":"application/json"}});return HexUInt.of(a.signature.slice(2)).bytes}catch(a){throw new NotDelegatedTransaction("_getDelegationSignature()","Delegation failed: Cannot get signature from gasPayerUrl.",{gasPayerUrl:e},a)}},V=n=>{let e=n==null,t=!e&&n?.gasPayerServiceUrl!==void 0,r=!e&&n?.gasPayerPrivateKey!==void 0;return {isDelegated:()=>t||r,gasPayerOrUndefined:()=>e?void 0:n,gasPayerOrNull:()=>e?null:n,getDelegationSignatureUsingUrl:async(o,i,a)=>{if(!t)throw new NotDelegatedTransaction("DelegationHandler.getDelegationSignatureUsingUrl()","Delegation with url failed: gasPayerServiceUrl is not defined.",void 0);return await Bo(o,n?.gasPayerServiceUrl,i,a)}}};var Ce=new Map,_o=5*60*1e3,xe=!1,H=class{constructor(e){this.httpClient=e;}async isGalacticaForked(e){if(xe)return !0;if(e===void 0&&(e="best"),!Revision.isValid(e))throw new InvalidDataType("GalacticaForkDetector.isGalacticaForked()","Invalid revision. Must be a valid block number or ID.",{revision:e});let t=String(e),r=Ce.get(t),o=Date.now();if(r!==void 0){if(r.result)return xe=!0,!0;if(o-r.timestamp<_o)return !1}let i=await this.httpClient.http("GET",u.blocks.get.BLOCK_DETAIL(e),{query:y({expanded:!0})});if(i===null)return Ce.set(t,{result:!1,timestamp:o}),!1;let a=i.baseFeePerGas!==void 0;return Ce.set(t,{result:a,timestamp:o}),a&&(xe=!0),a}async detectGalactica(e="best"){return await this.isGalacticaForked(e)}clearCache(){Ce.clear(),xe=!1;}};var oe=class n{constructor(e,t){this.httpClient=e;this.accounts=new K(e),this.debug=new Z(e),this.blocks=new z(e,t),this.logs=new te(this.blocks),this.nodes=new ne(this.blocks),this.gas=new ee(this.httpClient),this.forkDetector=new H(this.httpClient),this.transactions=new re(this.blocks,this.debug,this.logs,this.gas,this.forkDetector),this.gas.setTransactionsModule(this.transactions),this.contracts=new X(this.transactions);}accounts;nodes;blocks;logs;transactions;contracts;forkDetector;gas;debug;static at(e,t){return new n(new E(e),t)}destroy(){this.blocks.destroy();}static fromUrl(e,t){return n.at(e,t)}};var ae=class{MESSAGE_PREFIX=Txt.of(`Ethereum Signed Message:
`).bytes;provider;constructor(e){this.provider=e;}async populateCall(e){if(e.from===void 0||e.from===null)e.from=Address.checksum(HexUInt.of(await this.getAddress()));else if(Address.checksum(HexUInt.of(e.from))!==Address.checksum(HexUInt.of(await this.getAddress())))throw new InvalidDataType("VeChainAbstractSigner.populateCall()","From address does not match the signer address.",{signerAddress:Address.checksum(HexUInt.of(await this.getAddress())),fromAddress:Address.checksum(HexUInt.of(e.from))});return e.to===void 0&&(e.to=null),e.clauses!==void 0&&e.clauses.length>0&&(e.to=e.clauses[0].to,e.value=e.clauses[0].value,e.data=e.clauses[0].data),e}async populateTransaction(e){if(this.provider===void 0)throw new JSONRPCInvalidParams("VechainAbstractSigner.populateTransaction()","Thor client not found into the signer. Please attach a Provider with a thor client to your signer instance.",{provider:this.provider});let t=this.provider.thorClient,r=await this.populateCall(e),o=e.gas!==void 0?Number(e.gas):await this.estimateGas(e);return await t.transactions.buildTransactionBody(r.clauses??this