UNPKG

@vechain/sdk-core

Version:

This module is crafted for dApp development and various blockchain operations that seamlessly unfold offline

1 lines 79.1 kB
import Dn from'fast-json-stable-stringify';import {InvalidOperation,InvalidDataType,InvalidHDKeyMnemonic,InvalidHDKey,InvalidSecp256k1PrivateKey,UnavailableTransactionField,NotDelegatedTransaction,InvalidTransactionField,InvalidSecp256k1MessageHash,InvalidSecp256k1Signature,InvalidRLP,InvalidAbiDataToEncodeOrDecode,InvalidAbiItem,CertificateSignatureMismatch,InvalidTransactionType,stringifyData,InvalidKeystore,InvalidKeystoreParams}from'@vechain/sdk-errors';import {parseAbiParameters,decodeAbiParameters,encodeAbiParameters,toFunctionSignature,parseAbiItem,toFunctionHash,decodeEventLog,encodeEventTopics,decodeFunctionData,encodeFunctionData,decodeFunctionResult,getAbiItem}from'viem';import*as v from'@noble/curves/abstract/utils';import*as ut from'@noble/hashes/utils';import {randomBytes}from'@noble/hashes/utils';import*as te from'@scure/bip32';import*as U from'@scure/bip39';import {base58}from'@scure/base';import*as gt from'@noble/hashes/sha256';import {secp256k1}from'@noble/curves/secp256k1';import {keccak_256}from'@noble/hashes/sha3';import {blake2b}from'@noble/hashes/blake2b';import {RLP}from'@ethereumjs/rlp';import {bytesToNumberBE}from'@noble/ciphers/utils';import {wordlist}from'@scure/bip39/wordlists/english';import {VeChainSDKLogger}from'@vechain/sdk-logging';import {ethers}from'ethers';import {ctr}from'@noble/ciphers/aes';import {scrypt}from'@noble/hashes/scrypt';var Mt=Object.defineProperty;var Xt=(n,e)=>{for(var t in e)Mt(n,t,{get:e[t],enumerable:true});};var _t={};Xt(_t,{ABI:()=>I,ABIContract:()=>N,ABIEvent:()=>x,ABIFunction:()=>w,ABIItem:()=>S,Account:()=>ve,Address:()=>f,Blake2b256:()=>A,BlockId:()=>ae,BlockRef:()=>Re,BloomFilter:()=>ie,BufferKind:()=>O,Certificate:()=>We,Clause:()=>it,Coin:()=>G,CompactFixedHexBlobKind:()=>X,ERC1155_ABI:()=>Ct,ERC20_ABI:()=>Ot,ERC721_ABI:()=>ce,FixedHexBlobKind:()=>C,FixedPointNumber:()=>p,HDKey:()=>K,Hex:()=>s,HexBlobKind:()=>R,HexInt:()=>D,HexUInt:()=>u,Keccak256:()=>P,MAINNET_NETWORK:()=>Ut,Mnemonic:()=>Me,NUMERIC_REGEX:()=>Jn,NumericKind:()=>y,OptionalFixedHexBlobKind:()=>F,Quantity:()=>Xe,RLP:()=>_,RLPProfiler:()=>L,Revision:()=>$e,SOLO_NETWORK:()=>Ht,ScalarKind:()=>h,Secp256k1:()=>d,Sha256:()=>B,TESTNET_NETWORK:()=>kt,ThorId:()=>je,Token:()=>De,Transaction:()=>ot,TransactionType:()=>rt,Txt:()=>l,Units:()=>g,VET:()=>re,VIP180_ABI:()=>ue,VIP181_ABI:()=>zn,VIP210_ABI:()=>qn,VTHO:()=>Z,VTHO_ADDRESS:()=>nt,ZERO_ADDRESS:()=>ni,ZERO_BYTES:()=>Qe,assertCompactFixedHexBlobBuffer:()=>Ke,assertFixedHexBlobKindBuffer:()=>He,assertFixedHexBlobKindData:()=>ke,assertValidHexBlobKindData:()=>Ue,assertValidNumericKindBuffer:()=>Ve,dataUtils:()=>ti,decodeBufferToHexWithLeadingZeros:()=>Nn,decodeBufferToNumberOrHex:()=>Oe,encodeBigIntToBuffer:()=>Le,encodeCompactFixedHexBlob:()=>Ge,fromTransactionType:()=>ui,keystore:()=>Zn,networkInfo:()=>si,toTransactionType:()=>ci,validateNumericKindData:()=>Be});var s=class n{static NEGATIVE=-1;static POSITIVE=1;static PREFIX="0x";static RADIX=16;static REGEX_HEX=/^-?(0x)?[0-9a-f]*$/i;static REGEX_HEX_PREFIX=/^-?0x/i;digits;sign;constructor(e,t,i=r=>r.toLowerCase()){this.digits=i(t),this.sign=e;}get abs(){return new n(n.POSITIVE,this.digits)}get bi(){return BigInt(this.sign)*v.hexToNumber(this.digits)}get bytes(){return v.hexToBytes(this.alignToBytes().digits)}get n(){if(this.isNumber())return new DataView(this.bytes.buffer).getFloat64(0);throw new InvalidOperation("Hex.n","not an IEEE 754 float 64 number",{hex:this.toString()})}alignToBytes(){return this.digits.length%2===0?this:new n(this.sign,"0"+this.digits)}compareTo(e){if(this.sign===e.sign){let t=Math.max(this.digits.length,e.digits.length),i=this.fit(t).bytes,r=e.fit(t).bytes,a=0,o=0;for(;o===0&&a<i.length;)o=i[a]-r[a],a++;return o}return this.sign-e.sign}fit(e){if(e<this.digits.length){let t=0;for(;this.digits.length-t>e&&this.digits.at(t)==="0";)t++;if(this.digits.length-t===e)return new n(this.sign,this.digits.slice(t));throw new InvalidDataType("Hex.fit",`can't fit in ${e} digits`,{digits:e,hex:this})}return e>this.digits.length?new n(this.sign,"0".repeat(e-this.digits.length)+this.digits):this}isEqual(e){return this.compareTo(e)===0}isNumber(){return this.digits.length===32}static isValid(e){return n.REGEX_HEX.test(e)}static isValid0x(e){return n.REGEX_HEX_PREFIX.test(e)&&n.isValid(e)}static of(e){try{if(typeof e=="bigint")return e<0n?new n(this.NEGATIVE,v.numberToHexUnpadded(-1n*e)):new n(this.POSITIVE,v.numberToHexUnpadded(e));if(typeof e=="number"){let t=new DataView(new ArrayBuffer(16));return t.setFloat64(0,e),new n(e<0?this.NEGATIVE:this.POSITIVE,v.bytesToHex(new Uint8Array(t.buffer)))}else if(typeof e=="string"){if(!this.isValid(e))throw new InvalidDataType("Hex.of","not an hexadecimal string",{exp:e});return e.startsWith("-")?new n(this.NEGATIVE,this.REGEX_HEX_PREFIX.test(e)?e.slice(3):e.slice(1)):new n(this.POSITIVE,this.REGEX_HEX_PREFIX.test(e)?e.slice(2):e)}return new n(this.POSITIVE,v.bytesToHex(e))}catch(t){throw new InvalidDataType("Hex.of","not an hexadecimal expression",{exp:`${e}`},t)}}static random(e){if(e>0)return n.of(ut.randomBytes(e));throw new InvalidDataType("Hex.random","bytes argument not > 0",{bytes:e})}toString(e=false){if(e){let t=this.digits.replace(/^0+/,""),i=t===""?"0":t;return (this.sign<0?"-0x":"0x")+i}return (this.sign<0?"-0x":"0x")+this.digits}};var I=class n{types;values;constructor(e=[],t=[]){this.types=typeof e=="string"?parseAbiParameters(e):e,this.values=t;}compareTo(e){return this.types.forEach((t,i)=>{if(t!==e.types[i])return -1}),this.values.forEach((t,i)=>{if(t!==e.values[i])return 1}),0}isEqual(e){return this.compareTo(e)===0}get bi(){throw new InvalidOperation("ABI.bi","There is no big integer representation for an ABI.",{data:""})}get bytes(){return this.toHex().bytes}get n(){throw new InvalidOperation("ABI.n","There is no number representation for an ABI.",{data:""})}static of(e,t){try{return new n(e,t)}catch(i){throw new InvalidAbiDataToEncodeOrDecode("ABI.of","Types and values must be valid ABI parameters.",{types:e,values:t},i)}}static ofEncoded(e,t){try{let i=s.of(t),r;if(typeof e=="string"){let a=parseAbiParameters(e);r=decodeAbiParameters(a,i.bytes);}else r=decodeAbiParameters([...e],i.bytes);return new n(e,[...r])}catch(i){throw new InvalidAbiDataToEncodeOrDecode("ABI.of","Decoding failed: Data must be a valid ABI type with corresponding valid data.",{types:e,data:t},i)}}parseObjectValues(e){let t=[],i=r=>{let a=[];for(let o in r)if(Object.prototype.hasOwnProperty.call(r,o)){let c=r[o];typeof c=="object"&&c!==null?a.push(i(c)):a.push(c);}return a};return t.push(...i(e)),t}getFirstDecodedValue(){return this.values[0]instanceof Object?this.parseObjectValues(this.values[0]):this.values[0]}toHex(){try{let e=encodeAbiParameters(this.types,this.values);return s.of(e)}catch(e){throw new InvalidAbiDataToEncodeOrDecode("ABI.toHex","Encoding failed: Data must be a valid ABI type with corresponding valid data.",{types:this.types,values:this.values},e)}}};var S=class extends I{signature;stringSignature;constructor(e){switch(super(),typeof e){case "string":this.stringSignature=e;break;case "object":this.stringSignature=toFunctionSignature(e);break;default:this.stringSignature="";}this.signature=typeof e=="string"?parseAbiItem([e]):e;}static ofSignature(e,t){return new e(t)}format(e="string"){return e==="json"?JSON.stringify(this.signature):this.stringSignature}get signatureHash(){return toFunctionHash(this.stringSignature)}compareTo(e){return super.compareTo(e)!==0?-1:this.stringSignature.localeCompare(e.stringSignature)}};var x=class n extends S{abiEvent;constructor(e){try{super(e),this.abiEvent=this.signature;}catch(t){throw new InvalidAbiItem("ABIEvent constructor","Initialization failed: Cannot create Event ABI. Event format is invalid.",{type:"event",value:e},t)}}static parseLog(e,t){try{return decodeEventLog({abi:e,data:t.data.toString(),topics:t.topics.map(i=>i===null?i:Array.isArray(i)?i.map(r=>r.toString()):i.toString())})}catch(i){throw new InvalidAbiDataToEncodeOrDecode("ABIEvent.parseLog","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{data:{abi:e,data:t.data,topics:t.topics}},i)}}decodeEventLog(e){try{return n.parseLog([this.abiEvent],e)}catch(t){throw new InvalidAbiDataToEncodeOrDecode("ABIEvent.decodeEventLog","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{data:e},t)}}decodeEventLogAsArray(e){let t=this.decodeEventLog(e);return t.args===void 0?[]:this.parseObjectValues(t.args)}encodeEventLog(e){try{let t=this.encodeFilterTopics(e),i=[],r=[];return this.abiEvent.inputs.forEach((a,o)=>{if(a.indexed??!1)return;let c=e[o];i.push(a),r.push(c);}),{data:I.of(i,r).toHex(),topics:t.map(a=>a===null?a:Array.isArray(a)?a.map(o=>s.of(o)):s.of(a))}}catch(t){throw new InvalidAbiDataToEncodeOrDecode("ABIEvent.encodeEventLog","Encoding failed: Data format is invalid. Event data must be correctly formatted for ABI-compliant encoding.",{dataToEncode:e},t)}}encodeFilterTopics(e){let t=Array.isArray(e)?e.length:Object.values(e??{}).length;if(this.abiEvent.inputs.length<t)throw new InvalidAbiDataToEncodeOrDecode("ABIEvent.encodeEventLog","Encoding failed: Data format is invalid. Number of values to encode is greater than the inputs.",{valuesToEncode:e});try{return encodeEventTopics({abi:[this.abiEvent],args:e})}catch(i){throw new InvalidAbiDataToEncodeOrDecode("ABIEvent.encodeEventLog","Encoding failed: Data format is invalid. Event topics values must be correctly formatted for ABI-compliant encoding.",{valuesToEncode:e},i)}}encodeFilterTopicsNoNull(e){return this.encodeFilterTopics(e).map(i=>i===null?void 0:i)}};var w=class extends S{abiFunction;constructor(e){try{super(e),this.abiFunction=this.signature;}catch(t){throw new InvalidAbiItem("ABIFunction constructor","Initialization failed: Cannot create Function ABI. Function format is invalid.",{type:"function",value:e},t)}}get signatureHash(){return super.signatureHash.substring(0,10)}decodeData(e){try{return decodeFunctionData({abi:[this.abiFunction],data:e.toString()})}catch(t){throw new InvalidAbiDataToEncodeOrDecode("ABIFunction.decodeData","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{data:e},t)}}encodeData(e){try{return s.of(encodeFunctionData({abi:[this.abiFunction],args:e}))}catch(t){throw new InvalidAbiDataToEncodeOrDecode("ABIFunction.encodeData","Encoding failed: Data format is invalid. Function data does not match the expected format for ABI type encoding.",{dataToEncode:e},t)}}decodeResult(e){try{return decodeFunctionResult({abi:[this.abiFunction],data:e.toString()})}catch(t){throw new InvalidAbiDataToEncodeOrDecode("ABIFunction.decodeResult","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{data:e},t)}}decodeOutputAsArray(e){let t=this.decodeResult(e);return this.abiFunction.outputs.length>1?this.parseObjectValues(t):this.abiFunction.outputs.length===1&&this.abiFunction.outputs[0].type==="tuple"?[this.parseObjectValues(t)]:[t]}};var N=class n extends I{constructor(t){super();this.abi=t;this.viemABI=t;}viemABI;static ofAbi(t){return new n(t)}getFunction(t){let i=getAbiItem({abi:this.viemABI,name:t});if(i==null)throw new InvalidAbiItem("ABIContract.getFunction()",`Function '${t}' not found in contract ABI.`,{type:"function",value:t});return new w(i)}getEvent(t){let i=getAbiItem({abi:this.viemABI,name:t});if(i==null)throw new InvalidAbiItem("ABIContract.getEvent()",`Function '${t}' not found in contract ABI.`,{type:"event",value:t});return new x(i)}encodeFunctionInput(t,i){try{let r=getAbiItem({abi:this.viemABI,name:t});return new w(r).encodeData(i)}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.encodeFunctionInput()","Encoding failed: Data format is invalid. Function data does not match the expected format for ABI type encoding.",{functionName:t,functionData:i},r)}}decodeFunctionInput(t,i){try{let r=getAbiItem({abi:this.viemABI,name:t});return new w(r).decodeData(i)}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.decodeFunctionInput()","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{functionName:t,encodedFunctionInput:i},r)}}decodeFunctionOutput(t,i){try{let r=getAbiItem({abi:this.viemABI,name:t});return new w(r).decodeResult(i)}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.decodeFunctionOutput()","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{functionName:t,encodedFunctionOutput:i},r)}}encodeEventLog(t,i){try{let r=getAbiItem({abi:this.viemABI,name:t});return new x(r).encodeEventLog(i)}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.encodeEventLog()","Encoding failed: Data format is invalid. Event data does not match the expected format for ABI type encoding.",{eventName:t,dataToEncode:i},r)}}decodeEventLog(t,i){try{let r=getAbiItem({abi:this.viemABI,name:t});return new x(r).decodeEventLog(i)}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.encodeEventLog()","Encoding failed: Data format is invalid. Event data does not match the expected format for ABI type encoding.",{eventName:t,dataToDecode:i},r)}}parseLog(t,i){try{return x.parseLog(this.abi,{data:t,topics:i})}catch(r){throw new InvalidAbiDataToEncodeOrDecode("ABIContract.parseLog()","Decoding failed: Data must be a valid hex string encoding a compliant ABI type.",{data:t,topics:i},r)}}parseLogAsArray(t,i){let r=this.parseLog(t,i);return r.args===void 0?[]:this.parseObjectValues(r.args)}};var ve=class{address;balance;transactions;type;constructor(e,t,i="EOA",r){this.address=e,this.balance=t,this.type=i,this.transactions=r??[];}get bi(){throw new InvalidOperation("Account.bi","There is no big integer representation for an account.",{data:""})}get bytes(){throw new InvalidOperation("Account.bytes","There is no bytes representation for an account.",{data:""})}get n(){throw new InvalidOperation("Account.n","There is no number representation for an account.",{data:""})}addTransaction(e){this.transactions.push(e);}compareTo(e){let t=this.type.localeCompare(e.type);if(t===0){let i=this.address.compareTo(e.address);if(i===0){let r=this.balance.code.compareTo(e.balance.code);return r===0?this.balance.value.compareTo(e.balance.value):r}return i}return t}isEqual(e){return this.compareTo(e)===0}toString(){return `${this.type} Address: ${this.address.toString()} Balance: ${this.balance.value} ${this.balance.code}`}};var l=class n extends String{static DECODER=new TextDecoder;static NFC="NFC";static ENCODER=new TextEncoder;constructor(e){super(e.normalize(n.NFC));}get bi(){try{return BigInt(this.toString())}catch(e){throw new InvalidOperation("Txt.bi()","Can't cast to big integer",{txt:this.toString()},e)}}get bytes(){return n.ENCODER.encode(this.toString())}get n(){return Number(this.toString())}compareTo(e){return this.toString().localeCompare(e.toString())}isEqual(e){return this.compareTo(e)===0}toString(){return this.valueOf()}static of(e){return typeof e=="string"?new n(e):typeof e=="bigint"||typeof e=="number"?new n(e.toString()):new n(n.DECODER.decode(e))}};var p=class n{static BASE=10n;static DEFAULT_FRACTIONAL_DECIMALS=20n;static NaN=new n(0n,0n,NaN);static NEGATIVE_INFINITY=new n(0n,0n,Number.NEGATIVE_INFINITY);static ONE=n.of(1n);static POSITIVE_INFINITY=new n(0n,0n,Number.POSITIVE_INFINITY);static REGEX_INTEGER=/^[-+]?\d+$/;static REGEX_NUMBER=/(^[-+]?\d+(\.\d+)?)$|(^[-+]?\.\d+)$/;static REGEX_NATURAL=/^\d+$/;static ZERO=new n(0n,0n,0);edgeFlag;fractionalDigits;scaledValue;get bi(){if(this.isFinite())return this.scaledValue/n.BASE**this.fractionalDigits;throw new InvalidOperation("FixedPointNumber.bi","not finite value cannot cast to big integer",{this:this.toString()})}get bytes(){return l.of(this.toString()).bytes}get n(){return this.isNaN()?Number.NaN:this.isNegativeInfinite()?Number.NEGATIVE_INFINITY:this.isPositiveInfinite()?Number.POSITIVE_INFINITY:this.isZero()?0:Number(this.scaledValue)*10**-Number(this.fractionalDigits)}constructor(e,t,i=0){this.fractionalDigits=e,this.edgeFlag=i,this.scaledValue=t;}abs(){return this.isNaN()?n.NaN:this.isNegativeInfinite()?n.POSITIVE_INFINITY:new n(this.fractionalDigits,this.scaledValue<0n?-this.scaledValue:this.scaledValue,this.edgeFlag)}compareTo(e){if(this.isNaN()||e.isNaN())throw new InvalidOperation("FixedPointNumber.compareTo","compare between NaN",{this:`${this}`,that:`${e}`});if(this.isNegativeInfinite())return e.isNegativeInfinite()?0:-1;if(this.isPositiveInfinite())return e.isPositiveInfinite()?0:1;if(e.isNegativeInfinite())return 1;if(e.isPositiveInfinite())return -1;let t=this.maxFractionalDigits(e,this.fractionalDigits),i=this.dp(t).scaledValue-e.dp(t).scaledValue;return i<0n?-1:i===0n?0:1}comparedTo(e){try{return this.compareTo(e)}catch{return null}}div(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isNegativeInfinite())return e.isInfinite()?n.NaN:e.isPositive()?n.NEGATIVE_INFINITY:n.POSITIVE_INFINITY;if(this.isPositiveInfinite())return e.isInfinite()?n.NaN:e.isPositive()?n.POSITIVE_INFINITY:n.NEGATIVE_INFINITY;if(e.isInfinite())return n.ZERO;if(e.isZero())return this.isZero()?n.NaN:this.isNegative()?n.NEGATIVE_INFINITY:n.POSITIVE_INFINITY;let t=this.maxFractionalDigits(e,this.fractionalDigits);return new n(t,n.div(t,this.dp(t).scaledValue,e.dp(t).scaledValue)).dp(this.fractionalDigits)}static div(e,t,i){return n.BASE**e*t/i}dp(e){let t=BigInt(e);if(t>=0){let i=this.fractionalDigits,r=this.scaledValue;if(t>i)r*=n.BASE**(t-i),i=t;else for(;i>t&&r%n.BASE===0n;)i--,r/=n.BASE;return new n(i,r,this.edgeFlag)}throw new InvalidDataType("FixedPointNumber.scale","negative `dp` arg",{dp:`${t}`})}eq(e){return this.comparedTo(e)===0}gt(e){let t=this.comparedTo(e);return t!==null&&t>0}gte(e){let t=this.comparedTo(e);return t!==null&&t>=0}idiv(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isNegativeInfinite())return e.isInfinite()?n.NaN:e.isPositive()?n.NEGATIVE_INFINITY:n.POSITIVE_INFINITY;if(this.isPositiveInfinite())return e.isInfinite()?n.NaN:e.isPositive()?n.POSITIVE_INFINITY:n.NEGATIVE_INFINITY;if(e.isInfinite())return n.ZERO;if(e.isZero())return this.isZero()?n.NaN:this.isNegative()?n.NEGATIVE_INFINITY:n.POSITIVE_INFINITY;let t=this.maxFractionalDigits(e,this.fractionalDigits);return new n(t,n.idiv(t,this.dp(t).scaledValue,e.dp(t).scaledValue)).dp(this.fractionalDigits)}static idiv(e,t,i){return t/i*n.BASE**e}isEqual(e){return this.eq(e)}isFinite(){return this.edgeFlag===0}isInfinite(){return this.isNegativeInfinite()||this.isPositiveInfinite()}isInteger(){return this.isFinite()?this.scaledValue%n.BASE**this.fractionalDigits===0n:false}static isIntegerExpression(e){return this.REGEX_INTEGER.test(e)}isNaN(){return Number.isNaN(this.edgeFlag)}static isNaturalExpression(e){return this.REGEX_NATURAL.test(e)}isNegative(){return this.isFinite()&&this.scaledValue<0n||this.isNegativeInfinite()}isNegativeInfinite(){return this.edgeFlag===Number.NEGATIVE_INFINITY}static isNumberExpression(e){return n.REGEX_NUMBER.test(e)}isPositive(){return this.isFinite()&&this.scaledValue>=0n||this.isPositiveInfinite()}isPositiveInfinite(){return this.edgeFlag===Number.POSITIVE_INFINITY}isZero(){return this.isFinite()&&this.scaledValue===0n}lt(e){let t=this.comparedTo(e);return t!==null&&t<0}lte(e){let t=this.comparedTo(e);return t!==null&&t<=0}maxFractionalDigits(e,t){let i=this.fractionalDigits<e.fractionalDigits?e.fractionalDigits:this.fractionalDigits;return i>t?i:t}minus(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isNegativeInfinite())return e.isNegativeInfinite()?n.NaN:n.NEGATIVE_INFINITY;if(this.isPositiveInfinite())return e.isPositiveInfinite()?n.NaN:n.POSITIVE_INFINITY;let t=this.maxFractionalDigits(e,this.fractionalDigits);return new n(t,this.dp(t).scaledValue-e.dp(t).scaledValue).dp(this.fractionalDigits)}modulo(e){if(this.isNaN()||e.isNaN()||this.isInfinite()||e.isInfinite()||e.isZero())return n.NaN;let t=this.maxFractionalDigits(e,this.fractionalDigits),i=this.abs().dp(t).scaledValue,r=e.abs().dp(t).scaledValue;for(;i>=r;)i-=r;return new n(t,i).dp(this.fractionalDigits)}static mul(e,t,i){return e*t/n.BASE**i}negated(){return this.isNegativeInfinite()?n.POSITIVE_INFINITY:this.isPositiveInfinite()?n.NEGATIVE_INFINITY:new n(this.fractionalDigits,-this.scaledValue,this.edgeFlag)}static of(e,t=this.DEFAULT_FRACTIONAL_DECIMALS){try{return e instanceof n?new n(e.fractionalDigits,e.scaledValue,e.edgeFlag):Number.isNaN(e)?new n(t,0n,Number.NaN):e===Number.NEGATIVE_INFINITY?new n(t,-1n,Number.NEGATIVE_INFINITY):e===Number.POSITIVE_INFINITY?new n(t,1n,Number.POSITIVE_INFINITY):new n(t,this.txtToSV(e.toString(),t))}catch(i){throw new InvalidDataType("FixedPointNumber.of","not a number",{exp:e},i)}}plus(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isNegativeInfinite())return e.isPositiveInfinite()?n.NaN:n.NEGATIVE_INFINITY;if(this.isPositiveInfinite())return e.isNegativeInfinite()?n.NaN:n.POSITIVE_INFINITY;let t=this.maxFractionalDigits(e,this.fractionalDigits);return new n(t,this.dp(t).scaledValue+e.dp(t).scaledValue).dp(this.fractionalDigits)}pow(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isInfinite())return e.isZero()?n.ONE:e.isNegative()?n.ZERO:n.POSITIVE_INFINITY;if(e.isNegativeInfinite())return n.ZERO;if(e.isPositiveInfinite())return n.POSITIVE_INFINITY;if(e.isZero())return n.ONE;let t=e.abs().bi,i=n.of(this),r=n.ONE;for(;t>0n;)t%2n===1n&&(r=r.times(i)),i=i.times(i),t=t/2n;return e.isNegative()?n.ONE.div(r):r}static sqr(e,t){if(e<0n)throw new RangeError("Value must be positive");let i=t*n.BASE,r=0,a=e,o=0n;for(;a!==o&&r<i;)o=a,a=(a+n.div(t,e,a))/2n,r++;return a}sqrt(){if(this.isNaN()||this.isNegativeInfinite())return n.NaN;if(this.isPositiveInfinite())return n.POSITIVE_INFINITY;try{return new n(this.fractionalDigits,n.sqr(this.scaledValue,this.fractionalDigits))}catch{return n.NaN}}times(e){if(this.isNaN()||e.isNaN())return n.NaN;if(this.isNegativeInfinite())return e.isNegative()?n.POSITIVE_INFINITY:n.NEGATIVE_INFINITY;if(this.isPositiveInfinite())return e.isNegative()?n.NEGATIVE_INFINITY:n.POSITIVE_INFINITY;let t=this.fractionalDigits>e.fractionalDigits?this.fractionalDigits:e.fractionalDigits;return new n(t,n.mul(this.dp(t).scaledValue,e.dp(t).scaledValue,t)).dp(this.fractionalDigits)}toString(e="."){if(this.edgeFlag===0){let t=this.scaledValue<0n?"-":"",r=(this.scaledValue<0n?(-this.scaledValue).toString():this.scaledValue.toString()).padStart(Number(this.fractionalDigits),"0"),a=this.fractionalDigits>0?r.slice(Number(-this.fractionalDigits)):"",o=r.slice(0,r.length-a.length),c=o.length<1?"0":o,m=n.trimEnd(a);return t+c+(m.length>0?e+m:"")}return this.edgeFlag.toString()}static trimEnd(e,t="0"){return e.endsWith(t)?n.trimEnd(e.substring(0,e.length-t.length),t):e}static txtToSV(e,t,i="."){let r=e.charAt(0),a=1n;r==="-"?(a=-1n,e=e.substring(1)):r==="+"&&(e=e.substring(1));let o=n.BASE**t,c=e.lastIndexOf(i);if(c<0)return a*o*BigInt(e);let m=e.substring(0,c),E=e.substring(c+1);return a*o*BigInt(m)+a*(o*BigInt(E))/BigInt(10**E.length)}};var D=class n extends s{get n(){let e=this.bi;if(Number.MIN_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER)return Number(e);throw new InvalidDataType("HexInt.n","not in the safe number range",{bi:`${e}`,hex:this.toString()})}static of(e){try{if(e instanceof s)return new n(e.sign,e.digits);if(typeof e=="number"){if(Number.isInteger(e)){let i=s.of(BigInt(e));return new n(i.sign,i.digits)}throw new InvalidDataType("HexInt.of","not an integer",{exp:e})}let t=s.of(e);return new n(t.sign,t.digits)}catch(t){throw new InvalidDataType("HexInt.of","not an hexadecimal integer expression",{exp:`${e}`,e:t})}}};var u=class n extends D{static REGEX_HEXUINT=/^(0x)?[0-9a-f]*$/i;static REGEX_HEXUINT_PREFIX=/^0x/i;static isValid(e){return n.REGEX_HEXUINT.test(e)}static isValid0x(e){return n.REGEX_HEX_PREFIX.test(e)&&s.isValid(e)}static of(e){try{let t=D.of(e);if(t.sign>=s.POSITIVE)return new n(t.sign,t.digits);throw new InvalidDataType("HexUInt.of","not positive",{exp:`${e}`})}catch(t){throw new InvalidDataType("HexUInt.of","not a hexadecimal positive integer expression",{exp:`${e}`,e:t},t)}}};var B=class n extends u{static of(e){try{let t=gt.sha256(u.of(e).bytes);return new n(s.POSITIVE,u.of(t).digits)}catch(t){throw new InvalidOperation("Sha256.of","hash error",{exp:`${e}`,e:t})}}};var d=class n{static COMPRESSED_PREFIX=2;static SIGNATURE_LENGTH=65;static UNCOMPRESS_PREFIX=4;static VALID_HASH_LENGTH=32;static compressPublicKey(e){if(e.at(0)===n.UNCOMPRESS_PREFIX){let i=e.slice(1,33),r=e.slice(33,65),a=r[r.length-1]&1;return v.concatBytes(Uint8Array.of(n.COMPRESSED_PREFIX+a),i)}else return e}static derivePublicKey(e,t=true){if(n.isValidPrivateKey(e))return secp256k1.getPublicKey(e,t);throw new InvalidSecp256k1PrivateKey("Secp256k1.derivePublicKey","Invalid private key given as input. Ensure it is a valid 32-byte secp256k1 private key.",void 0)}static async generatePrivateKey(){return await new Promise((e,t)=>{try{let i=secp256k1.utils.randomPrivateKey();e(i);}catch(i){t(new InvalidSecp256k1PrivateKey("Secp256k1.generatePrivateKey","Private key generation failed: ensure you have a secure random number generator available at runtime.",void 0,i));}})}static inflatePublicKey(e){if(e.at(0)!==n.UNCOMPRESS_PREFIX){let i=e.slice(0,33);return secp256k1.ProjectivePoint.fromAffine(secp256k1.ProjectivePoint.fromHex(u.of(i).digits).toAffine()).toRawBytes(false)}else return e}static isValidMessageHash(e){return e.length===n.VALID_HASH_LENGTH}static isValidPrivateKey(e){return secp256k1.utils.isValidPrivateKey(e)}static randomBytes(e=32){try{return randomBytes(e)}catch{return global.crypto.getRandomValues(new Uint8Array(e))}}static recover(e,t){if(!n.isValidMessageHash(e))throw new InvalidSecp256k1MessageHash("Secp256k1.recover","Invalid message hash given as input. Ensure it is a valid 32-byte message hash.",{messageHash:e});if(t.length!==n.SIGNATURE_LENGTH)throw new InvalidSecp256k1Signature("Secp256k1.recover","Invalid signature given as input. Length must be exactly 65 bytes.",{signature:t});let i=t[64];if(i!==0&&i!==1)throw new InvalidSecp256k1Signature("Secp256k1.recover","Invalid signature recovery value. Signature bytes at position 64 must be 0 or 1.",{signature:t,recovery:i});return secp256k1.Signature.fromCompact(t.slice(0,64)).addRecoveryBit(i).recoverPublicKey(e).toRawBytes(false)}static sign(e,t){if(!n.isValidMessageHash(e))throw new InvalidSecp256k1MessageHash("Secp256k1.sign","Invalid message hash given as input. Ensure it is a valid 32-byte message hash.",{messageHash:e});if(!n.isValidPrivateKey(t))throw new InvalidSecp256k1PrivateKey("Secp256k1.sign","Invalid private key given as input. Ensure it is a valid 32-byte secp256k1 private key.",void 0);let i=secp256k1.sign(e,t);return v.concatBytes(v.numberToBytesBE(i.r,32),v.numberToBytesBE(i.s,32),v.numberToVarBytesBE(i.recovery))}};var K=class extends te.HDKey{static EXTENDED_PRIVATE_KEY_PREFIX=u.of("0488ade4000000000000000000").bytes;static EXTENDED_PUBLIC_KEY_PREFIX=u.of("0488b21e000000000000000000").bytes;static VET_DERIVATION_PATH="m/44'/818'/0'/0";static fromMnemonic(e,t=this.VET_DERIVATION_PATH){let i;try{i=te.HDKey.fromMasterSeed(U.mnemonicToSeedSync(e.join(" ").toLowerCase()));}catch(r){throw new InvalidHDKeyMnemonic("HDNode.fromMnemonic","Invalid mnemonic words given as input.",void 0,r)}try{return i.derive(t)}catch(r){throw new InvalidHDKey("HDNode.fromMnemonic","Invalid derivation path given as input.",{derivationPath:t},r)}}static fromPrivateKey(e,t){if(e.length===32){let i=v.concatBytes(this.EXTENDED_PRIVATE_KEY_PREFIX,t,Uint8Array.of(0),e);e.fill(0);let r=B.of(B.of(i).bytes).bytes.subarray(0,4),a=v.concatBytes(i,r);try{return te.HDKey.fromExtendedKey(base58.encode(a))}catch{throw new InvalidSecp256k1PrivateKey("HDNode.fromPrivateKey","Invalid private key path given as input.",void 0)}}throw e.fill(0),new InvalidSecp256k1PrivateKey("HDNode.fromPrivateKey()","Invalid private key path given as input. Length must be exactly 32 bytes.",void 0)}static fromPublicKey(e,t){if(t.length===32){let i=v.concatBytes(this.EXTENDED_PUBLIC_KEY_PREFIX,t,d.compressPublicKey(e)),r=B.of(B.of(i).bytes).bytes.subarray(0,4),a=v.concatBytes(i,r);try{return te.HDKey.fromExtendedKey(base58.encode(a))}catch(o){throw new InvalidHDKey("HDNode.fromPublicKey()","Invalid public key path given as input.",{publicKey:e},o)}}throw new InvalidHDKey("HDNode.fromPublicKey()","Invalid chain code given as input. Length must be exactly 32 bytes.",{chainCode:t})}static isDerivationPathComponentValid(e,t){return (t===0?e==="m":false)||p.isNaturalExpression(e)||p.isNaturalExpression(e.slice(0,-1))&&e.endsWith("'")}static isDerivationPathValid(e){return /^m(\/\d+'?){3}(\/\d+){1,2}$/.test(e)}};var P=class n extends u{static of(e){try{let t=keccak_256(u.of(e).bytes);return new n(s.POSITIVE,u.of(t).digits)}catch(t){throw new InvalidOperation("Keccak256.of","hash error",{exp:`${e}`,e:t})}}};var f=class n extends u{static DIGITS=40;static checksum(e){let t=e.digits,i=P.of(l.of(t).bytes).digits,r="";for(let a=0;a<t.length;a++)r+=parseInt(i[a],16)>7?t[a].toUpperCase():t[a];return "0x"+r}static isValid(e){return s.isValid0x(e)&&e.length===n.DIGITS+2}static of(e){try{let t=u.of(e),i=u.of(t.digits.padStart(40,"0")),r=n.checksum(i);return new n(s.POSITIVE,"0x0",()=>r.substring(2))}catch(t){throw new InvalidDataType("Address.of","not a valid hexadecimal positive integer expression",{exp:`${e}`},t)}}static ofPrivateKey(e){try{return n.ofPublicKey(d.derivePublicKey(e,!0))}catch(t){throw new InvalidDataType("Address.ofPrivateKey","not a valid private key",{privateKey:"private key is obfuscated"},t)}}static ofPublicKey(e){try{let t=d.inflatePublicKey(e),i=P.of(t.slice(1)).bytes;return n.of(i.slice(12))}catch(t){throw new InvalidDataType("Address.ofPublicKey","not a valid public key",{publicKey:`${e}`},t)}}static ofMnemonic(e,t="m/0"){let i=K.fromMnemonic(e);try{return n.ofPublicKey(i.derive(t).publicKey)}catch(r){throw new InvalidHDKey("mnemonic.deriveAddress()","Invalid derivation path given as input.",{derivationPath:t},r)}}};var Re=class n extends u{static DIGITS=16;constructor(e){super(s.POSITIVE,e.fit(n.DIGITS).digits);}static isValid(e){return s.isValid(e)&&u.REGEX_HEXUINT_PREFIX.test(e)?e.length===n.DIGITS+2:e.length===n.DIGITS}static isValid0x(e){return u.REGEX_HEXUINT_PREFIX.test(e)&&n.isValid(e)}static of(e){try{return e instanceof u?new n(e):new n(u.of(e))}catch(t){throw new InvalidDataType("BlockRef.of","not a BlockRef expression",{exp:`${e}`},t)}}};var A=class n extends u{static of(e){try{let t=blake2b.create({dkLen:32}).update(u.of(e).bytes).digest();return new n(s.POSITIVE,u.of(t).digits)}catch(t){throw new InvalidOperation("Blake2b256.of","hash error",{exp:`${e}`,e:t})}}};var ie=class n{bytes;k;constructor(e,t){this.bytes=e,this.k=t;}get bi(){return v.bytesToNumberBE(this.bytes)}get n(){let e=this.bi;if(Number.MIN_SAFE_INTEGER<=e&&e<=Number.MAX_SAFE_INTEGER)return Number(e);throw new InvalidDataType("BloomFilter.n","not in the safe number range",{bytes:this.bytes,k:this.k})}compareTo(e){return this.bi<e.bi?-1:this.bi>e.bi?1:this.k-e.k}isEqual(e){return this.bi===e.bi&&this.k===e.k}contains(e){return Nt(xt(e instanceof s?e.bytes:e),this.k,this.bytes.byteLength*8,(t,i)=>(this.bytes[t]&i)===i)}static computeBestBitsPerKey(e){return e<=1?2:e>=30?44:Math.ceil(e/.69)}static computeBestHashFunctionsQuantity(e){let t=Math.floor(e*.69);return t<1?1:t>30?30:t}isJoinable(e){return this.k===e.k&&this.bytes.length===e.bytes.length}join(e){if(this.k!==e.k)throw new InvalidOperation("BloomFilter.join","different k values",{this:this,other:e});if(this.bytes.length!==e.bytes.length)throw new InvalidOperation("BloomFilter.join","different length values",{this:this,other:e});let t=new Uint8Array(this.bytes.length);for(let i=0;i<this.bytes.length;i++)t[i]=this.bytes[i]|e.bytes[i];return new n(t,this.k)}static of(...e){let t=new Fe;return t.add(...e),t}},Fe=class n{static DEFAULT_K=5;hashMap=new Map;add(...e){for(let t of e)this.hashMap.set(xt(t instanceof s?t.bytes:t),true);return this}build(e=n.DEFAULT_K,t=ie.computeBestBitsPerKey(e)){let i=Math.floor((this.hashMap.size*t+7)/8);i=i<8?8:i;let r=new Uint8Array(i),a=i*8;for(let o of this.hashMap.keys())Nt(o,e,a,(c,m)=>(r[c]|=m,true));return new ie(r,e)}},yn=2**32;function bn(n,e){return (n+e)%yn}function Nt(n,e,t,i){let r=(n>>>17|n<<15)>>>0;for(let a=0;a<e;a++){let o=n%t;if(!i(Math.floor(o/8),1<<o%8))return false;n=bn(n,r);}return true}function xt(n){return Number(v.bytesToNumberBE(A.of(n).bytes.slice(0,4)))}var G=class{_code;_value;constructor(e,t){this._code=e,this._value=t;}get code(){return this._code}get value(){return this._value}get bi(){return this._value.bi}get bytes(){return l.of(this.toString()).bytes}get n(){return this._value.n}compareTo(e){if(this.code.isEqual(e.code))return this.value.compareTo(e.value);throw new InvalidDataType("Coin.compareTo","not VET currency",{that:`${e}`})}isEqual(e){try{return this.compareTo(e)===0}catch{return false}}toString(){return `${this.value.toString()} ${this._code}`}};var g=(c=>(c[c.wei=0]="wei",c[c.kwei=3]="kwei",c[c.mwei=6]="mwei",c[c.gwei=9]="gwei",c[c.szabo=12]="szabo",c[c.finney=15]="finney",c[c.ether=18]="ether",c))(g||{});(o=>{function n(c){return e(c,18)}o.formatEther=n;function e(c,m=18){let E=c.div(p.of(10n**BigInt(m)));return E.isInteger()?`${E}.0`:`${E}`}o.formatUnits=e;function t(c){return i(c,18)}o.parseEther=t;function i(c,m=18){return p.of(c).times(p.of(10n**BigInt(m)))}o.parseUnits=i;function r(c,m,E){let b=BigInt(E-m);return b>=0n?c.div(p.of(10n**b)):c.times(p.of(10n**BigInt(-b)))}o.convertUnits=r;function a(c,m,E,b){let Te=r(c,m,E);if(b!==void 0)if(b>=0)Te=p.of(Te).dp(b);else throw new InvalidDataType("Units.formatFromUnits","displayDecimals must be greater than or equal to 0",{value:c,fromUnits:m,toUnits:E,displayDecimals:b});let ct=Te.toString();if(b!==void 0){let j=ct.split(".");return j.length>1?b>0?j[0]+"."+j[1].slice(0,b):j[0]:b>0?j[0]+"."+"0".repeat(b):j[0]}return ct}o.formatFromUnits=a;})(g||={});var re=class n extends G{static CODE=l.of("\u{1D54D}\u039ET");static WEI_FD=18n;wei=this.value.dp(n.WEI_FD).scaledValue;constructor(e){super(n.CODE,e);}static of(e,t=18){let i=e instanceof p?e:p.of(e);return new n(i.div(p.of(10n**(n.WEI_FD-BigInt(t)))))}};var Z=class n extends G{static CODE=l.of("\u{1D54D}THO");static WEI_FD=18n;wei=this.value.dp(n.WEI_FD).scaledValue;constructor(e){super(n.CODE,e);}static of(e,t=18){let i=e instanceof p?e:p.of(e);return new n(i.div(p.of(10n**(n.WEI_FD-BigInt(t)))))}};var De=class{_valueWei;constructor(){this._valueWei=0n;}initialize(e,t=this.units){let i=g.convertUnits(p.of(e),t,0);if(i.isNegative())throw new InvalidDataType("Token.initialize","Value is negative",{value:e,valueUnits:t});this._valueWei=i.bi;}convertWeiToTokenUnits(){return g.convertUnits(p.of(this._valueWei),0,this.units).bi}get value(){return this.convertWeiToTokenUnits()}format(e=this.units,t){return g.formatFromUnits(p.of(this._valueWei),0,e,t)}};var h=class{};var _=class n{encoded;decoded;constructor(e){this.decoded=ArrayBuffer.isView(e)?RLP.decode(e):e,this.encoded=ArrayBuffer.isView(e)?e:RLP.encode(e);}get bi(){return bytesToNumberBE(this.bytes)}get bytes(){return this.encoded}get n(){let e=this.bi;if(e<=Number.MAX_SAFE_INTEGER)return Number(e);throw new InvalidDataType("RLP.n","not in the safe number range",{bytes:this.bytes})}compareTo(e){if(this.encoded.length!==e.encoded.length)return -1;for(let t=0;t<this.encoded.length;t++)if(this.encoded[t]!==e.encoded[t])return 1;return 0}isEqual(e){return this.compareTo(e)===0}toHex(){return s.of(this.bytes)}static of(e){try{return new n(e)}catch(t){throw new InvalidRLP("RLP.of()",`Error when creating an RLP instance for data ${e}`,{context:"This method creates an RLP instance from a plain value.",data:{data:e}},t)}}static ofEncoded(e){try{return new n(e)}catch(t){throw new InvalidRLP("RLP.ofEncoded()","Error when creating an RLP instance for encoded data.",{context:"This method creates an RLP instance from an encoded value.",data:{encodedData:e}},t)}}static packData(e,t,i){i=i!==""?i+"."+t.name:t.name;let r=t.kind;if(r instanceof h)return r.data(e,i).encode();if(Array.isArray(r))return r.map(a=>this.packData(e[a.name],a,i));if(!Array.isArray(e))throw new InvalidRLP("RLP.packData()",`Validation error: Expected an array in ${i}.`,{context:i,data:{obj:e,profile:t}});if("item"in r&&Array.isArray(e)){let a=r.item;return e.map((o,c)=>this.packData(o,{name:"#"+c,kind:a},i))}}static unpackData(e,t,i){i=i!==""?i+"."+t.name:t.name;let r=t.kind;if(r instanceof h){if(!ArrayBuffer.isView(e))throw new InvalidRLP("RLP.unpackData()","Unpacking error: Expected data type is Uint8Array.",{context:i,data:{packed:e,profile:t}});return r.buffer(e,i).decode()}if(Array.isArray(r)&&Array.isArray(e)){let a=e;if(r.length!==a.length)throw new InvalidRLP("RLP.unpackData()",`Unpacking error: Expected ${r.length} items, but got ${a.length}.`,{context:i,data:{packed:e,profile:t}});return r.reduce((o,c,m)=>(o[c.name]=this.unpackData(a[m],c,i),o),{})}if(!Array.isArray(e))throw new InvalidRLP("RLP.unpackData()",`Validation error: Expected an array in ${i}.`,{context:i,data:{packed:e,profile:t}});if("item"in r&&Array.isArray(e)){let a=r.item;return e.map((o,c)=>this.unpackData(o,{name:"#"+c,kind:a},i))}}};var L=class n extends _{constructor(t,i){super(t);this.profile=i;}static ofObject(t,i){let r=this.packData(t,i,"");return new n(r,i)}static ofObjectEncoded(t,i){let r=_.ofEncoded(t).decoded;return new n(r,i)}get object(){return n.unpackData(this.decoded,this.profile,"")}};var Be=(n,e)=>{if(typeof n!="number"&&typeof n!="string")throw new InvalidRLP("validateNumericKindData()",`Validation error: Input in ${e} must be a string or number.`,{context:e,data:{data:n}});return typeof n=="number"?En(n,e):typeof n=="string"&&vn(n,e),BigInt(n)},En=(n,e)=>{if(!Number.isSafeInteger(n)||n<0)throw new InvalidRLP("_validateNumericKindNumber()",`Validation error: Number in ${e} must be a safe and non-negative integer.`,{context:e,data:{num:n}})},vn=(n,e)=>{let t=u.isValid0x(n),i=p.isNaturalExpression(n);if(!t&&!i)throw new InvalidRLP("_validateNumericKindString()",`Validation error: String in ${e} must represent a non-negative integer in hex or decimal format.`,{context:e,data:{str:n}});if(t&&n.length<=2)throw new InvalidRLP("_validateNumericKindString()",`Validation error: Hex string number in ${e} must be of valid length.`,{context:e,data:{str:n}})},Ve=(n,e,t)=>{if(t!==void 0&&n.length>t)throw new InvalidRLP("assertValidNumericKindBuffer()",`Validation error: Buffer in ${e} must be less than ${t} bytes.`,{context:e,data:{buf:n,maxBytes:t}});if(n[0]===0)throw new InvalidRLP("assertValidNumericKindBuffer()",`Validation error: Buffer in ${e} must represent a canonical integer (no leading zeros).`,{context:e,data:{buf:n,maxBytes:t}})},Le=(n,e,t)=>{if(n===0n)return Uint8Array.from([]);let i=s.of(n).digits;if(e!==void 0&&i.length>e*2)throw new InvalidRLP("encodeBigIntToBuffer()",`Validation error: Encoded number in ${t} must fit within ${e} bytes.`,{context:t,data:{hex:i,maxBytes:e}});return s.of(i).bytes},Oe=n=>{if(n.length===0)return 0;let e=s.of(n).bi,t=Number(e);return Number.isSafeInteger(t)?t:"0x"+e.toString(16)};var Ue=(n,e)=>{if(typeof n!="string")throw new InvalidRLP("assertValidHexBlobKindData()","Validation error: Input must be a string.",{context:e,data:{data:n}});if(!s.isValid(n))throw new InvalidRLP("assertValidHexBlobKindData()","Validation error: Input must be a valid hex string with a '0x' prefix.",{context:e,data:{data:n}});if(n.length%2!==0)throw new InvalidRLP("assertValidHexBlobKindData()","Validation error: Hex string must have an even length.",{context:e,data:{data:n}})};var ke=(n,e,t)=>{if(n.length!==t*2+2)throw new InvalidRLP("assertFixedHexBlobKindData()",`Validation error: Hex string in ${e} must be exactly ${t} bytes in length.`,{context:e,data:{data:n,bytes:t}})},He=(n,e,t)=>{if(n.length!==t)throw new InvalidRLP("assertFixedHexBlobKindData()",`Validation error: Hex string in ${e} must be exactly ${t} bytes in length.`,{context:e,data:{buffer:n,bytes:t}})};var Ke=(n,e,t)=>{if(n.length>t)throw new InvalidRLP("assertCompactFixedHexBlobBuffer()",`Validation error: Buffer in ${e} must be at most ${t} bytes.`,{context:e,data:{buffer:n,bytes:t}});if(n.length!==0&&n[0]===0)throw new InvalidRLP("assertCompactFixedHexBlobBuffer()",`Validation error: Buffer in ${e} should not have leading zero bytes.`,{context:e,data:{buffer:n,bytes:t}})},Ge=n=>{let e=n.findIndex(t=>t!==0);return e!==-1?n.subarray(e):Uint8Array.from([])},Nn=(n,e)=>s.of(n).fit(e*2).toString();var O=class extends h{data(e,t){if(!ArrayBuffer.isView(e))throw new InvalidRLP("BufferKind.data()",`Validation error: Expected a Uint8Array type in ${t}.`,{context:t,data:{data:e}});return {encode:()=>e}}buffer(e){return {decode:()=>e}}};var y=class extends h{constructor(t){super();this.maxBytes=t;}data(t,i){let r=Be(t,i);return {encode:()=>Le(r,this.maxBytes,i)}}buffer(t,i){return Ve(t,i,this.maxBytes),{decode:()=>Oe(t)}}};var R=class extends h{data(e,t){return Ue(e,t),{encode:()=>u.of(e.slice(2)).bytes}}buffer(e,t){return {decode:()=>s.of(e).toString()}}};var C=class extends R{constructor(t){super();this.bytes=t;}data(t,i){let r=super.data(t,i);return ke(t,i,this.bytes),r}buffer(t,i){let r=super.buffer(t,i);return He(t,i,this.bytes),r}};var F=class extends C{data(e,t){return e==null?{encode:()=>Uint8Array.from([])}:super.data(e,t)}buffer(e,t){return e.length===0?{decode:()=>null}:super.buffer(e,t)}};var X=class extends C{data(e,t){let i=super.data(e,t).encode();return {encode:()=>Ge(i)}}buffer(e,t){return Ke(e,t,this.bytes),{decode:()=>s.of(e).fit(this.bytes*2).toString()}}};var Me=class n{static ENCODER=new TextEncoder;get bi(){throw new InvalidOperation("Mnemonic.bi","There is no big integer representation for a mnemonic.",{data:""})}get bytes(){return n.ENCODER.encode(n.of().join(" "))}get n(){throw new InvalidOperation("Mnemonic.n","There is no number representation for a mnemonic.",{data:""})}compareTo(e){throw new InvalidOperation("Mnemonic.compareTo","There is no comparison for a mnemonic since it is not stored in memory.",{data:""})}isEqual(e){throw new InvalidOperation("Mnemonic.isEqual","There is no comparison for a mnemonic since it is not stored in memory.",{data:""})}static wordsNoToStrength(e){switch(e){case 12:return 128;case 15:return 160;case 18:return 192;case 21:return 224;case 24:return 256;default:throw new InvalidDataType("Mnemonic.wordsNoToStrength","not a valid number of words",{numberOfWords:e})}}static toPrivateKey(e,t=K.VET_DERIVATION_PATH+"/0"){let i=te.HDKey.fromMasterSeed(U.mnemonicToSeedSync(e.join(" ").toLowerCase()));try{return i.derive(t).privateKey}catch(r){throw new InvalidHDKey("mnemonic.derivePrivateKey()","Invalid derivation path given as input.",{derivationPath:t},r)}}static of(e=12,t){try{let i=n.wordsNoToStrength(e);if(t!=null){let r=i/8;return U.entropyToMnemonic(t(r),wordlist).split(" ")}return U.generateMnemonic(wordlist,i).split(" ")}catch(i){throw new InvalidHDKeyMnemonic("Mnemonic.of","error while generating mnemonic",{wordlistSize:e},i)}}static isValid(e){let t=Array.isArray(e)?e.join(" "):e;return U.validateMnemonic(t,wordlist)}};var Xe=class n extends u{static of(e){try{let t=u.of(e),i=0;for(;i<t.digits.length&&t.digits.at(i)==="0";)i++;return new n(t.sign,i===t.digits.length?"0":t.digits.slice(i))}catch(t){throw new InvalidDataType("Quantity.of","not a Quantity expression",{exp:`${e}`},t)}}};var $e=class n extends l{static VALID_REVISION_REGEX=/^(best|finalized|next|justified|0x[a-fA-F0-9]+|\d+)$/;static isValid(e){return typeof e=="number"?Number.isInteger(e)&&e>=0:typeof e=="bigint"?e>=BigInt(0):e instanceof s?n.isValid(e.bi):n.VALID_REVISION_REGEX.test(e)}static of(e){try{if(ArrayBuffer.isView(e)){let t=l.of(e).toString();if(n.isValid(t))return new n(t);throw new InvalidDataType("Revision.of","not a revision",{value:`${e}`})}if(n.isValid(e))return new n(`${e}`);throw new InvalidDataType("Revision.of","not a revision",{value:`${e}`})}catch(t){throw new InvalidDataType("Revision.of","not a revision",{value:`${e}`,e:t})}}static BEST=n.of("best");static FINALIZED=n.of("finalized");static NEXT=n.of("next");static JUSTIFIED=n.of("justified")};var ae=class n extends u{static DIGITS=64;constructor(e){super(s.POSITIVE,e.fit(n.DIGITS).digits);}static isValid(e){return s.isValid(e)&&u.REGEX_HEXUINT_PREFIX.test(e)?e.length===n.DIGITS+2:e.length===n.DIGITS}static isValid0x(e){return u.REGEX_HEXUINT_PREFIX.test(e)&&n.isValid(e)}static of(e){try{return e instanceof u?new n(e):new n(u.of(e))}catch(t){throw new InvalidDataType("BlockId.of","not a BlockId expression",{exp:`${e}`},t)}}},je=class n extends ae{constructor(e){super(e);}static of(e){return new n(ae.of(e))}};var We=class n{purpose;payload;domain;timestamp;signer;signature;constructor(e,t,i,r,a,o){if(Number.isSafeInteger(r)&&r>=0)if(f.isValid(a)){this.purpose=e,this.payload=t,this.domain=i,this.timestamp=r,this.signer=a.toString().toLowerCase();try{this.signature=typeof o=="string"?u.of(o).alignToBytes().toString():o;}catch(c){throw new InvalidDataType("Certificate.constructor","invalid signature",{signature:o},c)}}else throw new InvalidDataType("Certificate.constructor","signer is not an address",{signer:a});else throw new InvalidDataType("Certificate.constructor","not positive safe integer timestamp",{timestamp:r})}static encode(e){return l.of(Dn(e)).bytes}encode(){return n.encode({...this,signature:void 0})}isSigned(){return typeof this.signature=="string"&&u.isValid(this.signature)}static of(e){try{return new n(e.purpose,e.payload,e.domain,e.timestamp,e.signer,e.signature)}catch(t){throw new InvalidDataType("Certificate.of","invalid certificate data",{certifiable:e},t)}}sign(e){return this.signature=void 0,this.signature=u.of(d.sign(A.of(n.encode(this)).bytes,e)).toString(),this}verify(){if(!this.isSigned())throw new CertificateSignatureMismatch("Certificate.verify","signature missing",{certificate:this});if(f.ofPublicKey(d.recover(A.of(n.encode({...this,signature:void 0})).bytes,u.of(this.signature).bytes)).toString().toLowerCase()!==this.signer)throw new CertificateSignatureMismatch("Certificate.verify","signature doesn't match with signer's public key",{certificate:this})}};var fe={N:131072,r:8,p:1};async function Ln(n,e){let t=d.derivePublicKey(n),r={address:f.ofPublicKey(t).toString(),privateKey:u.of(n).toString()},a={scrypt:{N:fe.N,r:fe.r,p:fe.p}},o=await ethers.encryptKeystoreJson(r,e,a);return JSON.parse(o)}async function On(n,e){if(!Bt(n))throw new InvalidKeystore("keystore.decrypt()","Invalid keystore. Ensure the keystore is properly formatted and contains the necessary data.",{keystore:n});try{return await ethers.decryptKeystoreJson(stringifyData(n),e)}catch{throw new InvalidKeystoreParams("keystore.decrypt()","Decryption failed: Invalid Password for the given keystore.",{keystore:n})}}function Bt(n){return ethers.isKeystoreJson(stringifyData(n))}var se={encrypt:Ln,decrypt:On,isValid:Bt};var ze="aes-128-ctr",q=32,ye="scrypt",qe=3,J={N:131072,r:8,p:1};function Un(n){let e=v.hexToBytes(n.crypto.kdfparams.salt),t=n.crypto.kdfparams.n,i=n.crypto.kdfparams.r,r=n.crypto.kdfparams.p;if(t<=0||(t&t-1)!==0)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.decodeScryptParams()","Decryption failed: invalid keystore.crypto.kdfparams.n parameter.",{keystore:n,N:t});if(i<=0||r<=0)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.decodeScryptParams()","Decryption failed: both keystore.crypto.kdfparams.r or keystore.crypto.kdfparams.p parameter must be > 0.",{keystore:n,r:i,p:r});let a=n.crypto.kdfparams.dklen;if(a!==q)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.decodeScryptParams()",`Decryption failed: keystore.crypto.kdfparams.dklen parameter must be ${q}`,{keystore:n,dkLen:a});return {N:t,dkLen:q,name:ye,p:r,r:i,salt:e}}function kn(n){let e=n.salt??d.randomBytes(q),t=J.N,i=J.r,r=J.p;if(n.scrypt!=null&&(n.scrypt.N!=null&&(t=n.scrypt.N),n.scrypt.r!=null&&(i=n.scrypt.r),n.scrypt.p!=null&&(r=n.scrypt.p)),t<=0||(BigInt(t)&BigInt(t-1))!==BigInt(0))throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.encodeScryptParams()","Encryption failed: invalid options.scrypt.N parameter.",{options:n,N:t});if(i<=0||!Number.isSafeInteger(i))throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.encodeScryptParams()","Encryption failed: invalid options.scrypt.r parameter.",{options:n,r:i});if(r<=0||!Number.isSafeInteger(r))throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.encodeScryptParams()","Encryption failed: invalid options.scrypt.p parameter.",{options:n,p:r});return {name:ye,dkLen:q,N:t,p:r,r:i,salt:e}}function Hn(n,e){return Kn(n,e,{scrypt:{N:J.N,r:J.r,p:J.p}})}function Kn(n,e,t){try{let i=kn(t),r=scrypt(e,i.salt,{N:i.N,r:i.r,p:i.p,dkLen:i.dkLen}),a=t.iv??d.randomBytes(16);if(a.length!==16)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.encryptKeystore()","Encryption failed: invalid options.iv length.",{iv:a});let o=t.uuid??d.randomBytes(16);if(o.length!==16)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.encryptKeystore()","Encryption failed: invalid options.uuid length.",{uuidRandom:o});let c=r.slice(16,32),m=ctr(r.slice(0,16),a).encrypt(n);return {address:f.ofPrivateKey(n).toString(),crypto:{cipher:ze,cipherparams:{iv:s.of(a).digits},ciphertext:s.of(m).digits,kdf:"scrypt",kdfparams:{dklen:q,n:i.N,p:i.p,r:i.r,salt:s.of(i.salt).digits},mac:P.of(v.concatBytes(c,m)).digits},id:Xn(o),version:qe}}finally{n.fill(0),e.fill(0);}}function Gn(n,e){return _n(n,e)}function _n(n,e){try{if(n.crypto.cipher.toLowerCase()!==ze)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.decryptKeystore()","Decryption failed: unsupported crypto cipher algorithm.",{cipher:n.crypto.cipher.toLowerCase()});if(n.crypto.kdf.toLowerCase()!==ye)throw new InvalidKeystoreParams("(EXPERIMENTAL) keystore.decryptKeystore()","Decryption failed: unsupported crypto key derivation function.",{key