@hiero-ledger/sdk 2.73.1 → 2.73.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/umd.js +79 -31
- package/dist/umd.min.js +2 -2
- package/lib/account/AccountId.cjs +4 -4
- package/lib/account/AccountId.js +1 -1
- package/lib/account/AccountId.js.map +1 -1
- package/lib/client/Client.cjs +48 -0
- package/lib/client/Client.d.ts +14 -0
- package/lib/client/Client.js +1 -1
- package/lib/client/Client.js.map +1 -1
- package/lib/query/MirrorNodeContractQuery.cjs +15 -9
- package/lib/query/MirrorNodeContractQuery.js +1 -1
- package/lib/query/MirrorNodeContractQuery.js.map +1 -1
- package/lib/version.js +1 -1
- package/package.json +1 -1
- package/src/account/AccountId.js +6 -10
- package/src/client/Client.js +55 -0
- package/src/query/MirrorNodeContractQuery.js +16 -19
|
@@ -153,13 +153,13 @@ class AccountId {
|
|
|
153
153
|
if (this.evmAddress === null) {
|
|
154
154
|
throw new Error("field `evmAddress` should not be null");
|
|
155
155
|
}
|
|
156
|
-
const
|
|
156
|
+
const mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;
|
|
157
|
+
const url = `${mirrorRestApiBaseUrl}/accounts/${this.evmAddress.toString()}`;
|
|
157
158
|
await new Promise(resolve => {
|
|
158
159
|
setTimeout(resolve, 3000);
|
|
159
160
|
});
|
|
160
161
|
|
|
161
162
|
/* eslint-disable */
|
|
162
|
-
const url = `https://${mirrorUrl}/api/v1/accounts/${this.evmAddress.toString()}`;
|
|
163
163
|
const response = await fetch(url);
|
|
164
164
|
const data = await response.json();
|
|
165
165
|
const mirrorAccountId = data.account;
|
|
@@ -178,13 +178,13 @@ class AccountId {
|
|
|
178
178
|
if (this.num === null) {
|
|
179
179
|
throw new Error("field `num` should not be null");
|
|
180
180
|
}
|
|
181
|
-
const
|
|
181
|
+
const mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;
|
|
182
|
+
const url = `${mirrorRestApiBaseUrl}/accounts/${this.num.toString()}`;
|
|
182
183
|
await new Promise(resolve => {
|
|
183
184
|
setTimeout(resolve, 3000);
|
|
184
185
|
});
|
|
185
186
|
|
|
186
187
|
/* eslint-disable */
|
|
187
|
-
const url = `https://${mirrorUrl}/api/v1/accounts/${this.num.toString()}`;
|
|
188
188
|
const response = await fetch(url);
|
|
189
189
|
const data = await response.json();
|
|
190
190
|
const mirrorAccountId = data.evm_address;
|
package/lib/account/AccountId.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import s from"long";import{constructor as t,fromStringSplitter as e,fromEvmAddress as r,validateChecksum as i,fromSolidityAddress as n,toSolidityAddress as l,toEvmAddress as a,toStringWithChecksum as o}from"../EntityIdHelper.js";import*as m from"@hashgraph/proto";import u from"../Key.js";import h from"../PublicKey.js";import d from"../Cache.js";import c from"../EvmAddress.js";import{decode as f}from"../encoding/hex.js";import{isLongZeroAddress as v}from"../util.js";class y{constructor(s,e,r,i,n){const l=t(s,e,r);this.shard=l.shard,this.realm=l.realm,this.num=l.num,this.aliasKey=null!=i?i:null,this.evmAddress=null!=n?n:null,this._checksum=null}static fromString(t){let r,i,n=s.ZERO,l=s.ZERO,a=s.ZERO;if(t.startsWith("0x")&&42==t.length||40==t.length)i=c.fromString(t);else{const o=e(t);if(Number.isNaN(o.shard)||Number.isNaN(o.realm))throw new Error("invalid format for entity ID");null!=o.shard&&(n=s.fromString(o.shard)),null!=o.realm&&(l=s.fromString(o.realm)),o.numOrHex.length<20?a=s.fromString(o.numOrHex):40==o.numOrHex.length?i=c.fromString(o.numOrHex):r=h.fromString(o.numOrHex)}return new y(n,l,a,r,i)}static fromEvmAddress(s,t,e){const i="string"==typeof e?c.fromString(e):e,[n,l,a,o]=r(s,t,i.toString());return new y(n,l,a,void 0,o||void 0)}static fromEvmPublicAddress(s){return new y(0,0,0,void 0,s)}static _fromProtobuf(s){let t,e;return null!=s.alias&&(20===s.alias.length?e=c.fromBytes(s.alias):t=u._fromProtobufKey(m.proto.Key.decode(s.alias))),t instanceof h||(t=void 0),new y(null!=s.shardNum?s.shardNum:0,null!=s.realmNum?s.realmNum:0,null!=s.accountNum?s.accountNum:0,t,e)}get checksum(){return this._checksum}getEvmAddress(){return this.evmAddress}async populateAccountNum(t){if(null===this.evmAddress)throw new Error("field `evmAddress` should not be null");const e=`${t.mirrorRestApiBaseUrl}/accounts/${this.evmAddress.toString()}`;await new Promise(s=>{setTimeout(s,3e3)});const r=await fetch(e),i=(await r.json()).account;return this.num=s.fromString(i.slice(i.lastIndexOf(".")+1)),this}async populateAccountEvmAddress(s){if(null===this.num)throw new Error("field `num` should not be null");const t=`${s.mirrorRestApiBaseUrl}/accounts/${this.num.toString()}`;await new Promise(s=>{setTimeout(s,3e3)});const e=await fetch(t),r=(await e.json()).evm_address;return this.evmAddress=c.fromString(r),this}validate(s){console.warn("Deprecated: Use `validateChecksum` instead"),this.validateChecksum(s)}validateChecksum(s){if(null!=this.aliasKey)throw new Error("cannot calculate checksum with an account ID that has a aliasKey");i(this.shard,this.realm,this.num,this._checksum,s)}static fromBytes(s){return y._fromProtobuf(m.proto.AccountID.decode(s))}static fromSolidityAddress(s){return v(f(s))?new y(...n(s)):this.fromEvmAddress(0,0,s)}toSolidityAddress(){return null!=this.evmAddress?this.evmAddress.toString():null!=this.aliasKey&&"secp256k1"==this.aliasKey._key._type?this.aliasKey.toEvmAddress():l([this.shard,this.realm,this.num])}toEvmAddress(){return null!=this.evmAddress?a(this.evmAddress.toBytes()):a(this.num)}_toProtobuf(){let t=null;null!=this.aliasKey?t=m.proto.Key.encode(this.aliasKey._toProtobufKey()).finish():null!=this.evmAddress&&(t=this.evmAddress._bytes);const e=this.num.eq(s.fromBigInt(0n))&&t;return t?{alias:e?t:null,accountNum:e?null:this.num,shardNum:this.shard,realmNum:this.realm}:{alias:null,accountNum:this.num,shardNum:this.shard,realmNum:this.realm}}toBytes(){return m.proto.AccountID.encode(this._toProtobuf()).finish()}toString(){let s=this.num.toString();return null!=this.aliasKey?s=this.aliasKey.toString():null!=this.evmAddress&&(s=this.evmAddress.toString()),`${this.shard.toString()}.${this.realm.toString()}.${s}`}toStringWithChecksum(s){if(null!=this.aliasKey)throw new Error("cannot calculate checksum with an account ID that has a aliasKey");return o(this.toString(),s)}equals(s){let t=!1;return null!=this.aliasKey&&null!=s.aliasKey?t=this.aliasKey.equals(s.aliasKey):null!=this.evmAddress&&null!=s.evmAddress?t=this.evmAddress.equals(s.evmAddress):null==this.aliasKey&&null==s.aliasKey&&null==this.evmAddress&&null==s.evmAddress&&(t=this.num.eq(s.num)),this.shard.eq(s.shard)&&this.realm.eq(s.realm)&&t}clone(){const s=new y(this);return s._checksum=this._checksum,s.aliasKey=this.aliasKey,s.evmAddress=this.evmAddress,s}compare(s){let t=this.shard.compare(s.shard);if(0!=t)return t;if(t=this.realm.compare(s.realm),0!=t)return t;if(null!=this.aliasKey&&null!=s.aliasKey){const t=this.aliasKey.toString(),e=s.aliasKey.toString();return t>e?1:t<e?-1:0}if(null!=this.evmAddress&&null!=s.evmAddress){const t=this.evmAddress.toString(),e=s.evmAddress.toString();return t>e?1:t<e?-1:0}return null==this.aliasKey&&null==s.aliasKey&&null==this.evmAddress&&null==s.evmAddress?this.num.compare(s.num):1}}d.setAccountIdConstructor((t,e,r)=>new y(t,e,s.ZERO,r));export{y as default};
|
|
2
2
|
//# sourceMappingURL=AccountId.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountId.js","sources":["../../src/account/AccountId.js"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport Long from \"long\";\nimport * as EntityIdHelper from \"../EntityIdHelper.js\";\nimport * as HieroProto from \"@hashgraph/proto\";\nimport Key from \"../Key.js\";\nimport PublicKey from \"../PublicKey.js\";\nimport CACHE from \"../Cache.js\";\nimport EvmAddress from \"../EvmAddress.js\";\nimport * as hex from \".././encoding/hex.js\";\nimport { isLongZeroAddress } from \"../util.js\";\n\n/**\n * @typedef {import(\"../client/Client.js\").default<*, *>} Client\n */\n\n/**\n * The ID for a crypto-currency account on Hedera.\n */\nexport default class AccountId {\n /**\n * @param {number | Long | import(\"../EntityIdHelper\").IEntityId} props\n * @param {(number | Long)=} realm\n * @param {(number | Long)=} num\n * @param {(PublicKey)=} aliasKey\n * @param {(EvmAddress)=} evmAddress\n */\n constructor(props, realm, num, aliasKey, evmAddress) {\n const result = EntityIdHelper.constructor(props, realm, num);\n\n this.shard = result.shard;\n this.realm = result.realm;\n this.num = result.num;\n this.aliasKey = aliasKey != null ? aliasKey : null;\n this.evmAddress = evmAddress != null ? evmAddress : null;\n\n /**\n * @type {string | null}\n */\n this._checksum = null;\n }\n\n /**\n * @description Accepts the following formats as string:\n * - as stand alone nubmers\n * - as shard.realm.num\n * - as shard.realm.hex (wo 0x prefix)\n * - hex (w/wo 0x prefix)\n * @param {string} text\n * @returns {AccountId}\n */\n static fromString(text) {\n let shard = Long.ZERO;\n let realm = Long.ZERO;\n let num = Long.ZERO;\n let aliasKey = undefined;\n let evmAddress = undefined;\n\n if ((text.startsWith(\"0x\") && text.length == 42) || text.length == 40) {\n evmAddress = EvmAddress.fromString(text);\n } else {\n const result = EntityIdHelper.fromStringSplitter(text);\n\n if (Number.isNaN(result.shard) || Number.isNaN(result.realm)) {\n throw new Error(\"invalid format for entity ID\");\n }\n\n if (result.shard != null) shard = Long.fromString(result.shard);\n if (result.realm != null) realm = Long.fromString(result.realm);\n\n if (result.numOrHex.length < 20) {\n num = Long.fromString(result.numOrHex);\n } else if (result.numOrHex.length == 40) {\n evmAddress = EvmAddress.fromString(result.numOrHex);\n } else {\n aliasKey = PublicKey.fromString(result.numOrHex);\n }\n }\n\n return new AccountId(shard, realm, num, aliasKey, evmAddress);\n }\n\n /**\n * @description This handles both long-zero format and evm address format addresses.\n * If an actual evm address is passed, please use `AccountId.populateAccountNum(client)` method\n * to get the actual `num` value, since there is no cryptographic relation to the evm address\n * and cannot be populated directly\n * @param {Long | number} shard\n * @param {Long | number} realm\n * @param {EvmAddress | string} evmAddress\n * @returns {AccountId}\n */\n static fromEvmAddress(shard, realm, evmAddress) {\n const evmAddressObj =\n typeof evmAddress === \"string\"\n ? EvmAddress.fromString(evmAddress)\n : evmAddress;\n\n const [shardLong, realmLong, num, address] =\n EntityIdHelper.fromEvmAddress(\n shard,\n realm,\n evmAddressObj.toString(),\n );\n\n return new AccountId(\n shardLong,\n realmLong,\n num,\n undefined,\n address || undefined,\n );\n }\n\n /**\n * @deprecated - Use `fromEvmAddress` instead\n * @summary Accepts an evm address only as `EvmAddress` type\n * @param {EvmAddress} evmAddress\n * @returns {AccountId}\n */\n static fromEvmPublicAddress(evmAddress) {\n return new AccountId(0, 0, 0, undefined, evmAddress);\n }\n\n /**\n * @internal\n * @param {HieroProto.proto.IAccountID} id\n * @returns {AccountId}\n */\n static _fromProtobuf(id) {\n let aliasKey = undefined;\n let evmAddress = undefined;\n\n if (id.alias != null) {\n if (id.alias.length === 20) {\n evmAddress = EvmAddress.fromBytes(id.alias);\n } else {\n aliasKey = Key._fromProtobufKey(\n HieroProto.proto.Key.decode(id.alias),\n );\n }\n }\n\n if (!(aliasKey instanceof PublicKey)) {\n aliasKey = undefined;\n }\n\n return new AccountId(\n id.shardNum != null ? id.shardNum : 0,\n id.realmNum != null ? id.realmNum : 0,\n id.accountNum != null ? id.accountNum : 0,\n aliasKey,\n evmAddress,\n );\n }\n\n /**\n * @returns {string | null}\n */\n get checksum() {\n return this._checksum;\n }\n\n /**\n * @returns {?EvmAddress}\n */\n getEvmAddress() {\n return this.evmAddress;\n }\n\n /**\n * @description Gets the actual `num` field of the `AccountId` from the Mirror Node.\n * Should be used after generating `AccountId.fromEvmAddress()` because it sets the `num` field to `0`\n * automatically since there is no connection between the `num` and the `evmAddress`\n * @param {Client} client\n * @returns {Promise<AccountId>}\n */\n async populateAccountNum(client) {\n if (this.evmAddress === null) {\n throw new Error(\"field `evmAddress` should not be null\");\n }\n const mirrorUrl = client.mirrorNetwork[0].slice(\n 0,\n client.mirrorNetwork[0].indexOf(\":\"),\n );\n\n await new Promise((resolve) => {\n setTimeout(resolve, 3000);\n });\n\n /* eslint-disable */\n const url = `https://${mirrorUrl}/api/v1/accounts/${this.evmAddress.toString()}`;\n const response = await fetch(url);\n const data = await response.json();\n const mirrorAccountId = data.account;\n\n this.num = Long.fromString(\n mirrorAccountId.slice(mirrorAccountId.lastIndexOf(\".\") + 1),\n );\n /* eslint-enable */\n\n return this;\n }\n\n /**\n * @description Populates `evmAddress` field of the `AccountId` extracted from the Mirror Node.\n * @param {Client} client\n * @returns {Promise<AccountId>}\n */\n async populateAccountEvmAddress(client) {\n if (this.num === null) {\n throw new Error(\"field `num` should not be null\");\n }\n const mirrorUrl = client.mirrorNetwork[0].slice(\n 0,\n client.mirrorNetwork[0].indexOf(\":\"),\n );\n\n await new Promise((resolve) => {\n setTimeout(resolve, 3000);\n });\n\n /* eslint-disable */\n const url = `https://${mirrorUrl}/api/v1/accounts/${this.num.toString()}`;\n const response = await fetch(url);\n const data = await response.json();\n const mirrorAccountId = data.evm_address;\n\n this.evmAddress = EvmAddress.fromString(mirrorAccountId);\n /* eslint-enable */\n\n return this;\n }\n\n /**\n * @deprecated - Use `validateChecksum` instead\n * @param {Client} client\n */\n validate(client) {\n console.warn(\"Deprecated: Use `validateChecksum` instead\");\n this.validateChecksum(client);\n }\n\n /**\n * @param {Client} client\n */\n validateChecksum(client) {\n if (this.aliasKey != null) {\n throw new Error(\n \"cannot calculate checksum with an account ID that has a aliasKey\",\n );\n }\n\n EntityIdHelper.validateChecksum(\n this.shard,\n this.realm,\n this.num,\n this._checksum,\n client,\n );\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {AccountId}\n */\n static fromBytes(bytes) {\n return AccountId._fromProtobuf(\n HieroProto.proto.AccountID.decode(bytes),\n );\n }\n\n /**\n * @deprecated - Use `fromEvmAddress` instead\n * @param {string} address\n * @returns {AccountId}\n */\n static fromSolidityAddress(address) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (isLongZeroAddress(hex.decode(address))) {\n return new AccountId(\n ...EntityIdHelper.fromSolidityAddress(address),\n );\n } else {\n return this.fromEvmAddress(0, 0, address);\n }\n }\n\n /**\n * @description Statically compute the EVM address. Use only with non-native EVM accounts.\n * @deprecated - Use `toEvmAddress` instead\n * If the account is EVM-native, the EVM address depends on the public key and is not directly related to the account ID.\n * @returns {string}\n */\n toSolidityAddress() {\n if (this.evmAddress != null) {\n return this.evmAddress.toString();\n } else if (\n this.aliasKey != null &&\n this.aliasKey._key._type == \"secp256k1\"\n ) {\n return this.aliasKey.toEvmAddress();\n } else {\n return EntityIdHelper.toSolidityAddress([\n this.shard,\n this.realm,\n this.num,\n ]);\n }\n }\n\n /**\n * @returns {string} EVM-compatible address representation of the entity\n */\n toEvmAddress() {\n if (this.evmAddress != null) {\n return EntityIdHelper.toEvmAddress(this.evmAddress.toBytes());\n }\n\n return EntityIdHelper.toEvmAddress(this.num);\n }\n\n //TODO remove the comments after we get to HIP-631\n /**\n * @internal\n * @returns {HieroProto.proto.IAccountID}\n */\n _toProtobuf() {\n let alias = null;\n //let evmAddress = null;\n\n if (this.aliasKey != null) {\n alias = HieroProto.proto.Key.encode(\n this.aliasKey._toProtobufKey(),\n ).finish();\n } else if (this.evmAddress != null) {\n alias = this.evmAddress._bytes;\n }\n\n /* if (this.evmAddress != null) {\n evmAddress = this.evmAddress._bytes;\n } */\n\n const isHollowAccount = this.num.eq(Long.fromBigInt(0n)) && alias;\n\n if (alias) {\n return {\n alias: isHollowAccount ? alias : null,\n accountNum: isHollowAccount ? null : this.num,\n shardNum: this.shard,\n realmNum: this.realm,\n };\n }\n return {\n alias: null,\n accountNum: this.num,\n shardNum: this.shard,\n realmNum: this.realm,\n };\n }\n\n /**\n * @returns {Uint8Array}\n */\n toBytes() {\n return HieroProto.proto.AccountID.encode(this._toProtobuf()).finish();\n }\n\n /**\n * @returns {string}\n */\n toString() {\n let account = this.num.toString();\n\n if (this.aliasKey != null) {\n account = this.aliasKey.toString();\n } else if (this.evmAddress != null) {\n account = this.evmAddress.toString();\n }\n\n return `${this.shard.toString()}.${this.realm.toString()}.${account}`;\n }\n\n /**\n * @param {Client} client\n * @returns {string}\n */\n toStringWithChecksum(client) {\n if (this.aliasKey != null) {\n throw new Error(\n \"cannot calculate checksum with an account ID that has a aliasKey\",\n );\n }\n\n return EntityIdHelper.toStringWithChecksum(this.toString(), client);\n }\n\n /**\n * @param {this} other\n * @returns {boolean}\n */\n equals(other) {\n let account = false;\n\n if (this.aliasKey != null && other.aliasKey != null) {\n account = this.aliasKey.equals(other.aliasKey);\n } else if (this.evmAddress != null && other.evmAddress != null) {\n account = this.evmAddress.equals(other.evmAddress);\n } else if (\n this.aliasKey == null &&\n other.aliasKey == null &&\n this.evmAddress == null &&\n other.evmAddress == null\n ) {\n account = this.num.eq(other.num);\n }\n\n return (\n this.shard.eq(other.shard) && this.realm.eq(other.realm) && account\n );\n }\n\n /**\n * @returns {AccountId}\n */\n clone() {\n const id = new AccountId(this);\n id._checksum = this._checksum;\n id.aliasKey = this.aliasKey;\n id.evmAddress = this.evmAddress;\n return id;\n }\n\n /**\n * @param {AccountId} other\n * @returns {number}\n */\n compare(other) {\n let comparison = this.shard.compare(other.shard);\n if (comparison != 0) {\n return comparison;\n }\n\n comparison = this.realm.compare(other.realm);\n if (comparison != 0) {\n return comparison;\n }\n\n if (this.aliasKey != null && other.aliasKey != null) {\n const t = this.aliasKey.toString();\n const o = other.aliasKey.toString();\n\n if (t > o) {\n return 1;\n } else if (t < o) {\n return -1;\n } else {\n return 0;\n }\n } else if (this.evmAddress != null && other.evmAddress != null) {\n const t = this.evmAddress.toString();\n const o = other.evmAddress.toString();\n\n if (t > o) {\n return 1;\n } else if (t < o) {\n return -1;\n } else {\n return 0;\n }\n } else if (\n this.aliasKey == null &&\n other.aliasKey == null &&\n this.evmAddress == null &&\n other.evmAddress == null\n ) {\n return this.num.compare(other.num);\n } else {\n return 1;\n }\n }\n}\n\nCACHE.setAccountIdConstructor(\n (shard, realm, key) => new AccountId(shard, realm, Long.ZERO, key),\n);\n"],"names":["AccountId","constructor","props","realm","num","aliasKey","evmAddress","result","EntityIdHelper.constructor","this","shard","_checksum","fromString","text","Long","ZERO","startsWith","length","EvmAddress","EntityIdHelper.fromStringSplitter","Number","isNaN","Error","numOrHex","PublicKey","fromEvmAddress","evmAddressObj","shardLong","realmLong","address","EntityIdHelper.fromEvmAddress","toString","undefined","fromEvmPublicAddress","_fromProtobuf","id","alias","fromBytes","Key","_fromProtobufKey","HieroProto","proto","decode","shardNum","realmNum","accountNum","checksum","getEvmAddress","populateAccountNum","client","mirrorUrl","mirrorNetwork","slice","indexOf","Promise","resolve","setTimeout","url","response","fetch","mirrorAccountId","json","account","lastIndexOf","populateAccountEvmAddress","evm_address","validate","console","warn","validateChecksum","EntityIdHelper.validateChecksum","bytes","AccountID","fromSolidityAddress","isLongZeroAddress","hex.decode","EntityIdHelper.fromSolidityAddress","toSolidityAddress","_key","_type","toEvmAddress","EntityIdHelper.toSolidityAddress","EntityIdHelper.toEvmAddress","toBytes","_toProtobuf","encode","_toProtobufKey","finish","_bytes","isHollowAccount","eq","fromBigInt","toStringWithChecksum","EntityIdHelper.toStringWithChecksum","equals","other","clone","compare","comparison","t","o","CACHE","setAccountIdConstructor","key"],"mappings":"sdAmBe,MAAMA,EAQjB,WAAAC,CAAYC,EAAOC,EAAOC,EAAKC,EAAUC,GACrC,MAAMC,EAASC,EAA2BN,EAAOC,EAAOC,GAExDK,KAAKC,MAAQH,EAAOG,MACpBD,KAAKN,MAAQI,EAAOJ,MACpBM,KAAKL,IAAMG,EAAOH,IAClBK,KAAKJ,SAAuB,MAAZA,EAAmBA,EAAW,KAC9CI,KAAKH,WAA2B,MAAdA,EAAqBA,EAAa,KAKpDG,KAAKE,UAAY,IACzB,CAWI,iBAAOC,CAAWC,GACd,IAGIR,EACAC,EAJAI,EAAQI,EAAKC,KACbZ,EAAQW,EAAKC,KACbX,EAAMU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AA0C,MAApByF,EAAMzF,WAAoB,CAC5D,MAAM6F,EAAI1F,KAAKH,WAAWyB,WACpBqE,EAAIL,EAAMzF,WAAWyB,WAE3B,OAAIoE,EAAIC,EACG,EACAD,EAAIC,GACF,EAEF,CAEvB,CAAe,OACc,MAAjB3F,KAAKJ,UACa,MAAlB0F,EAAM1F,UACa,MAAnBI,KAAKH,YACe,MAApByF,EAAMzF,WAECG,KAAKL,IAAI6F,QAAQF,EAAM3F,KAEvB,CAEnB,EAGAiG,EAAMC,wBACF,CAAC5F,EAAOP,EAAOoG,IAAQ,IAAIvG,EAAUU,EAAOP,EAAOW,EAAKC,KAAMwF"}
|
|
1
|
+
{"version":3,"file":"AccountId.js","sources":["../../src/account/AccountId.js"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport Long from \"long\";\nimport * as EntityIdHelper from \"../EntityIdHelper.js\";\nimport * as HieroProto from \"@hashgraph/proto\";\nimport Key from \"../Key.js\";\nimport PublicKey from \"../PublicKey.js\";\nimport CACHE from \"../Cache.js\";\nimport EvmAddress from \"../EvmAddress.js\";\nimport * as hex from \".././encoding/hex.js\";\nimport { isLongZeroAddress } from \"../util.js\";\n\n/**\n * @typedef {import(\"../client/Client.js\").default<*, *>} Client\n */\n\n/**\n * The ID for a crypto-currency account on Hedera.\n */\nexport default class AccountId {\n /**\n * @param {number | Long | import(\"../EntityIdHelper\").IEntityId} props\n * @param {(number | Long)=} realm\n * @param {(number | Long)=} num\n * @param {(PublicKey)=} aliasKey\n * @param {(EvmAddress)=} evmAddress\n */\n constructor(props, realm, num, aliasKey, evmAddress) {\n const result = EntityIdHelper.constructor(props, realm, num);\n\n this.shard = result.shard;\n this.realm = result.realm;\n this.num = result.num;\n this.aliasKey = aliasKey != null ? aliasKey : null;\n this.evmAddress = evmAddress != null ? evmAddress : null;\n\n /**\n * @type {string | null}\n */\n this._checksum = null;\n }\n\n /**\n * @description Accepts the following formats as string:\n * - as stand alone nubmers\n * - as shard.realm.num\n * - as shard.realm.hex (wo 0x prefix)\n * - hex (w/wo 0x prefix)\n * @param {string} text\n * @returns {AccountId}\n */\n static fromString(text) {\n let shard = Long.ZERO;\n let realm = Long.ZERO;\n let num = Long.ZERO;\n let aliasKey = undefined;\n let evmAddress = undefined;\n\n if ((text.startsWith(\"0x\") && text.length == 42) || text.length == 40) {\n evmAddress = EvmAddress.fromString(text);\n } else {\n const result = EntityIdHelper.fromStringSplitter(text);\n\n if (Number.isNaN(result.shard) || Number.isNaN(result.realm)) {\n throw new Error(\"invalid format for entity ID\");\n }\n\n if (result.shard != null) shard = Long.fromString(result.shard);\n if (result.realm != null) realm = Long.fromString(result.realm);\n\n if (result.numOrHex.length < 20) {\n num = Long.fromString(result.numOrHex);\n } else if (result.numOrHex.length == 40) {\n evmAddress = EvmAddress.fromString(result.numOrHex);\n } else {\n aliasKey = PublicKey.fromString(result.numOrHex);\n }\n }\n\n return new AccountId(shard, realm, num, aliasKey, evmAddress);\n }\n\n /**\n * @description This handles both long-zero format and evm address format addresses.\n * If an actual evm address is passed, please use `AccountId.populateAccountNum(client)` method\n * to get the actual `num` value, since there is no cryptographic relation to the evm address\n * and cannot be populated directly\n * @param {Long | number} shard\n * @param {Long | number} realm\n * @param {EvmAddress | string} evmAddress\n * @returns {AccountId}\n */\n static fromEvmAddress(shard, realm, evmAddress) {\n const evmAddressObj =\n typeof evmAddress === \"string\"\n ? EvmAddress.fromString(evmAddress)\n : evmAddress;\n\n const [shardLong, realmLong, num, address] =\n EntityIdHelper.fromEvmAddress(\n shard,\n realm,\n evmAddressObj.toString(),\n );\n\n return new AccountId(\n shardLong,\n realmLong,\n num,\n undefined,\n address || undefined,\n );\n }\n\n /**\n * @deprecated - Use `fromEvmAddress` instead\n * @summary Accepts an evm address only as `EvmAddress` type\n * @param {EvmAddress} evmAddress\n * @returns {AccountId}\n */\n static fromEvmPublicAddress(evmAddress) {\n return new AccountId(0, 0, 0, undefined, evmAddress);\n }\n\n /**\n * @internal\n * @param {HieroProto.proto.IAccountID} id\n * @returns {AccountId}\n */\n static _fromProtobuf(id) {\n let aliasKey = undefined;\n let evmAddress = undefined;\n\n if (id.alias != null) {\n if (id.alias.length === 20) {\n evmAddress = EvmAddress.fromBytes(id.alias);\n } else {\n aliasKey = Key._fromProtobufKey(\n HieroProto.proto.Key.decode(id.alias),\n );\n }\n }\n\n if (!(aliasKey instanceof PublicKey)) {\n aliasKey = undefined;\n }\n\n return new AccountId(\n id.shardNum != null ? id.shardNum : 0,\n id.realmNum != null ? id.realmNum : 0,\n id.accountNum != null ? id.accountNum : 0,\n aliasKey,\n evmAddress,\n );\n }\n\n /**\n * @returns {string | null}\n */\n get checksum() {\n return this._checksum;\n }\n\n /**\n * @returns {?EvmAddress}\n */\n getEvmAddress() {\n return this.evmAddress;\n }\n\n /**\n * @description Gets the actual `num` field of the `AccountId` from the Mirror Node.\n * Should be used after generating `AccountId.fromEvmAddress()` because it sets the `num` field to `0`\n * automatically since there is no connection between the `num` and the `evmAddress`\n * @param {Client} client\n * @returns {Promise<AccountId>}\n */\n async populateAccountNum(client) {\n if (this.evmAddress === null) {\n throw new Error(\"field `evmAddress` should not be null\");\n }\n const mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;\n\n const url = `${mirrorRestApiBaseUrl}/accounts/${this.evmAddress.toString()}`;\n\n await new Promise((resolve) => {\n setTimeout(resolve, 3000);\n });\n\n /* eslint-disable */\n const response = await fetch(url);\n const data = await response.json();\n const mirrorAccountId = data.account;\n\n this.num = Long.fromString(\n mirrorAccountId.slice(mirrorAccountId.lastIndexOf(\".\") + 1),\n );\n /* eslint-enable */\n\n return this;\n }\n\n /**\n * @description Populates `evmAddress` field of the `AccountId` extracted from the Mirror Node.\n * @param {Client} client\n * @returns {Promise<AccountId>}\n */\n async populateAccountEvmAddress(client) {\n if (this.num === null) {\n throw new Error(\"field `num` should not be null\");\n }\n const mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;\n\n const url = `${mirrorRestApiBaseUrl}/accounts/${this.num.toString()}`;\n\n await new Promise((resolve) => {\n setTimeout(resolve, 3000);\n });\n\n /* eslint-disable */\n const response = await fetch(url);\n const data = await response.json();\n const mirrorAccountId = data.evm_address;\n\n this.evmAddress = EvmAddress.fromString(mirrorAccountId);\n /* eslint-enable */\n\n return this;\n }\n\n /**\n * @deprecated - Use `validateChecksum` instead\n * @param {Client} client\n */\n validate(client) {\n console.warn(\"Deprecated: Use `validateChecksum` instead\");\n this.validateChecksum(client);\n }\n\n /**\n * @param {Client} client\n */\n validateChecksum(client) {\n if (this.aliasKey != null) {\n throw new Error(\n \"cannot calculate checksum with an account ID that has a aliasKey\",\n );\n }\n\n EntityIdHelper.validateChecksum(\n this.shard,\n this.realm,\n this.num,\n this._checksum,\n client,\n );\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {AccountId}\n */\n static fromBytes(bytes) {\n return AccountId._fromProtobuf(\n HieroProto.proto.AccountID.decode(bytes),\n );\n }\n\n /**\n * @deprecated - Use `fromEvmAddress` instead\n * @param {string} address\n * @returns {AccountId}\n */\n static fromSolidityAddress(address) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (isLongZeroAddress(hex.decode(address))) {\n return new AccountId(\n ...EntityIdHelper.fromSolidityAddress(address),\n );\n } else {\n return this.fromEvmAddress(0, 0, address);\n }\n }\n\n /**\n * @description Statically compute the EVM address. Use only with non-native EVM accounts.\n * @deprecated - Use `toEvmAddress` instead\n * If the account is EVM-native, the EVM address depends on the public key and is not directly related to the account ID.\n * @returns {string}\n */\n toSolidityAddress() {\n if (this.evmAddress != null) {\n return this.evmAddress.toString();\n } else if (\n this.aliasKey != null &&\n this.aliasKey._key._type == \"secp256k1\"\n ) {\n return this.aliasKey.toEvmAddress();\n } else {\n return EntityIdHelper.toSolidityAddress([\n this.shard,\n this.realm,\n this.num,\n ]);\n }\n }\n\n /**\n * @returns {string} EVM-compatible address representation of the entity\n */\n toEvmAddress() {\n if (this.evmAddress != null) {\n return EntityIdHelper.toEvmAddress(this.evmAddress.toBytes());\n }\n\n return EntityIdHelper.toEvmAddress(this.num);\n }\n\n //TODO remove the comments after we get to HIP-631\n /**\n * @internal\n * @returns {HieroProto.proto.IAccountID}\n */\n _toProtobuf() {\n let alias = null;\n //let evmAddress = null;\n\n if (this.aliasKey != null) {\n alias = HieroProto.proto.Key.encode(\n this.aliasKey._toProtobufKey(),\n ).finish();\n } else if (this.evmAddress != null) {\n alias = this.evmAddress._bytes;\n }\n\n /* if (this.evmAddress != null) {\n evmAddress = this.evmAddress._bytes;\n } */\n\n const isHollowAccount = this.num.eq(Long.fromBigInt(0n)) && alias;\n\n if (alias) {\n return {\n alias: isHollowAccount ? alias : null,\n accountNum: isHollowAccount ? null : this.num,\n shardNum: this.shard,\n realmNum: this.realm,\n };\n }\n return {\n alias: null,\n accountNum: this.num,\n shardNum: this.shard,\n realmNum: this.realm,\n };\n }\n\n /**\n * @returns {Uint8Array}\n */\n toBytes() {\n return HieroProto.proto.AccountID.encode(this._toProtobuf()).finish();\n }\n\n /**\n * @returns {string}\n */\n toString() {\n let account = this.num.toString();\n\n if (this.aliasKey != null) {\n account = this.aliasKey.toString();\n } else if (this.evmAddress != null) {\n account = this.evmAddress.toString();\n }\n\n return `${this.shard.toString()}.${this.realm.toString()}.${account}`;\n }\n\n /**\n * @param {Client} client\n * @returns {string}\n */\n toStringWithChecksum(client) {\n if (this.aliasKey != null) {\n throw new Error(\n \"cannot calculate checksum with an account ID that has a aliasKey\",\n );\n }\n\n return EntityIdHelper.toStringWithChecksum(this.toString(), client);\n }\n\n /**\n * @param {this} other\n * @returns {boolean}\n */\n equals(other) {\n let account = false;\n\n if (this.aliasKey != null && other.aliasKey != null) {\n account = this.aliasKey.equals(other.aliasKey);\n } else if (this.evmAddress != null && other.evmAddress != null) {\n account = this.evmAddress.equals(other.evmAddress);\n } else if (\n this.aliasKey == null &&\n other.aliasKey == null &&\n this.evmAddress == null &&\n other.evmAddress == null\n ) {\n account = this.num.eq(other.num);\n }\n\n return (\n this.shard.eq(other.shard) && this.realm.eq(other.realm) && account\n );\n }\n\n /**\n * @returns {AccountId}\n */\n clone() {\n const id = new AccountId(this);\n id._checksum = this._checksum;\n id.aliasKey = this.aliasKey;\n id.evmAddress = this.evmAddress;\n return id;\n }\n\n /**\n * @param {AccountId} other\n * @returns {number}\n */\n compare(other) {\n let comparison = this.shard.compare(other.shard);\n if (comparison != 0) {\n return comparison;\n }\n\n comparison = this.realm.compare(other.realm);\n if (comparison != 0) {\n return comparison;\n }\n\n if (this.aliasKey != null && other.aliasKey != null) {\n const t = this.aliasKey.toString();\n const o = other.aliasKey.toString();\n\n if (t > o) {\n return 1;\n } else if (t < o) {\n return -1;\n } else {\n return 0;\n }\n } else if (this.evmAddress != null && other.evmAddress != null) {\n const t = this.evmAddress.toString();\n const o = other.evmAddress.toString();\n\n if (t > o) {\n return 1;\n } else if (t < o) {\n return -1;\n } else {\n return 0;\n }\n } else if (\n this.aliasKey == null &&\n other.aliasKey == null &&\n this.evmAddress == null &&\n other.evmAddress == null\n ) {\n return this.num.compare(other.num);\n } else {\n return 1;\n }\n }\n}\n\nCACHE.setAccountIdConstructor(\n (shard, realm, key) => new AccountId(shard, realm, Long.ZERO, key),\n);\n"],"names":["AccountId","constructor","props","realm","num","aliasKey","evmAddress","result","EntityIdHelper.constructor","this","shard","_checksum","fromString","text","Long","ZERO","startsWith","length","EvmAddress","EntityIdHelper.fromStringSplitter","Number","isNaN","Error","numOrHex","PublicKey","fromEvmAddress","evmAddressObj","shardLong","realmLong","address","EntityIdHelper.fromEvmAddress","toString","undefined","fromEvmPublicAddress","_fromProtobuf","id","alias","fromBytes","Key","_fromProtobufKey","HieroProto","proto","decode","shardNum","realmNum","accountNum","checksum","getEvmAddress","populateAccountNum","client","url","mirrorRestApiBaseUrl","Promise","resolve","setTimeout","response","fetch","mirrorAccountId","json","account","slice","lastIndexOf","populateAccountEvmAddress","evm_address","validate","console","warn","validateChecksum","EntityIdHelper.validateChecksum","bytes","AccountID","fromSolidityAddress","isLongZeroAddress","hex.decode","EntityIdHelper.fromSolidityAddress","toSolidityAddress","_key","_type","toEvmAddress","EntityIdHelper.toSolidityAddress","EntityIdHelper.toEvmAddress","toBytes","_toProtobuf","encode","_toProtobufKey","finish","_bytes","isHollowAccount","eq","fromBigInt","toStringWithChecksum","EntityIdHelper.toStringWithChecksum","equals","other","clone","compare","comparison","t","o","CACHE","setAccountIdConstructor","key"],"mappings":"sdAmBe,MAAMA,EAQjB,WAAAC,CAAYC,EAAOC,EAAOC,EAAKC,EAAUC,GACrC,MAAMC,EAASC,EAA2BN,EAAOC,EAAOC,GAExDK,KAAKC,MAAQH,EAAOG,MACpBD,KAAKN,MAAQI,EAAOJ,MACpBM,KAAKL,IAAMG,EAAOH,IAClBK,KAAKJ,SAAuB,MAAZA,EAAmBA,EAAW,KAC9CI,KAAKH,WAA2B,MAAdA,EAAqBA,EAAa,KAKpDG,KAAKE,UAAY,IACzB,CAWI,iBAAOC,CAAWC,GACd,IAGIR,EACAC,EAJAI,EAAQI,EAAKC,KACbZ,EAAQW,EAAKC,KACbX,EAAMU,EAAKC,KAIf,GAAKF,EAAKG,WAAW,OAAwB,IAAfH,EAAKI,QAAgC,IAAfJ,EAAKI,OACrDX,EAAaY,EAAWN,WAAWC,OAChC,CACH,MAAMN,EAASY,EAAkCN,GAEjD,GAAIO,OAAOC,MAAMd,EAAOG,QAAUU,OAAOC,MAAMd,EAAOJ,OAClD,MAAM,IAAImB,MAAM,gCAGA,MAAhBf,EAAOG,QAAeA,EAAQI,EAAKF,WAAWL,EAAOG,QACrC,MAAhBH,EAAOJ,QAAeA,EAAQW,EAAKF,WAAWL,EAAOJ,QAErDI,EAAOgB,SAASN,OAAS,GACzBb,EAAMU,EAAKF,WAAWL,EAAOgB,UACI,IAA1BhB,EAAOgB,SAASN,OACvBX,EAAaY,EAAWN,WAAWL,EAAOgB,UAE1ClB,EAAWmB,EAAUZ,WAAWL,EAAOgB,SAEvD,CAEQ,OAAO,IAAIvB,EA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K,IAAInC,EAAUS,MAIzB,OAHA0B,EAAGxB,UAAYF,KAAKE,UACpBwB,EAAG9B,SAAWI,KAAKJ,SACnB8B,EAAG7B,WAAaG,KAAKH,WACd6B,CACf,CAMI,OAAA4D,CAAQF,GACJ,IAAIG,EAAavF,KAAKC,MAAMqF,QAAQF,EAAMnF,OAC1C,GAAkB,GAAdsF,EACA,OAAOA,EAIX,GADAA,EAAavF,KAAKN,MAAM4F,QAAQF,EAAM1F,OACpB,GAAd6F,EACA,OAAOA,EAGX,GAAqB,MAAjBvF,KAAKJ,UAAsC,MAAlBwF,EAAMxF,SAAkB,CACjD,MAAM4F,EAAIxF,KAAKJ,SAAS0B,WAClBmE,EAAIL,EAAMxF,SAAS0B,WAEzB,OAAIkE,EAAIC,EACG,EACAD,EAAIC,GACF,EAEF,CAEvB,CAAe,GAAuB,MAAnBzF,KAAKH,YAA0C,MAApBuF,EAAMvF,WAAoB,CAC5D,MAAM2F,EAAIxF,KAAKH,WAAWyB,WACpBmE,EAAIL,EAAMvF,WAAWyB,WAE3B,OAAIkE,EAAIC,EACG,EACAD,EAAIC,GACF,EAEF,CAEvB,CAAe,OACc,MAAjBzF,KAAKJ,UACa,MAAlBwF,EAAMxF,UACa,MAAnBI,KAAKH,YACe,MAApBuF,EAAMvF,WAECG,KAAKL,IAAI2F,QAAQF,EAAMzF,KAEvB,CAEnB,EAGA+F,EAAMC,wBACF,CAAC1F,EAAOP,EAAOkG,IAAQ,IAAIrG,EAAUU,EAAOP,EAAOW,EAAKC,KAAMsF"}
|
package/lib/client/Client.cjs
CHANGED
|
@@ -259,6 +259,26 @@ class Client {
|
|
|
259
259
|
return this._mirrorNetwork.network;
|
|
260
260
|
}
|
|
261
261
|
|
|
262
|
+
/**
|
|
263
|
+
* @returns {string}
|
|
264
|
+
* @throws {Error} When no mirror network is configured or available
|
|
265
|
+
*/
|
|
266
|
+
get mirrorRestApiBaseUrl() {
|
|
267
|
+
try {
|
|
268
|
+
const mirrorNode = this._mirrorNetwork.getNextMirrorNode();
|
|
269
|
+
const host = mirrorNode.address.address;
|
|
270
|
+
const port = mirrorNode.address.port;
|
|
271
|
+
if (!host || !port) {
|
|
272
|
+
throw new Error("Mirror node has invalid address configuration");
|
|
273
|
+
}
|
|
274
|
+
const scheme = this._getSchemeFromHostAndPort(host, port);
|
|
275
|
+
return `${scheme}://${host}:${port}/api/v1`;
|
|
276
|
+
} catch (error) {
|
|
277
|
+
// Re-throw with a more descriptive error message
|
|
278
|
+
throw new Error("Client has no mirror network configured or no healthy mirror nodes are available");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
262
282
|
/**
|
|
263
283
|
* @returns {boolean}
|
|
264
284
|
*/
|
|
@@ -762,6 +782,34 @@ class Client {
|
|
|
762
782
|
}, this._networkUpdatePeriod);
|
|
763
783
|
}
|
|
764
784
|
|
|
785
|
+
/**
|
|
786
|
+
* Determines the appropriate scheme (http/https) based on the host and port.
|
|
787
|
+
*
|
|
788
|
+
* @private
|
|
789
|
+
* @param {string} host - The host address
|
|
790
|
+
* @param {number} port - The port number
|
|
791
|
+
* @returns {string} - The scheme ('http' or 'https')
|
|
792
|
+
*/
|
|
793
|
+
_getSchemeFromHostAndPort(host, port) {
|
|
794
|
+
// For localhost and 127.0.0.1, use HTTP scheme
|
|
795
|
+
if (host === "localhost" || host === "127.0.0.1") {
|
|
796
|
+
return "http";
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// Standard HTTPS ports
|
|
800
|
+
if (port === 443) {
|
|
801
|
+
return "https";
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// Standard HTTP ports
|
|
805
|
+
if (port === 80) {
|
|
806
|
+
return "http";
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// For other ports, assume HTTPS for security
|
|
810
|
+
return "https";
|
|
811
|
+
}
|
|
812
|
+
|
|
765
813
|
/**
|
|
766
814
|
* @returns {boolean}
|
|
767
815
|
*/
|
package/lib/client/Client.d.ts
CHANGED
|
@@ -183,6 +183,11 @@ export default class Client<ChannelT extends Channel, MirrorChannelT extends Mir
|
|
|
183
183
|
* @returns {string[]}
|
|
184
184
|
*/
|
|
185
185
|
get mirrorNetwork(): string[];
|
|
186
|
+
/**
|
|
187
|
+
* @returns {string}
|
|
188
|
+
* @throws {Error} When no mirror network is configured or available
|
|
189
|
+
*/
|
|
190
|
+
get mirrorRestApiBaseUrl(): string;
|
|
186
191
|
/**
|
|
187
192
|
* @returns {boolean}
|
|
188
193
|
*/
|
|
@@ -449,6 +454,15 @@ export default class Client<ChannelT extends Channel, MirrorChannelT extends Mir
|
|
|
449
454
|
* @private
|
|
450
455
|
*/
|
|
451
456
|
private _scheduleNetworkUpdate;
|
|
457
|
+
/**
|
|
458
|
+
* Determines the appropriate scheme (http/https) based on the host and port.
|
|
459
|
+
*
|
|
460
|
+
* @private
|
|
461
|
+
* @param {string} host - The host address
|
|
462
|
+
* @param {number} port - The port number
|
|
463
|
+
* @returns {string} - The scheme ('http' or 'https')
|
|
464
|
+
*/
|
|
465
|
+
private _getSchemeFromHostAndPort;
|
|
452
466
|
/**
|
|
453
467
|
* @returns {boolean}
|
|
454
468
|
*/
|
package/lib/client/Client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"../account/AccountId.js";import e from"../account/AccountBalanceQuery.js";import r from"../Hbar.js";import
|
|
1
|
+
import t from"../account/AccountId.js";import e from"../account/AccountBalanceQuery.js";import r from"../Hbar.js";import o from"./Network.js";import s from"./MirrorNetwork.js";import n from"../PublicKey.js";import i from"../PrivateKey.js";import a from"../LedgerId.js";import h from"../file/FileId.js";import"pino";import"../logger/LogLevel.js";import{convertToNumber as u}from"../util.js";import d from"../network/AddressBookQuery.js";class l{constructor(t){this._mirrorNetwork=new s(this._createMirrorNetworkChannel()),this._network=new o(this._createNetworkChannel()),this._operator=null,this._defaultMaxTransactionFee=null,this._defaultMaxQueryPayment=new r(1),null!=t&&null!=t.operator&&this.setOperator(t.operator.accountId,t.operator.privateKey),this._maxAttempts=null,this._signOnDemand=!1,this._autoValidateChecksums=!1,this._minBackoff=250,this._maxBackoff=8e3,this._defaultRegenerateTransactionId=!0,this._requestTimeout=null,this._isUpdatingNetwork=!1,this._networkUpdatePeriod=864e5,this._isShutdown=!1,this._shard=0,this._realm=0,null!=t&&!1!==t.scheduleNetworkUpdate&&this._scheduleNetworkUpdate(),null!=t&&null!=t.shard&&(this._shard=t.shard),null!=t&&null!=t.realm&&(this._realm=t.realm),this._timer,this._logger=null}setNetworkName(t){return console.warn("Deprecated: Use `setLedgerId` instead"),this.setLedgerId(t)}get networkName(){return console.warn("Deprecated: Use `ledgerId` instead"),null!=this.ledgerId?this.ledgerId.toString():null}setLedgerId(t){return this._network.setLedgerId("string"==typeof t?a.fromString(t):t),this}get ledgerId(){return null!=this._network._ledgerId?this._network.ledgerId:null}setNetwork(t){throw new Error("not implemented")}setNetworkFromAddressBook(t){return this._network.setNetworkFromAddressBook(t),this}get network(){return this._network.network}get shard(){return this._shard}get realm(){return this._realm}setMirrorNetwork(t){throw new Error("not implemented")}get mirrorNetwork(){return this._mirrorNetwork.network}get mirrorRestApiBaseUrl(){try{const t=this._mirrorNetwork.getNextMirrorNode(),e=t.address.address,r=t.address.port;if(!e||!r)throw new Error("Mirror node has invalid address configuration");return`${this._getSchemeFromHostAndPort(e,r)}://${e}:${r}/api/v1`}catch(t){throw new Error("Client has no mirror network configured or no healthy mirror nodes are available")}}get signOnDemand(){return this._signOnDemand}setSignOnDemand(t){this._signOnDemand=t}isTransportSecurity(){return this._network.isTransportSecurity()}setTransportSecurity(t){return this._network.setTransportSecurity(t),this}setOperator(t,e){const r="string"==typeof e?i.fromStringDer(e):e;return this.setOperatorWith(t,r.publicKey,t=>Promise.resolve(r.sign(t)))}getOperator(){return this._operator}setOperatorWith(e,r,o){const s=e instanceof t?e:t.fromString(e);return null!=this._network._ledgerId&&s.validateChecksum(this),this._operator={transactionSigner:o,accountId:s,publicKey:r instanceof n?r:n.fromString(r)},this}setAutoValidateChecksums(t){return this._autoValidateChecksums=t,this}isAutoValidateChecksumsEnabled(){return this._autoValidateChecksums}get operatorAccountId(){return null!=this._operator?this._operator.accountId:null}get operatorPublicKey(){return null!=this._operator?this._operator.publicKey:null}get defaultMaxTransactionFee(){return this._defaultMaxTransactionFee}get maxTransactionFee(){return this.defaultMaxTransactionFee}setDefaultMaxTransactionFee(t){if(t.toTinybars().toInt()<0)throw new Error("defaultMaxTransactionFee must be non-negative");return this._defaultMaxTransactionFee=t,this}setMaxTransactionFee(t){return this.setDefaultMaxTransactionFee(t)}get defaultRegenerateTransactionId(){return this._defaultRegenerateTransactionId}setDefaultRegenerateTransactionId(t){return this._defaultRegenerateTransactionId=t,this}get defaultMaxQueryPayment(){return this._defaultMaxQueryPayment}get maxQueryPayment(){return this.defaultMaxQueryPayment}setDefaultMaxQueryPayment(t){if(u(t.toTinybars())<0)throw new Error("defaultMaxQueryPayment must be non-negative");return this._defaultMaxQueryPayment=t,this}setMaxQueryPayment(t){return this.setDefaultMaxQueryPayment(t)}get maxAttempts(){return null!=this._maxAttempts?this._maxAttempts:10}setMaxAttempts(t){return this._maxAttempts=t,this}get maxNodeAttempts(){return this._network.maxNodeAttempts}setMaxNodeAttempts(t){return this._network.setMaxNodeAttempts(t),this}get nodeWaitTime(){return this._network.minBackoff}setNodeWaitTime(t){return this._network.setMinBackoff(t),this}get maxNodesPerTransaction(){return this._network.maxNodesPerTransaction}setMaxNodesPerTransaction(t){return this._network.setMaxNodesPerTransaction(t),this}setMinBackoff(t){if(null==t)throw new Error("minBackoff cannot be null.");if(t>this._maxBackoff)throw new Error("minBackoff cannot be larger than maxBackoff.");return this._minBackoff=t,this}get minBackoff(){return this._minBackoff}setMaxBackoff(t){if(null==t)throw new Error("maxBackoff cannot be null.");if(t<this._minBackoff)throw new Error("maxBackoff cannot be smaller than minBackoff.");return this._maxBackoff=t,this}get maxBackoff(){return this._maxBackoff}setNodeMinBackoff(t){return this._network.setMinBackoff(t),this}get nodeMinBackoff(){return this._network.minBackoff}setNodeMaxBackoff(t){return this._network.setMaxBackoff(t),this}get nodeMaxBackoff(){return this._network.maxBackoff}setNodeMinReadmitPeriod(t){return this._network.setNodeMinReadmitPeriod(t),this}get nodeMinReadmitPeriod(){return this._network.nodeMinReadmitPeriod}setNodeMaxReadmitPeriod(t){return this._network.setNodeMaxReadmitPeriod(t),this}get nodeMaxReadmitPeriod(){return this._network.nodeMaxReadmitPeriod}setRequestTimeout(t){return this._requestTimeout=t,this}get requestTimeout(){return this._requestTimeout}get networkUpdatePeriod(){return this._networkUpdatePeriod}setNetworkUpdatePeriod(t){return clearTimeout(this._timer),this._networkUpdatePeriod=t,this._scheduleNetworkUpdate(),this}setLogger(t){return this._logger=t,this}get logger(){return this._logger}async ping(r){await new e({accountId:r}).setNodeAccountIds([r instanceof t?r:t.fromString(r)]).execute(this)}async pingAll(){for(const t of Object.values(this._network.network))await this.ping(t)}async updateNetwork(){if(this._isUpdatingNetwork)return this;this._isUpdatingNetwork=!0;try{const t=await(new d).setFileId(h.getAddressBookFileIdFor(this._shard,this._realm)).execute(this);this.setNetworkFromAddressBook(t)}catch(t){this._logger&&this._logger.trace(`failed to update client address book: ${t.toString()}`)}finally{this._isUpdatingNetwork=!1}return this}close(){this._network.close(),this._mirrorNetwork.close(),this._isShutdown=!0,clearTimeout(this._timer)}_createNetworkChannel(){throw new Error("not implemented")}_createMirrorNetworkChannel(){throw new Error("not implemented")}_scheduleNetworkUpdate(){this._timer=setTimeout(async()=>{await this.updateNetwork(),this._isShutdown||this._scheduleNetworkUpdate()},this._networkUpdatePeriod)}_getSchemeFromHostAndPort(t,e){return"localhost"===t||"127.0.0.1"===t?"http":443===e?"https":80===e?"http":"https"}get isClientShutDown(){return this._isShutdown}static _validateNetworkConsistency(t){if(0===Object.keys(t).length)return;const[,e]=Object.entries(t)[0],r=e.toString(),[o,s]=r.split(".").map(Number),n=Object.values(t).every(t=>{const e=t.toString(),[r,n]=e.split(".").map(Number);return r===o&&n===s});if(!n)throw new Error("Network is not valid, all nodes must be in the same shard and realm")}static _extractShardRealm(t){const e=Object.entries(t);if(0===e.length)return{shard:0,realm:0};const[,r]=e[0],o=r.toString(),[s,n]=o.split(".").map(Number);return{shard:s,realm:n}}}export{l as default};
|
|
2
2
|
//# sourceMappingURL=Client.js.map
|
package/lib/client/Client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Client.js","sources":["../../src/client/Client.js"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport AccountId from \"../account/AccountId.js\";\nimport AccountBalanceQuery from \"../account/AccountBalanceQuery.js\";\nimport Hbar from \"../Hbar.js\";\nimport Network from \"./Network.js\";\nimport MirrorNetwork from \"./MirrorNetwork.js\";\nimport PublicKey from \"../PublicKey.js\";\nimport PrivateKey from \"../PrivateKey.js\";\nimport LedgerId from \"../LedgerId.js\";\nimport FileId from \"../file/FileId.js\";\nimport Logger from \"../logger/Logger.js\"; // eslint-disable-line\nimport { convertToNumber } from \"../util.js\";\nimport AddressBookQuery from \"../network/AddressBookQuery.js\";\n\n/**\n * @typedef {import(\"../channel/Channel.js\").default} Channel\n * @typedef {import(\"../channel/MirrorChannel.js\").default} MirrorChannel\n * @typedef {import(\"../address_book/NodeAddressBook.js\").default} NodeAddressBook\n */\n\n/**\n * @typedef {object} Operator\n * @property {string | PrivateKey} privateKey\n * @property {string | AccountId} accountId\n */\n\n/**\n * @typedef {object} ClientOperator\n * @property {PublicKey} publicKey\n * @property {AccountId} accountId\n * @property {(message: Uint8Array) => Promise<Uint8Array>} transactionSigner\n */\n\n/**\n * @typedef {object} ClientConfiguration\n * @property {{[key: string]: (string | AccountId)} | string} [network]\n * @property {string[] | string} [mirrorNetwork]\n * @property {Operator} [operator]\n * @property {boolean} [scheduleNetworkUpdate]\n * @property {number} [shard]\n * @property {number} [realm]\n */\n\n/**\n * @typedef {\"mainnet\" | \"testnet\" | \"previewnet\"} NetworkName\n */\n\n/**\n * The `Client` class is the main entry point for interacting with the Hedera Hashgraph network.\n * It provides methods for managing network connections, setting operators, handling transactions\n * and queries, and configuring various client settings.\n *\n * @abstract\n * @template {Channel} ChannelT\n * @template {MirrorChannel} MirrorChannelT\n */\nexport default class Client {\n /**\n * @protected\n * @hideconstructor\n * @param {ClientConfiguration} [props]\n */\n constructor(props) {\n /**\n * List of mirror network URLs.\n *\n * @internal\n * @type {MirrorNetwork}\n */\n this._mirrorNetwork = new MirrorNetwork(\n this._createMirrorNetworkChannel(),\n );\n\n /**\n * Map of node account ID (as a string)\n * to the node URL.\n *\n * @internal\n * @type {Network}\n */\n this._network = new Network(this._createNetworkChannel());\n\n /**\n * @internal\n * @type {?ClientOperator}\n */\n this._operator = null;\n\n /**\n * @private\n * @type {?Hbar}\n */\n this._defaultMaxTransactionFee = null;\n\n /**\n * @private\n * @type {Hbar}\n */\n this._defaultMaxQueryPayment = new Hbar(1);\n\n if (props != null) {\n if (props.operator != null) {\n this.setOperator(\n props.operator.accountId,\n props.operator.privateKey,\n );\n }\n }\n\n /** @type {number | null} */\n this._maxAttempts = null;\n\n /** @private */\n this._signOnDemand = false;\n\n /** @private */\n this._autoValidateChecksums = false;\n\n /** @private */\n this._minBackoff = 250;\n\n /** @private */\n this._maxBackoff = 8000;\n\n /** @private */\n this._defaultRegenerateTransactionId = true;\n\n /** @private */\n this._requestTimeout = null;\n\n /**\n * @type {boolean}\n */\n this._isUpdatingNetwork = false;\n\n /** @private */\n this._networkUpdatePeriod = 24 * 60 * 60 * 1000;\n\n /** @private */\n this._isShutdown = false;\n\n this._shard = 0;\n\n this._realm = 0;\n\n if (props != null && props.scheduleNetworkUpdate !== false) {\n this._scheduleNetworkUpdate();\n }\n\n if (props != null && props.shard != null) {\n this._shard = props.shard;\n }\n\n if (props != null && props.realm != null) {\n this._realm = props.realm;\n }\n\n /** @internal */\n /** @type {NodeJS.Timeout} */\n this._timer;\n\n /**\n * Logger\n *\n * @external\n * @type {Logger | null}\n */\n this._logger = null;\n }\n\n /**\n * @deprecated\n * @param {NetworkName} networkName\n * @returns {this}\n */\n setNetworkName(networkName) {\n // uses custom NetworkName type\n // remove if phasing out set|get NetworkName\n console.warn(\"Deprecated: Use `setLedgerId` instead\");\n return this.setLedgerId(networkName);\n }\n\n /**\n * @deprecated\n * @returns {string | null}\n */\n get networkName() {\n console.warn(\"Deprecated: Use `ledgerId` instead\");\n return this.ledgerId != null ? this.ledgerId.toString() : null;\n }\n\n /**\n * @param {string|LedgerId} ledgerId\n * @returns {this}\n */\n setLedgerId(ledgerId) {\n this._network.setLedgerId(\n typeof ledgerId === \"string\"\n ? LedgerId.fromString(ledgerId)\n : ledgerId,\n );\n\n return this;\n }\n\n /**\n * @returns {LedgerId | null}\n */\n get ledgerId() {\n return this._network._ledgerId != null ? this._network.ledgerId : null;\n }\n\n /**\n * @param {{[key: string]: (string | AccountId)} | string} network\n * @returns {void}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setNetwork(network) {\n // TODO: This logic _can_ be de-duplicated and likely should\n throw new Error(\"not implemented\");\n }\n\n /**\n * @param {NodeAddressBook} addressBook\n * @returns {this}\n */\n setNetworkFromAddressBook(addressBook) {\n this._network.setNetworkFromAddressBook(addressBook);\n return this;\n }\n\n /**\n * @returns {{[key: string]: (string | AccountId)}}\n */\n get network() {\n return this._network.network;\n }\n\n /**\n * @returns {number}\n */\n get shard() {\n return this._shard;\n }\n\n /**\n * @returns {number}\n */\n get realm() {\n return this._realm;\n }\n\n /**\n * @param {string[] | string} mirrorNetwork\n * @returns {void}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setMirrorNetwork(mirrorNetwork) {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @returns {string[]}\n */\n get mirrorNetwork() {\n return this._mirrorNetwork.network;\n }\n\n /**\n * @returns {boolean}\n */\n get signOnDemand() {\n return this._signOnDemand;\n }\n\n /**\n * @param {boolean} signOnDemand\n */\n setSignOnDemand(signOnDemand) {\n this._signOnDemand = signOnDemand;\n }\n\n /**\n * @returns {boolean}\n */\n isTransportSecurity() {\n return this._network.isTransportSecurity();\n }\n\n /**\n * @param {boolean} transportSecurity\n * @returns {this}\n */\n setTransportSecurity(transportSecurity) {\n this._network.setTransportSecurity(transportSecurity);\n return this;\n }\n\n /**\n * Set the account that will, by default, pay for transactions and queries built with this client.\n * NOTE: When using string for private key, the string needs to contain DER headers\n *\n * @param {AccountId | string} accountId\n * @param {PrivateKey | string} privateKey\n * @returns {this}\n */\n setOperator(accountId, privateKey) {\n const key =\n typeof privateKey === \"string\"\n ? PrivateKey.fromStringDer(privateKey)\n : privateKey;\n\n return this.setOperatorWith(accountId, key.publicKey, (message) =>\n Promise.resolve(key.sign(message)),\n );\n }\n\n /**\n * @returns {?ClientOperator}\n */\n getOperator() {\n return this._operator;\n }\n\n /**\n * Sets the account that will, by default, pay for transactions and queries built with\n * this client.\n *\n * @param {AccountId | string} accountId\n * @param {PublicKey | string} publicKey\n * @param {(message: Uint8Array) => Promise<Uint8Array>} transactionSigner\n * @returns {this}\n */\n setOperatorWith(accountId, publicKey, transactionSigner) {\n const accountId_ =\n accountId instanceof AccountId\n ? accountId\n : AccountId.fromString(accountId);\n\n if (this._network._ledgerId != null) {\n accountId_.validateChecksum(this);\n }\n\n this._operator = {\n transactionSigner,\n\n accountId: accountId_,\n\n publicKey:\n publicKey instanceof PublicKey\n ? publicKey\n : PublicKey.fromString(publicKey),\n };\n\n return this;\n }\n\n /**\n * @param {boolean} value\n * @returns {this}\n */\n setAutoValidateChecksums(value) {\n this._autoValidateChecksums = value;\n return this;\n }\n\n /**\n * @returns {boolean}\n */\n isAutoValidateChecksumsEnabled() {\n return this._autoValidateChecksums;\n }\n\n /**\n * @returns {?AccountId}\n */\n get operatorAccountId() {\n return this._operator != null ? this._operator.accountId : null;\n }\n\n /**\n * @returns {?PublicKey}\n */\n get operatorPublicKey() {\n return this._operator != null ? this._operator.publicKey : null;\n }\n\n /**\n * @returns {?Hbar}\n */\n get defaultMaxTransactionFee() {\n return this._defaultMaxTransactionFee;\n }\n\n /**\n * @deprecated - Use `defaultMaxTransactionFee` instead\n * @returns {?Hbar}\n */\n get maxTransactionFee() {\n return this.defaultMaxTransactionFee;\n }\n\n /**\n * Set the defaultimum fee to be paid for transactions\n * executed by this client.\n *\n * @param {Hbar} defaultMaxTransactionFee\n * @returns {this}\n */\n setDefaultMaxTransactionFee(defaultMaxTransactionFee) {\n if (defaultMaxTransactionFee.toTinybars().toInt() < 0) {\n throw new Error(\"defaultMaxTransactionFee must be non-negative\");\n }\n this._defaultMaxTransactionFee = defaultMaxTransactionFee;\n return this;\n }\n\n /**\n * @deprecated - Use `setDefaultMaxTransactionFee()` instead\n * Set the maximum fee to be paid for transactions\n * executed by this client.\n * @param {Hbar} maxTransactionFee\n * @returns {this}\n */\n setMaxTransactionFee(maxTransactionFee) {\n return this.setDefaultMaxTransactionFee(maxTransactionFee);\n }\n\n /**\n * @returns {boolean}\n */\n get defaultRegenerateTransactionId() {\n return this._defaultRegenerateTransactionId;\n }\n\n /**\n * Set if a new transaction ID should be generated when a `TRANSACTION_EXPIRED` status\n * is returned.\n *\n * @param {boolean} defaultRegenerateTransactionId\n * @returns {this}\n */\n setDefaultRegenerateTransactionId(defaultRegenerateTransactionId) {\n this._defaultRegenerateTransactionId = defaultRegenerateTransactionId;\n return this;\n }\n\n /**\n * @returns {Hbar}\n */\n get defaultMaxQueryPayment() {\n return this._defaultMaxQueryPayment;\n }\n\n /**\n * @deprecated in a favor of defaultMaxQueryPayment\n * @returns {Hbar}\n */\n get maxQueryPayment() {\n return this.defaultMaxQueryPayment;\n }\n\n /**\n * Set the maximum payment allowable for queries.\n *\n * @param {Hbar} defaultMaxQueryPayment\n * @returns {Client<ChannelT, MirrorChannelT>}\n */\n setDefaultMaxQueryPayment(defaultMaxQueryPayment) {\n const isMaxQueryPaymentNegative =\n convertToNumber(defaultMaxQueryPayment.toTinybars()) < 0;\n if (isMaxQueryPaymentNegative) {\n throw new Error(\"defaultMaxQueryPayment must be non-negative\");\n }\n this._defaultMaxQueryPayment = defaultMaxQueryPayment;\n return this;\n }\n /**\n * @deprecated in a favor of setDefaultMaxQueryPayment()\n * Set the maximum payment allowable for queries.\n * @param {Hbar} maxQueryPayment\n * @returns {Client<ChannelT, MirrorChannelT>}\n */\n setMaxQueryPayment(maxQueryPayment) {\n return this.setDefaultMaxQueryPayment(maxQueryPayment);\n }\n\n /**\n * @returns {number}\n */\n get maxAttempts() {\n return this._maxAttempts != null ? this._maxAttempts : 10;\n }\n\n /**\n * @param {number} maxAttempts\n * @returns {this}\n */\n setMaxAttempts(maxAttempts) {\n this._maxAttempts = maxAttempts;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxNodeAttempts() {\n return this._network.maxNodeAttempts;\n }\n\n /**\n * @param {number} maxNodeAttempts\n * @returns {this}\n */\n setMaxNodeAttempts(maxNodeAttempts) {\n this._network.setMaxNodeAttempts(maxNodeAttempts);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeWaitTime() {\n return this._network.minBackoff;\n }\n\n /**\n * @param {number} nodeWaitTime\n * @returns {this}\n */\n setNodeWaitTime(nodeWaitTime) {\n this._network.setMinBackoff(nodeWaitTime);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxNodesPerTransaction() {\n return this._network.maxNodesPerTransaction;\n }\n\n /**\n * @param {number} maxNodesPerTransaction\n * @returns {this}\n */\n setMaxNodesPerTransaction(maxNodesPerTransaction) {\n this._network.setMaxNodesPerTransaction(maxNodesPerTransaction);\n return this;\n }\n\n /**\n * @param {?number} minBackoff\n * @returns {this}\n */\n setMinBackoff(minBackoff) {\n if (minBackoff == null) {\n throw new Error(\"minBackoff cannot be null.\");\n }\n if (minBackoff > this._maxBackoff) {\n throw new Error(\"minBackoff cannot be larger than maxBackoff.\");\n }\n this._minBackoff = minBackoff;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get minBackoff() {\n return this._minBackoff;\n }\n\n /**\n * @param {?number} maxBackoff\n * @returns {this}\n */\n setMaxBackoff(maxBackoff) {\n if (maxBackoff == null) {\n throw new Error(\"maxBackoff cannot be null.\");\n } else if (maxBackoff < this._minBackoff) {\n throw new Error(\"maxBackoff cannot be smaller than minBackoff.\");\n }\n this._maxBackoff = maxBackoff;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxBackoff() {\n return this._maxBackoff;\n }\n\n /**\n * @param {number} nodeMinBackoff\n * @returns {this}\n */\n setNodeMinBackoff(nodeMinBackoff) {\n this._network.setMinBackoff(nodeMinBackoff);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMinBackoff() {\n return this._network.minBackoff;\n }\n\n /**\n * @param {number} nodeMaxBackoff\n * @returns {this}\n */\n setNodeMaxBackoff(nodeMaxBackoff) {\n this._network.setMaxBackoff(nodeMaxBackoff);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMaxBackoff() {\n return this._network.maxBackoff;\n }\n\n /**\n * @param {number} nodeMinReadmitPeriod\n * @returns {this}\n */\n setNodeMinReadmitPeriod(nodeMinReadmitPeriod) {\n this._network.setNodeMinReadmitPeriod(nodeMinReadmitPeriod);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMinReadmitPeriod() {\n return this._network.nodeMinReadmitPeriod;\n }\n\n /**\n * @param {number} nodeMaxReadmitPeriod\n * @returns {this}\n */\n setNodeMaxReadmitPeriod(nodeMaxReadmitPeriod) {\n this._network.setNodeMaxReadmitPeriod(nodeMaxReadmitPeriod);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMaxReadmitPeriod() {\n return this._network.nodeMaxReadmitPeriod;\n }\n\n /**\n * @param {number} requestTimeout - Number of milliseconds\n * @returns {this}\n */\n setRequestTimeout(requestTimeout) {\n this._requestTimeout = requestTimeout;\n return this;\n }\n\n /**\n * @returns {?number}\n */\n get requestTimeout() {\n return this._requestTimeout;\n }\n\n /**\n * @returns {number}\n */\n get networkUpdatePeriod() {\n return this._networkUpdatePeriod;\n }\n\n /**\n * @param {number} networkUpdatePeriod\n * @returns {this}\n */\n setNetworkUpdatePeriod(networkUpdatePeriod) {\n clearTimeout(this._timer);\n this._networkUpdatePeriod = networkUpdatePeriod;\n this._scheduleNetworkUpdate();\n return this;\n }\n /**\n * Set logger\n *\n * @param {Logger} logger\n * @returns {this}\n */\n setLogger(logger) {\n this._logger = logger;\n return this;\n }\n\n /**\n * Get logger if set\n *\n * @returns {?Logger}\n */\n get logger() {\n return this._logger;\n }\n\n /**\n * @param {AccountId | string} accountId\n */\n async ping(accountId) {\n await new AccountBalanceQuery({ accountId })\n .setNodeAccountIds([\n accountId instanceof AccountId\n ? accountId\n : AccountId.fromString(accountId),\n ])\n .execute(this);\n }\n\n async pingAll() {\n for (const nodeAccountId of Object.values(this._network.network)) {\n await this.ping(nodeAccountId);\n }\n }\n\n /**\n * Update the network address book.\n * @returns {Promise<this>}\n */\n async updateNetwork() {\n if (this._isUpdatingNetwork) {\n return this;\n }\n\n this._isUpdatingNetwork = true;\n\n try {\n const addressBook = await new AddressBookQuery()\n .setFileId(\n FileId.getAddressBookFileIdFor(this._shard, this._realm),\n )\n .execute(this);\n this.setNetworkFromAddressBook(addressBook);\n } catch (error) {\n if (this._logger) {\n this._logger.trace(\n `failed to update client address book: ${\n /** @type {Error} */ (error).toString()\n }`,\n );\n }\n } finally {\n this._isUpdatingNetwork = false;\n }\n\n return this;\n }\n\n /**\n * @returns {void}\n */\n close() {\n this._network.close();\n this._mirrorNetwork.close();\n this._isShutdown = true;\n clearTimeout(this._timer);\n }\n\n /**\n * @abstract\n * @returns {(address: string) => ChannelT}\n */\n _createNetworkChannel() {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @abstract\n * @returns {(address: string) => MirrorChannelT}\n */\n _createMirrorNetworkChannel() {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @private\n */\n _scheduleNetworkUpdate() {\n // This is the automatic network update promise that _eventually_ completes\n // eslint-disable-next-line @typescript-eslint/no-floating-promises,@typescript-eslint/no-misused-promises\n this._timer = setTimeout(async () => {\n await this.updateNetwork();\n\n if (!this._isShutdown) {\n // Recall this method to continuously update the network\n // every `networkUpdatePeriod` amount of itme\n this._scheduleNetworkUpdate();\n }\n }, this._networkUpdatePeriod);\n }\n\n /**\n * @returns {boolean}\n */\n get isClientShutDown() {\n return this._isShutdown;\n }\n\n /**\n * Validates that all nodes in a network are in the same shard and realm.\n *\n * @param {{[key: string]: (string | AccountId)}} network\n */\n static _validateNetworkConsistency(network) {\n if (Object.keys(network).length === 0) {\n return;\n }\n\n const [, nodeAccountId] = Object.entries(network)[0];\n\n const accountIdStr = nodeAccountId.toString();\n\n const [firstNodeShard, firstNodeRealm] = accountIdStr\n .split(\".\")\n .map(Number);\n\n const isNetworkValid = Object.values(network).every((accountId) => {\n const accountIdStr = accountId.toString();\n\n const [currentShard, currentRealm] = accountIdStr\n .split(\".\")\n .map(Number);\n return (\n currentShard === firstNodeShard &&\n currentRealm === firstNodeRealm\n );\n });\n\n if (!isNetworkValid) {\n throw new Error(\n \"Network is not valid, all nodes must be in the same shard and realm\",\n );\n }\n }\n\n /**\n * Extracts shard and realm values from a network configuration.\n * Note: This method assumes the network is consistent (all nodes in same shard/realm).\n * Use validateNetworkConsistency() first to ensure this.\n *\n * @param {{[key: string]: (string | AccountId)}} network\n * @returns {{shard: number, realm: number}}\n */\n static _extractShardRealm(network) {\n const entries = Object.entries(network);\n if (entries.length === 0) {\n return { shard: 0, realm: 0 };\n }\n\n const [, firstNodeAccountId] = entries[0];\n\n const accountIdStr = firstNodeAccountId.toString();\n const [shard, realm] = accountIdStr.split(\".\").map(Number);\n\n return { shard, realm };\n }\n}\n"],"names":["Client","constructor","props","this","_mirrorNetwork","MirrorNetwork","_createMirrorNetworkChannel","_network","Network","_createNetworkChannel","_operator","_defaultMaxTransactionFee","_defaultMaxQueryPayment","Hbar","operator","setOperator","accountId","privateKey","_maxAttempts","_signOnDemand","_autoValidateChecksums","_minBackoff","_maxBackoff","_defaultRegenerateTransactionId","_requestTimeout","_isUpdatingNetwork","_networkUpdatePeriod","_isShutdown","_shard","_realm","scheduleNetworkUpdate","_scheduleNetworkUpdate","shard","realm","_timer","_logger","setNetworkName","networkName","console","warn","setLedgerId","ledgerId","toString","LedgerId","fromString","_ledgerId","setNetwork","network","Error","setNetworkFromAddressBook","addressBook","setMirrorNetwork","mirrorNetwork","signOnDemand","setSignOnDemand","isTransportSecurity","setTransportSecurity","transportSecurity","key","PrivateKey","fromStringDer","setOperatorWith","publicKey","message","Promise","resolve","sign","getOperator","transactionSigner","accountId_","AccountId","validateChecksum","PublicKey","setAutoValidateChecksums","value","isAutoValidateChecksumsEnabled","operatorAccountId","operatorPublicKey","defaultMaxTransactionFee","maxTransactionFee","setDefaultMaxTransactionFee","toTinybars","toInt","setMaxTransactionFee","defaultRegenerateTransactionId","setDefaultRegenerateTransactionId","defaultMaxQueryPayment","maxQueryPayment","setDefaultMaxQueryPayment","convertToNumber","setMaxQueryPayment","maxAttempts","setMaxAttempts","maxNodeAttempts","setMaxNodeAttempts","nodeWaitTime","minBackoff","setNodeWaitTime","setMinBackoff","maxNodesPerTransaction","setMaxNodesPerTransaction","setMaxBackoff","maxBackoff","setNodeMinBackoff","nodeMinBackoff","setNodeMaxBackoff","nodeMaxBackoff","setNodeMinReadmitPeriod","nodeMinReadmitPeriod","setNodeMaxReadmitPeriod","nodeMaxReadmitPeriod","setRequestTimeout","requestTimeout","networkUpdatePeriod","setNetworkUpdatePeriod","clearTimeout","setLogger","logger","ping","AccountBalanceQuery","setNodeAccountIds","execute","pingAll","nodeAccountId","Object","values","updateNetwork","AddressBookQuery","setFileId","FileId","getAddressBookFileIdFor","error","trace","close","setTimeout","async","isClientShutDown","_validateNetworkConsistency","keys","length","entries","accountIdStr","firstNodeShard","firstNodeRealm","split","map","Number","isNetworkValid","every","currentShard","currentRealm","_extractShardRealm","firstNodeAccountId"],"mappings":"obAyDe,MAAMA,EAMjB,WAAAC,CAAYC,GAORC,KAAKC,eAAiB,IAAIC,EACtBF,KAAKG,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QAEHC,EAAiBvB,OAAOC,OAAO9E,GAASqG,MAAOpI,IACjD,MAAM6H,EAAe7H,EAAU0B,YAExB2G,EAAcC,GAAgBT,EAChCG,MAAM,KACNC,IAAIC,QACT,OACIG,IAAiBP,GACjBQ,IAAiBP,IAIzB,IAAKI,EACD,MAAM,IAAInG,MACN,sEAGhB,CAUI,yBAAOuG,CAAmBxG,GACtB,MAAM6F,EAAUhB,OAAOgB,QAAQ7F,GAC/B,GAAuB,IAAnB6F,EAAQD,OACR,MAAO,CAAE3G,MAAO,EAAGC,MAAO,GAG9B,OAASuH,GAAsBZ,EAAQ,GAEjCC,EAAeW,EAAmB9G,YACjCV,EAAOC,GAAS4G,EAAaG,MAAM,KAAKC,IAAIC,QAEnD,MAAO,CAAElH,QAAOC,QACxB"}
|
|
1
|
+
{"version":3,"file":"Client.js","sources":["../../src/client/Client.js"],"sourcesContent":["// SPDX-License-Identifier: Apache-2.0\n\nimport AccountId from \"../account/AccountId.js\";\nimport AccountBalanceQuery from \"../account/AccountBalanceQuery.js\";\nimport Hbar from \"../Hbar.js\";\nimport Network from \"./Network.js\";\nimport MirrorNetwork from \"./MirrorNetwork.js\";\nimport PublicKey from \"../PublicKey.js\";\nimport PrivateKey from \"../PrivateKey.js\";\nimport LedgerId from \"../LedgerId.js\";\nimport FileId from \"../file/FileId.js\";\nimport Logger from \"../logger/Logger.js\"; // eslint-disable-line\nimport { convertToNumber } from \"../util.js\";\nimport AddressBookQuery from \"../network/AddressBookQuery.js\";\n\n/**\n * @typedef {import(\"../channel/Channel.js\").default} Channel\n * @typedef {import(\"../channel/MirrorChannel.js\").default} MirrorChannel\n * @typedef {import(\"../address_book/NodeAddressBook.js\").default} NodeAddressBook\n */\n\n/**\n * @typedef {object} Operator\n * @property {string | PrivateKey} privateKey\n * @property {string | AccountId} accountId\n */\n\n/**\n * @typedef {object} ClientOperator\n * @property {PublicKey} publicKey\n * @property {AccountId} accountId\n * @property {(message: Uint8Array) => Promise<Uint8Array>} transactionSigner\n */\n\n/**\n * @typedef {object} ClientConfiguration\n * @property {{[key: string]: (string | AccountId)} | string} [network]\n * @property {string[] | string} [mirrorNetwork]\n * @property {Operator} [operator]\n * @property {boolean} [scheduleNetworkUpdate]\n * @property {number} [shard]\n * @property {number} [realm]\n */\n\n/**\n * @typedef {\"mainnet\" | \"testnet\" | \"previewnet\"} NetworkName\n */\n\n/**\n * The `Client` class is the main entry point for interacting with the Hedera Hashgraph network.\n * It provides methods for managing network connections, setting operators, handling transactions\n * and queries, and configuring various client settings.\n *\n * @abstract\n * @template {Channel} ChannelT\n * @template {MirrorChannel} MirrorChannelT\n */\nexport default class Client {\n /**\n * @protected\n * @hideconstructor\n * @param {ClientConfiguration} [props]\n */\n constructor(props) {\n /**\n * List of mirror network URLs.\n *\n * @internal\n * @type {MirrorNetwork}\n */\n this._mirrorNetwork = new MirrorNetwork(\n this._createMirrorNetworkChannel(),\n );\n\n /**\n * Map of node account ID (as a string)\n * to the node URL.\n *\n * @internal\n * @type {Network}\n */\n this._network = new Network(this._createNetworkChannel());\n\n /**\n * @internal\n * @type {?ClientOperator}\n */\n this._operator = null;\n\n /**\n * @private\n * @type {?Hbar}\n */\n this._defaultMaxTransactionFee = null;\n\n /**\n * @private\n * @type {Hbar}\n */\n this._defaultMaxQueryPayment = new Hbar(1);\n\n if (props != null) {\n if (props.operator != null) {\n this.setOperator(\n props.operator.accountId,\n props.operator.privateKey,\n );\n }\n }\n\n /** @type {number | null} */\n this._maxAttempts = null;\n\n /** @private */\n this._signOnDemand = false;\n\n /** @private */\n this._autoValidateChecksums = false;\n\n /** @private */\n this._minBackoff = 250;\n\n /** @private */\n this._maxBackoff = 8000;\n\n /** @private */\n this._defaultRegenerateTransactionId = true;\n\n /** @private */\n this._requestTimeout = null;\n\n /**\n * @type {boolean}\n */\n this._isUpdatingNetwork = false;\n\n /** @private */\n this._networkUpdatePeriod = 24 * 60 * 60 * 1000;\n\n /** @private */\n this._isShutdown = false;\n\n this._shard = 0;\n\n this._realm = 0;\n\n if (props != null && props.scheduleNetworkUpdate !== false) {\n this._scheduleNetworkUpdate();\n }\n\n if (props != null && props.shard != null) {\n this._shard = props.shard;\n }\n\n if (props != null && props.realm != null) {\n this._realm = props.realm;\n }\n\n /** @internal */\n /** @type {NodeJS.Timeout} */\n this._timer;\n\n /**\n * Logger\n *\n * @external\n * @type {Logger | null}\n */\n this._logger = null;\n }\n\n /**\n * @deprecated\n * @param {NetworkName} networkName\n * @returns {this}\n */\n setNetworkName(networkName) {\n // uses custom NetworkName type\n // remove if phasing out set|get NetworkName\n console.warn(\"Deprecated: Use `setLedgerId` instead\");\n return this.setLedgerId(networkName);\n }\n\n /**\n * @deprecated\n * @returns {string | null}\n */\n get networkName() {\n console.warn(\"Deprecated: Use `ledgerId` instead\");\n return this.ledgerId != null ? this.ledgerId.toString() : null;\n }\n\n /**\n * @param {string|LedgerId} ledgerId\n * @returns {this}\n */\n setLedgerId(ledgerId) {\n this._network.setLedgerId(\n typeof ledgerId === \"string\"\n ? LedgerId.fromString(ledgerId)\n : ledgerId,\n );\n\n return this;\n }\n\n /**\n * @returns {LedgerId | null}\n */\n get ledgerId() {\n return this._network._ledgerId != null ? this._network.ledgerId : null;\n }\n\n /**\n * @param {{[key: string]: (string | AccountId)} | string} network\n * @returns {void}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setNetwork(network) {\n // TODO: This logic _can_ be de-duplicated and likely should\n throw new Error(\"not implemented\");\n }\n\n /**\n * @param {NodeAddressBook} addressBook\n * @returns {this}\n */\n setNetworkFromAddressBook(addressBook) {\n this._network.setNetworkFromAddressBook(addressBook);\n return this;\n }\n\n /**\n * @returns {{[key: string]: (string | AccountId)}}\n */\n get network() {\n return this._network.network;\n }\n\n /**\n * @returns {number}\n */\n get shard() {\n return this._shard;\n }\n\n /**\n * @returns {number}\n */\n get realm() {\n return this._realm;\n }\n\n /**\n * @param {string[] | string} mirrorNetwork\n * @returns {void}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setMirrorNetwork(mirrorNetwork) {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @returns {string[]}\n */\n get mirrorNetwork() {\n return this._mirrorNetwork.network;\n }\n\n /**\n * @returns {string}\n * @throws {Error} When no mirror network is configured or available\n */\n get mirrorRestApiBaseUrl() {\n try {\n const mirrorNode = this._mirrorNetwork.getNextMirrorNode();\n const host = mirrorNode.address.address;\n const port = mirrorNode.address.port;\n\n if (!host || !port) {\n throw new Error(\n \"Mirror node has invalid address configuration\",\n );\n }\n\n const scheme = this._getSchemeFromHostAndPort(host, port);\n\n return `${scheme}://${host}:${port}/api/v1`;\n } catch (error) {\n // Re-throw with a more descriptive error message\n throw new Error(\n \"Client has no mirror network configured or no healthy mirror nodes are available\",\n );\n }\n }\n\n /**\n * @returns {boolean}\n */\n get signOnDemand() {\n return this._signOnDemand;\n }\n\n /**\n * @param {boolean} signOnDemand\n */\n setSignOnDemand(signOnDemand) {\n this._signOnDemand = signOnDemand;\n }\n\n /**\n * @returns {boolean}\n */\n isTransportSecurity() {\n return this._network.isTransportSecurity();\n }\n\n /**\n * @param {boolean} transportSecurity\n * @returns {this}\n */\n setTransportSecurity(transportSecurity) {\n this._network.setTransportSecurity(transportSecurity);\n return this;\n }\n\n /**\n * Set the account that will, by default, pay for transactions and queries built with this client.\n * NOTE: When using string for private key, the string needs to contain DER headers\n *\n * @param {AccountId | string} accountId\n * @param {PrivateKey | string} privateKey\n * @returns {this}\n */\n setOperator(accountId, privateKey) {\n const key =\n typeof privateKey === \"string\"\n ? PrivateKey.fromStringDer(privateKey)\n : privateKey;\n\n return this.setOperatorWith(accountId, key.publicKey, (message) =>\n Promise.resolve(key.sign(message)),\n );\n }\n\n /**\n * @returns {?ClientOperator}\n */\n getOperator() {\n return this._operator;\n }\n\n /**\n * Sets the account that will, by default, pay for transactions and queries built with\n * this client.\n *\n * @param {AccountId | string} accountId\n * @param {PublicKey | string} publicKey\n * @param {(message: Uint8Array) => Promise<Uint8Array>} transactionSigner\n * @returns {this}\n */\n setOperatorWith(accountId, publicKey, transactionSigner) {\n const accountId_ =\n accountId instanceof AccountId\n ? accountId\n : AccountId.fromString(accountId);\n\n if (this._network._ledgerId != null) {\n accountId_.validateChecksum(this);\n }\n\n this._operator = {\n transactionSigner,\n\n accountId: accountId_,\n\n publicKey:\n publicKey instanceof PublicKey\n ? publicKey\n : PublicKey.fromString(publicKey),\n };\n\n return this;\n }\n\n /**\n * @param {boolean} value\n * @returns {this}\n */\n setAutoValidateChecksums(value) {\n this._autoValidateChecksums = value;\n return this;\n }\n\n /**\n * @returns {boolean}\n */\n isAutoValidateChecksumsEnabled() {\n return this._autoValidateChecksums;\n }\n\n /**\n * @returns {?AccountId}\n */\n get operatorAccountId() {\n return this._operator != null ? this._operator.accountId : null;\n }\n\n /**\n * @returns {?PublicKey}\n */\n get operatorPublicKey() {\n return this._operator != null ? this._operator.publicKey : null;\n }\n\n /**\n * @returns {?Hbar}\n */\n get defaultMaxTransactionFee() {\n return this._defaultMaxTransactionFee;\n }\n\n /**\n * @deprecated - Use `defaultMaxTransactionFee` instead\n * @returns {?Hbar}\n */\n get maxTransactionFee() {\n return this.defaultMaxTransactionFee;\n }\n\n /**\n * Set the defaultimum fee to be paid for transactions\n * executed by this client.\n *\n * @param {Hbar} defaultMaxTransactionFee\n * @returns {this}\n */\n setDefaultMaxTransactionFee(defaultMaxTransactionFee) {\n if (defaultMaxTransactionFee.toTinybars().toInt() < 0) {\n throw new Error(\"defaultMaxTransactionFee must be non-negative\");\n }\n this._defaultMaxTransactionFee = defaultMaxTransactionFee;\n return this;\n }\n\n /**\n * @deprecated - Use `setDefaultMaxTransactionFee()` instead\n * Set the maximum fee to be paid for transactions\n * executed by this client.\n * @param {Hbar} maxTransactionFee\n * @returns {this}\n */\n setMaxTransactionFee(maxTransactionFee) {\n return this.setDefaultMaxTransactionFee(maxTransactionFee);\n }\n\n /**\n * @returns {boolean}\n */\n get defaultRegenerateTransactionId() {\n return this._defaultRegenerateTransactionId;\n }\n\n /**\n * Set if a new transaction ID should be generated when a `TRANSACTION_EXPIRED` status\n * is returned.\n *\n * @param {boolean} defaultRegenerateTransactionId\n * @returns {this}\n */\n setDefaultRegenerateTransactionId(defaultRegenerateTransactionId) {\n this._defaultRegenerateTransactionId = defaultRegenerateTransactionId;\n return this;\n }\n\n /**\n * @returns {Hbar}\n */\n get defaultMaxQueryPayment() {\n return this._defaultMaxQueryPayment;\n }\n\n /**\n * @deprecated in a favor of defaultMaxQueryPayment\n * @returns {Hbar}\n */\n get maxQueryPayment() {\n return this.defaultMaxQueryPayment;\n }\n\n /**\n * Set the maximum payment allowable for queries.\n *\n * @param {Hbar} defaultMaxQueryPayment\n * @returns {Client<ChannelT, MirrorChannelT>}\n */\n setDefaultMaxQueryPayment(defaultMaxQueryPayment) {\n const isMaxQueryPaymentNegative =\n convertToNumber(defaultMaxQueryPayment.toTinybars()) < 0;\n if (isMaxQueryPaymentNegative) {\n throw new Error(\"defaultMaxQueryPayment must be non-negative\");\n }\n this._defaultMaxQueryPayment = defaultMaxQueryPayment;\n return this;\n }\n /**\n * @deprecated in a favor of setDefaultMaxQueryPayment()\n * Set the maximum payment allowable for queries.\n * @param {Hbar} maxQueryPayment\n * @returns {Client<ChannelT, MirrorChannelT>}\n */\n setMaxQueryPayment(maxQueryPayment) {\n return this.setDefaultMaxQueryPayment(maxQueryPayment);\n }\n\n /**\n * @returns {number}\n */\n get maxAttempts() {\n return this._maxAttempts != null ? this._maxAttempts : 10;\n }\n\n /**\n * @param {number} maxAttempts\n * @returns {this}\n */\n setMaxAttempts(maxAttempts) {\n this._maxAttempts = maxAttempts;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxNodeAttempts() {\n return this._network.maxNodeAttempts;\n }\n\n /**\n * @param {number} maxNodeAttempts\n * @returns {this}\n */\n setMaxNodeAttempts(maxNodeAttempts) {\n this._network.setMaxNodeAttempts(maxNodeAttempts);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeWaitTime() {\n return this._network.minBackoff;\n }\n\n /**\n * @param {number} nodeWaitTime\n * @returns {this}\n */\n setNodeWaitTime(nodeWaitTime) {\n this._network.setMinBackoff(nodeWaitTime);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxNodesPerTransaction() {\n return this._network.maxNodesPerTransaction;\n }\n\n /**\n * @param {number} maxNodesPerTransaction\n * @returns {this}\n */\n setMaxNodesPerTransaction(maxNodesPerTransaction) {\n this._network.setMaxNodesPerTransaction(maxNodesPerTransaction);\n return this;\n }\n\n /**\n * @param {?number} minBackoff\n * @returns {this}\n */\n setMinBackoff(minBackoff) {\n if (minBackoff == null) {\n throw new Error(\"minBackoff cannot be null.\");\n }\n if (minBackoff > this._maxBackoff) {\n throw new Error(\"minBackoff cannot be larger than maxBackoff.\");\n }\n this._minBackoff = minBackoff;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get minBackoff() {\n return this._minBackoff;\n }\n\n /**\n * @param {?number} maxBackoff\n * @returns {this}\n */\n setMaxBackoff(maxBackoff) {\n if (maxBackoff == null) {\n throw new Error(\"maxBackoff cannot be null.\");\n } else if (maxBackoff < this._minBackoff) {\n throw new Error(\"maxBackoff cannot be smaller than minBackoff.\");\n }\n this._maxBackoff = maxBackoff;\n return this;\n }\n\n /**\n * @returns {number}\n */\n get maxBackoff() {\n return this._maxBackoff;\n }\n\n /**\n * @param {number} nodeMinBackoff\n * @returns {this}\n */\n setNodeMinBackoff(nodeMinBackoff) {\n this._network.setMinBackoff(nodeMinBackoff);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMinBackoff() {\n return this._network.minBackoff;\n }\n\n /**\n * @param {number} nodeMaxBackoff\n * @returns {this}\n */\n setNodeMaxBackoff(nodeMaxBackoff) {\n this._network.setMaxBackoff(nodeMaxBackoff);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMaxBackoff() {\n return this._network.maxBackoff;\n }\n\n /**\n * @param {number} nodeMinReadmitPeriod\n * @returns {this}\n */\n setNodeMinReadmitPeriod(nodeMinReadmitPeriod) {\n this._network.setNodeMinReadmitPeriod(nodeMinReadmitPeriod);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMinReadmitPeriod() {\n return this._network.nodeMinReadmitPeriod;\n }\n\n /**\n * @param {number} nodeMaxReadmitPeriod\n * @returns {this}\n */\n setNodeMaxReadmitPeriod(nodeMaxReadmitPeriod) {\n this._network.setNodeMaxReadmitPeriod(nodeMaxReadmitPeriod);\n return this;\n }\n\n /**\n * @returns {number}\n */\n get nodeMaxReadmitPeriod() {\n return this._network.nodeMaxReadmitPeriod;\n }\n\n /**\n * @param {number} requestTimeout - Number of milliseconds\n * @returns {this}\n */\n setRequestTimeout(requestTimeout) {\n this._requestTimeout = requestTimeout;\n return this;\n }\n\n /**\n * @returns {?number}\n */\n get requestTimeout() {\n return this._requestTimeout;\n }\n\n /**\n * @returns {number}\n */\n get networkUpdatePeriod() {\n return this._networkUpdatePeriod;\n }\n\n /**\n * @param {number} networkUpdatePeriod\n * @returns {this}\n */\n setNetworkUpdatePeriod(networkUpdatePeriod) {\n clearTimeout(this._timer);\n this._networkUpdatePeriod = networkUpdatePeriod;\n this._scheduleNetworkUpdate();\n return this;\n }\n /**\n * Set logger\n *\n * @param {Logger} logger\n * @returns {this}\n */\n setLogger(logger) {\n this._logger = logger;\n return this;\n }\n\n /**\n * Get logger if set\n *\n * @returns {?Logger}\n */\n get logger() {\n return this._logger;\n }\n\n /**\n * @param {AccountId | string} accountId\n */\n async ping(accountId) {\n await new AccountBalanceQuery({ accountId })\n .setNodeAccountIds([\n accountId instanceof AccountId\n ? accountId\n : AccountId.fromString(accountId),\n ])\n .execute(this);\n }\n\n async pingAll() {\n for (const nodeAccountId of Object.values(this._network.network)) {\n await this.ping(nodeAccountId);\n }\n }\n\n /**\n * Update the network address book.\n * @returns {Promise<this>}\n */\n async updateNetwork() {\n if (this._isUpdatingNetwork) {\n return this;\n }\n\n this._isUpdatingNetwork = true;\n\n try {\n const addressBook = await new AddressBookQuery()\n .setFileId(\n FileId.getAddressBookFileIdFor(this._shard, this._realm),\n )\n .execute(this);\n this.setNetworkFromAddressBook(addressBook);\n } catch (error) {\n if (this._logger) {\n this._logger.trace(\n `failed to update client address book: ${\n /** @type {Error} */ (error).toString()\n }`,\n );\n }\n } finally {\n this._isUpdatingNetwork = false;\n }\n\n return this;\n }\n\n /**\n * @returns {void}\n */\n close() {\n this._network.close();\n this._mirrorNetwork.close();\n this._isShutdown = true;\n clearTimeout(this._timer);\n }\n\n /**\n * @abstract\n * @returns {(address: string) => ChannelT}\n */\n _createNetworkChannel() {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @abstract\n * @returns {(address: string) => MirrorChannelT}\n */\n _createMirrorNetworkChannel() {\n throw new Error(\"not implemented\");\n }\n\n /**\n * @private\n */\n _scheduleNetworkUpdate() {\n // This is the automatic network update promise that _eventually_ completes\n // eslint-disable-next-line @typescript-eslint/no-floating-promises,@typescript-eslint/no-misused-promises\n this._timer = setTimeout(async () => {\n await this.updateNetwork();\n\n if (!this._isShutdown) {\n // Recall this method to continuously update the network\n // every `networkUpdatePeriod` amount of itme\n this._scheduleNetworkUpdate();\n }\n }, this._networkUpdatePeriod);\n }\n\n /**\n * Determines the appropriate scheme (http/https) based on the host and port.\n *\n * @private\n * @param {string} host - The host address\n * @param {number} port - The port number\n * @returns {string} - The scheme ('http' or 'https')\n */\n _getSchemeFromHostAndPort(host, port) {\n // For localhost and 127.0.0.1, use HTTP scheme\n if (host === \"localhost\" || host === \"127.0.0.1\") {\n return \"http\";\n }\n\n // Standard HTTPS ports\n if (port === 443) {\n return \"https\";\n }\n\n // Standard HTTP ports\n if (port === 80) {\n return \"http\";\n }\n\n // For other ports, assume HTTPS for security\n return \"https\";\n }\n\n /**\n * @returns {boolean}\n */\n get isClientShutDown() {\n return this._isShutdown;\n }\n\n /**\n * Validates that all nodes in a network are in the same shard and realm.\n *\n * @param {{[key: string]: (string | AccountId)}} network\n */\n static _validateNetworkConsistency(network) {\n if (Object.keys(network).length === 0) {\n return;\n }\n\n const [, nodeAccountId] = Object.entries(network)[0];\n\n const accountIdStr = nodeAccountId.toString();\n\n const [firstNodeShard, firstNodeRealm] = accountIdStr\n .split(\".\")\n .map(Number);\n\n const isNetworkValid = Object.values(network).every((accountId) => {\n const accountIdStr = accountId.toString();\n\n const [currentShard, currentRealm] = accountIdStr\n .split(\".\")\n .map(Number);\n return (\n currentShard === firstNodeShard &&\n currentRealm === firstNodeRealm\n );\n });\n\n if (!isNetworkValid) {\n throw new Error(\n \"Network is not valid, all nodes must be in the same shard and realm\",\n );\n }\n }\n\n /**\n * Extracts shard and realm values from a network configuration.\n * Note: This method assumes the network is consistent (all nodes in same shard/realm).\n * Use validateNetworkConsistency() first to ensure this.\n *\n * @param {{[key: string]: (string | AccountId)}} network\n * @returns {{shard: number, realm: number}}\n */\n static _extractShardRealm(network) {\n const entries = Object.entries(network);\n if (entries.length === 0) {\n return { shard: 0, realm: 0 };\n }\n\n const [, firstNodeAccountId] = entries[0];\n\n const accountIdStr = firstNodeAccountId.toString();\n const [shard, realm] = accountIdStr.split(\".\").map(Number);\n\n return { shard, realm };\n }\n}\n"],"names":["Client","constructor","props","this","_mirrorNetwork","MirrorNetwork","_createMirrorNetworkChannel","_network","Network","_createNetworkChannel","_operator","_defaultMaxTransactionFee","_defaultMaxQueryPayment","Hbar","operator","setOperator","accountId","privateKey","_maxAttempts","_signOnDemand","_autoValidateChecksums","_minBackoff","_maxBackoff","_defaultRegenerateTransactionId","_requestTimeout","_isUpdatingNetwork","_networkUpdatePeriod","_isShutdown","_shard","_realm","scheduleNetworkUpdate","_scheduleNetworkUpdate","shard","realm","_timer","_logger","setNetworkName","networkName","console","warn","setLedgerId","ledgerId","toString","LedgerId","fromString","_ledgerId","setNetwork","network","Error","setNetworkFromAddressBook","addressBook","setMirrorNetwork","mirrorNetwork","mirrorRestApiBaseUrl","mirrorNode","getNextMirrorNode","host","address","port","_getSchemeFromHostAndPort","error","signOnDemand","setSignOnDemand","isTransportSecurity","setTransportSecurity","transportSecurity","key","PrivateKey","fromStringDer","setOperatorWith","publicKey","message","Promise","resolve","sign","getOperator","transactionSigner","accountId_","AccountId","validateChecksum","PublicKey","setAutoValidateChecksums","value","isAutoValidateChecksumsEnabled","operatorAccountId","operatorPublicKey","defaultMaxTransactionFee","maxTransactionFee","setDefaultMaxTransactionFee","toTinybars","toInt","setMaxTransactionFee","defaultRegenerateTransactionId","setDefaultRegenerateTransactionId","defaultMaxQueryPayment","maxQueryPayment","setDefaultMaxQueryPayment","convertToNumber","setMaxQueryPayment","maxAttempts","setMaxAttempts","maxNodeAttempts","setMaxNodeAttempts","nodeWaitTime","minBackoff","setNodeWaitTime","setMinBackoff","maxNodesPerTransaction","setMaxNodesPerTransaction","setMaxBackoff","maxBackoff","setNodeMinBackoff","nodeMinBackoff","setNodeMaxBackoff","nodeMaxBackoff","setNodeMinReadmitPeriod","nodeMinReadmitPeriod","setNodeMaxReadmitPeriod","nodeMaxReadmitPeriod","setRequestTimeout","requestTimeout","networkUpdatePeriod","setNetworkUpdatePeriod","clearTimeout","setLogger","logger","ping","AccountBalanceQuery","setNodeAccountIds","execute","pingAll","nodeAccountId","Object","values","updateNetwork","AddressBookQuery","setFileId","FileId","getAddressBookFileIdFor","trace","close","setTimeout","async","isClientShutDown","_validateNetworkConsistency","keys","length","entries","accountIdStr","firstNodeShard","firstNodeRealm","split","map","Number","isNetworkValid","every","currentShard","currentRealm","_extractShardRealm","firstNodeAccountId"],"mappings":"obAyDe,MAAMA,EAMjB,WAAAC,CAAYC,GAORC,KAAKC,eAAiB,IAAIC,EACtBF,KAAKG,+BAUTH,KAAKI,SAAW,IAAIC,EAAQL,KAAKM,yBAMjCN,KAAKO,UAAY,KAMjBP,KAAKQ,0BAA4B,KAMjCR,KAAKS,wBAA0B,IAAIC,EAAK,GAE3B,MAATX,GACsB,MAAlBA,EAAMY,UACNX,KAAKY,YACDb,EAAMY,SAASE,UACfd,EAAMY,SAASG,YAM3Bd,K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AAhCqF,OAAOa,KAAKlG,GAASmG,OACrB,OAGJ,MAAM,CAAGf,GAAiBC,OAAOe,QAAQpG,GAAS,GAE5CqG,EAAejB,EAAczF,YAE5B2G,EAAgBC,GAAkBF,EACpCG,MAAM,KACNC,IAAIC,QAEHC,EAAiBtB,OAAOC,OAAOtF,GAAS4G,MAAO3I,IACjD,MAAMoI,EAAepI,EAAU0B,YAExBkH,EAAcC,GAAgBT,EAChCG,MAAM,KACNC,IAAIC,QACT,OACIG,IAAiBP,GACjBQ,IAAiBP,IAIzB,IAAKI,EACD,MAAM,IAAI1G,MACN,sEAGhB,CAUI,yBAAO8G,CAAmB/G,GACtB,MAAMoG,EAAUf,OAAOe,QAAQpG,GAC/B,GAAuB,IAAnBoG,EAAQD,OACR,MAAO,CAAElH,MAAO,EAAGC,MAAO,GAG9B,OAAS8H,GAAsBZ,EAAQ,GAEjCC,EAAeW,EAAmBrH,YACjCV,EAAOC,GAASmH,EAAaG,MAAM,KAAKC,IAAIC,QAEnD,MAAO,CAAEzH,QAAOC,QACxB"}
|
|
@@ -219,18 +219,24 @@ class MirrorNodeContractQuery {
|
|
|
219
219
|
throw new Error("Contract ID is not set");
|
|
220
220
|
}
|
|
221
221
|
this._fillEvmAddress();
|
|
222
|
-
let
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
222
|
+
let mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;
|
|
223
|
+
const contractCallEndpointPath = "/contracts/call";
|
|
224
|
+
|
|
225
|
+
// Check if this is a local environment (localhost or 127.0.0.1)
|
|
226
|
+
const mirrorNode = client._mirrorNetwork.getNextMirrorNode();
|
|
227
|
+
const host = mirrorNode.address.address;
|
|
228
|
+
const isLocalEnvironment = host === "localhost" || host === "127.0.0.1";
|
|
229
|
+
if (isLocalEnvironment) {
|
|
230
|
+
// For local environments, use HTTP scheme and port 8545
|
|
231
|
+
const url = new URL(mirrorRestApiBaseUrl);
|
|
232
|
+
url.protocol = "http:";
|
|
233
|
+
url.port = "8545";
|
|
234
|
+
mirrorRestApiBaseUrl = url.toString();
|
|
230
235
|
}
|
|
236
|
+
const contractCallEndpointUrl = `${mirrorRestApiBaseUrl}${contractCallEndpointPath}`;
|
|
231
237
|
|
|
232
238
|
// eslint-disable-next-line n/no-unsupported-features/node-builtins
|
|
233
|
-
const response = await fetch(
|
|
239
|
+
const response = await fetch(contractCallEndpointUrl, {
|
|
234
240
|
method: "POST",
|
|
235
241
|
headers: {
|
|
236
242
|
"Content-Type": "application/json"
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"../contract/ContractFunctionParameters.js";class
|
|
1
|
+
import t from"../contract/ContractFunctionParameters.js";class r{constructor(){this._contractId=null,this._contractEvmAddress=null,this._sender=null,this._senderEvmAddress=null,this._functionName=null,this._functionParameters=null,this._value=null,this._gasLimit=null,this._gasPrice=null,this._blockNumber=null}setContractId(t){return this._contractId=t,this}setSender(t){return this._sender=t,this}setSenderEvmAddress(t){return this._senderEvmAddress=t,this}setFunction(r,e){return this._functionParameters=null!=e?e._build(r):(new t)._build(r),this}setValue(t){return this._value=t,this}setGasLimit(t){return this._gasLimit=t,this}setGasPrice(t){return this._gasPrice=t,this}setBlockNumber(t){return this._blockNumber=t,this}get contractId(){return this._contractId}get contractEvmAddress(){const t=this._contractId?.toEvmAddress();if(null==t)throw new Error("Contract ID is not set");return t}get sender(){return this._sender}get senderEvmAddress(){return this._senderEvmAddress}get callData(){return this._functionParameters}get value(){return this._value}get gasLimit(){return this._gasLimit}get gasPrice(){return this._gasPrice}get blockNumber(){return this._blockNumber}async performMirrorNodeRequest(t,r){if(null==this.contractId)throw new Error("Contract ID is not set");this._fillEvmAddress();let e=t.mirrorRestApiBaseUrl;const s=t._mirrorNetwork.getNextMirrorNode().address.address;if("localhost"===s||"127.0.0.1"===s){const t=new URL(e);t.protocol="http:",t.port="8545",e=t.toString()}const n=`${e}/contracts/call`,i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}_fillEvmAddress(){null==this.senderEvmAddress&&null!=this.sender&&(this._senderEvmAddress=this.sender.toEvmAddress())}get JSONPayload(){throw new Error("JSONPayload getter is not implemented. Please implement this method in the subclass.")}}export{r as default};
|
|
2
2
|
//# sourceMappingURL=MirrorNodeContractQuery.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MirrorNodeContractQuery.js","sources":["../../src/query/MirrorNodeContractQuery.js"],"sourcesContent":["import ContractFunctionParameters from \"../contract/ContractFunctionParameters.js\";\n\n/**\n * @typedef {import(\"../contract/ContractId\").default} ContractId\n * @typedef {import(\"../account/AccountId\").default} AccountId\n * @typedef {import(\"../client/Client.js\").default<*, *>} Client\n *\n */\n\n/**\n * @typedef {object} MirrorNodeResponse\n * @property {string} result\n * @property {string} [error]\n * @property {string} [gasUsed]\n * @property {string} [contractAddress]\n * @property {string} [status]\n */\n\n/**\n * MirrorNodeContractQuery returns a result from EVM execution such as cost-free execution of read-only smart contract\n * queries, gas estimation, and transient simulation of read-write operations.\n * When working with sender that has ECDSA key with alias, you MUST:\n * 1. Retrieve the account's EVM address from the Mirror Node API first\n * 2. Use setSenderEvmAddress() instead of setSender()\n *\n * This is because EVM addresses for accounts with ECDSA keys and aliases cannot be automatically\n * derived and must be fetched from the Mirror Node. Example:\n *\n * ```javascript\n * // For accounts with ECDSA keys and aliases:\n * const evmAddress = // ... fetch from Mirror Node API ...\n * query.setSenderEvmAddress(evmAddress);\n * ```\n */\nexport default class MirrorNodeContractQuery {\n constructor() {\n this._contractId = null;\n this._contractEvmAddress = null;\n this._sender = null;\n this._senderEvmAddress = null;\n this._functionName = null;\n this._functionParameters = null;\n this._value = null;\n this._gasLimit = null;\n this._gasPrice = null;\n this._blockNumber = null;\n }\n\n /**\n *\n * @param {ContractId} contractId\n * @description Sets the contract instance to call.\n * @returns {this}\n */\n setContractId(contractId) {\n this._contractId = contractId;\n return this;\n }\n\n /**\n * @param {AccountId} sender\n * @description Sets the sender of the transaction simulation.\n * @returns {this}\n */\n setSender(sender) {\n this._sender = sender;\n return this;\n }\n\n /**\n * @param {string} sender\n * @description Set the 20-byte EVM address of the sender.\n * This method must be used explicitly when working with accounts that have ECDSA keys with aliases,\n * as their EVM addresses cannot be automatically derived and must be retrieved from the Mirror Node API.\n * The EVM address can be filled using `accountId.populateAccountEvmAddress(client)`\n * @returns {this}\n */\n setSenderEvmAddress(sender) {\n this._senderEvmAddress = sender;\n return this;\n }\n\n /**\n *\n * @param {string} name\n * @param {ContractFunctionParameters} functionParameters\n * @description Sets the function to call, and the parameters to pass to the function\n * @returns {this}\n */\n setFunction(name, functionParameters) {\n this._functionParameters =\n functionParameters != null\n ? functionParameters._build(name)\n : new ContractFunctionParameters()._build(name);\n\n return this;\n }\n\n /**\n * @param {Long} value\n * @description Sets the amount of value (in tinybars or wei) to be sent to the contract in the transaction.\n * Use this to specify an amount for a payable function call.\n * @returns {this}\n */\n setValue(value) {\n this._value = value;\n return this;\n }\n\n /**\n * @param {Long} gasLimit\n * @description Sets the gas limit for the contract call.\n * This specifies the maximum amount of gas that the transaction can consume.\n * @returns {this}\n */\n setGasLimit(gasLimit) {\n this._gasLimit = gasLimit;\n return this;\n }\n\n /**\n * @param {Long} gasPrice\n * @description Sets the gas price to be used for the contract call. This specifies the price of each unit of gas used in the transaction.\n * @returns {this}\n */\n setGasPrice(gasPrice) {\n this._gasPrice = gasPrice;\n return this;\n }\n\n /**\n * @param {Long} blockNumber\n * @description Sets the block number for the simulation of the contract call.\n * The block number determines the context of the contract call simulation within the blockchain.\n * @returns {this}\n */\n setBlockNumber(blockNumber) {\n this._blockNumber = blockNumber;\n return this;\n }\n\n /**\n * @returns {ContractId?}\n */\n get contractId() {\n return this._contractId;\n }\n\n /**\n * @returns {string}\n */\n get contractEvmAddress() {\n const solidityAddress = this._contractId?.toEvmAddress();\n if (solidityAddress == null) {\n throw new Error(\"Contract ID is not set\");\n }\n return solidityAddress;\n }\n\n /**\n * @returns {AccountId?}\n */\n get sender() {\n return this._sender;\n }\n\n /**\n * @returns {string | null }\n */\n get senderEvmAddress() {\n return this._senderEvmAddress;\n }\n\n /**\n * @returns {Uint8Array | null | undefined}\n */\n get callData() {\n return this._functionParameters;\n }\n\n /**\n * @returns {Long?}\n */\n get value() {\n return this._value;\n }\n\n /**\n * @returns {Long?}\n */\n get gasLimit() {\n return this._gasLimit;\n }\n\n /**\n * @returns {Long?}\n */\n get gasPrice() {\n return this._gasPrice;\n }\n\n /**\n * @returns {Long?}\n */\n get blockNumber() {\n return this._blockNumber;\n }\n\n /**\n *\n * @param {Client} client\n * @param {object} jsonPayload\n * @returns {Promise<MirrorNodeResponse>}\n */\n async performMirrorNodeRequest(client, jsonPayload) {\n if (this.contractId == null) {\n throw new Error(\"Contract ID is not set\");\n }\n this._fillEvmAddress();\n let mirrorNetworkAddress = client.mirrorNetwork[0];\n const contractCallEndpoint = \"/api/v1/contracts/call\";\n\n if (!client.ledgerId || client.ledgerId?.isLocalNode()) {\n const currentMirrorNetworkPort =\n client.mirrorNetwork[0].split(\":\")[1];\n mirrorNetworkAddress = \"http://\"\n .concat(\n client.mirrorNetwork[0].replace(\n currentMirrorNetworkPort,\n \"8545\",\n ),\n )\n .concat(contractCallEndpoint);\n } else {\n let trimmed = client.mirrorNetwork[0].split(\":\");\n mirrorNetworkAddress = \"https://\"\n .concat(trimmed[0])\n .concat(contractCallEndpoint);\n }\n\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n const response = await fetch(mirrorNetworkAddress, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(jsonPayload),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const data = /** @type {MirrorNodeResponse} */ (await response.json());\n return data;\n }\n\n _fillEvmAddress() {\n if (this.senderEvmAddress == null && this.sender != null) {\n this._senderEvmAddress = this.sender.toEvmAddress();\n }\n }\n // eslint-disable-next-line jsdoc/require-returns-check\n /**\n * @returns {object}\n */\n get JSONPayload() {\n throw new Error(\n \"JSONPayload getter is not implemented. Please implement this method in the subclass.\",\n );\n }\n}\n"],"names":["MirrorNodeContractQuery","constructor","this","_contractId","_contractEvmAddress","_sender","_senderEvmAddress","_functionName","_functionParameters","_value","_gasLimit","_gasPrice","_blockNumber","setContractId","contractId","setSender","sender","setSenderEvmAddress","setFunction","name","functionParameters","_build","ContractFunctionParameters","setValue","value","setGasLimit","gasLimit","setGasPrice","gasPrice","setBlockNumber","blockNumber","contractEvmAddress","solidityAddress","toEvmAddress","Error","senderEvmAddress","callData","performMirrorNodeRequest","client","jsonPayload","_fillEvmAddress","mirrorNetworkAddress","mirrorNetwork","contractCallEndpoint","ledgerId","isLocalNode","currentMirrorNetworkPort","split","concat","replace","trimmed","response","fetch","method","headers","body","JSON","stringify","ok","status","json","JSONPayload"],"mappings":"yDAkCe,MAAMA,EACjB,WAAAC,GACIC,KAAKC,YAAc,KACnBD,KAAKE,oBAAsB,KAC3BF,KAAKG,QAAU,KACfH,KAAKI,kBAAoB,KACzBJ,KAAKK,cAAgB,KACrBL,KAAKM,oBAAsB,KAC3BN,KAAKO,OAAS,KACdP,KAAKQ,UAAY,KACjBR,KAAKS,UAAY,KACjBT,KAAKU,aAAe,IAC5B,CAQI,aAAAC,CAAcC,GAEV,OADAZ,KAAKC,YAAcW,EACZZ,IACf,CAOI,SAAAa,CAAUC,GAEN,OADAd,KAAKG,QAAUW,EACRd,IACf,CAUI,mBAAAe,CAAoBD,GAEhB,OADAd,KAAKI,kBAAoBU,EAClBd,IACf,CASI,WAAAgB,CAAYC,EAAMC,GAMd,OALAlB,KAAKM,oBACqB,MAAtBY,EACMA,EAAmBC,OAAOF,IAC1B,IAAIG,GAA6BD,OAAOF,GAE3CjB,IACf,CAQI,QAAAqB,C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,UAAUlB,KAGzB,IAAKY,EAASO,GACV,MAAM,IAAIxB,MAAM,uBAAuBiB,EAASQ,UAKpD,aADsDR,EAASS,MAEvE,CAEI,eAAApB,GACiC,MAAzBtC,KAAKiC,kBAA2C,MAAfjC,KAAKc,SACtCd,KAAKI,kBAAoBJ,KAAKc,OAAOiB,eAEjD,CAKI,eAAI4B,GACA,MAAM,IAAI3B,MACN,uFAEZ"}
|
|
1
|
+
{"version":3,"file":"MirrorNodeContractQuery.js","sources":["../../src/query/MirrorNodeContractQuery.js"],"sourcesContent":["import ContractFunctionParameters from \"../contract/ContractFunctionParameters.js\";\n\n/**\n * @typedef {import(\"../contract/ContractId\").default} ContractId\n * @typedef {import(\"../account/AccountId\").default} AccountId\n * @typedef {import(\"../client/Client.js\").default<*, *>} Client\n *\n */\n\n/**\n * @typedef {object} MirrorNodeResponse\n * @property {string} result\n * @property {string} [error]\n * @property {string} [gasUsed]\n * @property {string} [contractAddress]\n * @property {string} [status]\n */\n\n/**\n * MirrorNodeContractQuery returns a result from EVM execution such as cost-free execution of read-only smart contract\n * queries, gas estimation, and transient simulation of read-write operations.\n * When working with sender that has ECDSA key with alias, you MUST:\n * 1. Retrieve the account's EVM address from the Mirror Node API first\n * 2. Use setSenderEvmAddress() instead of setSender()\n *\n * This is because EVM addresses for accounts with ECDSA keys and aliases cannot be automatically\n * derived and must be fetched from the Mirror Node. Example:\n *\n * ```javascript\n * // For accounts with ECDSA keys and aliases:\n * const evmAddress = // ... fetch from Mirror Node API ...\n * query.setSenderEvmAddress(evmAddress);\n * ```\n */\nexport default class MirrorNodeContractQuery {\n constructor() {\n this._contractId = null;\n this._contractEvmAddress = null;\n this._sender = null;\n this._senderEvmAddress = null;\n this._functionName = null;\n this._functionParameters = null;\n this._value = null;\n this._gasLimit = null;\n this._gasPrice = null;\n this._blockNumber = null;\n }\n\n /**\n *\n * @param {ContractId} contractId\n * @description Sets the contract instance to call.\n * @returns {this}\n */\n setContractId(contractId) {\n this._contractId = contractId;\n return this;\n }\n\n /**\n * @param {AccountId} sender\n * @description Sets the sender of the transaction simulation.\n * @returns {this}\n */\n setSender(sender) {\n this._sender = sender;\n return this;\n }\n\n /**\n * @param {string} sender\n * @description Set the 20-byte EVM address of the sender.\n * This method must be used explicitly when working with accounts that have ECDSA keys with aliases,\n * as their EVM addresses cannot be automatically derived and must be retrieved from the Mirror Node API.\n * The EVM address can be filled using `accountId.populateAccountEvmAddress(client)`\n * @returns {this}\n */\n setSenderEvmAddress(sender) {\n this._senderEvmAddress = sender;\n return this;\n }\n\n /**\n *\n * @param {string} name\n * @param {ContractFunctionParameters} functionParameters\n * @description Sets the function to call, and the parameters to pass to the function\n * @returns {this}\n */\n setFunction(name, functionParameters) {\n this._functionParameters =\n functionParameters != null\n ? functionParameters._build(name)\n : new ContractFunctionParameters()._build(name);\n\n return this;\n }\n\n /**\n * @param {Long} value\n * @description Sets the amount of value (in tinybars or wei) to be sent to the contract in the transaction.\n * Use this to specify an amount for a payable function call.\n * @returns {this}\n */\n setValue(value) {\n this._value = value;\n return this;\n }\n\n /**\n * @param {Long} gasLimit\n * @description Sets the gas limit for the contract call.\n * This specifies the maximum amount of gas that the transaction can consume.\n * @returns {this}\n */\n setGasLimit(gasLimit) {\n this._gasLimit = gasLimit;\n return this;\n }\n\n /**\n * @param {Long} gasPrice\n * @description Sets the gas price to be used for the contract call. This specifies the price of each unit of gas used in the transaction.\n * @returns {this}\n */\n setGasPrice(gasPrice) {\n this._gasPrice = gasPrice;\n return this;\n }\n\n /**\n * @param {Long} blockNumber\n * @description Sets the block number for the simulation of the contract call.\n * The block number determines the context of the contract call simulation within the blockchain.\n * @returns {this}\n */\n setBlockNumber(blockNumber) {\n this._blockNumber = blockNumber;\n return this;\n }\n\n /**\n * @returns {ContractId?}\n */\n get contractId() {\n return this._contractId;\n }\n\n /**\n * @returns {string}\n */\n get contractEvmAddress() {\n const solidityAddress = this._contractId?.toEvmAddress();\n if (solidityAddress == null) {\n throw new Error(\"Contract ID is not set\");\n }\n return solidityAddress;\n }\n\n /**\n * @returns {AccountId?}\n */\n get sender() {\n return this._sender;\n }\n\n /**\n * @returns {string | null }\n */\n get senderEvmAddress() {\n return this._senderEvmAddress;\n }\n\n /**\n * @returns {Uint8Array | null | undefined}\n */\n get callData() {\n return this._functionParameters;\n }\n\n /**\n * @returns {Long?}\n */\n get value() {\n return this._value;\n }\n\n /**\n * @returns {Long?}\n */\n get gasLimit() {\n return this._gasLimit;\n }\n\n /**\n * @returns {Long?}\n */\n get gasPrice() {\n return this._gasPrice;\n }\n\n /**\n * @returns {Long?}\n */\n get blockNumber() {\n return this._blockNumber;\n }\n\n /**\n *\n * @param {Client} client\n * @param {object} jsonPayload\n * @returns {Promise<MirrorNodeResponse>}\n */\n async performMirrorNodeRequest(client, jsonPayload) {\n if (this.contractId == null) {\n throw new Error(\"Contract ID is not set\");\n }\n this._fillEvmAddress();\n let mirrorRestApiBaseUrl = client.mirrorRestApiBaseUrl;\n const contractCallEndpointPath = \"/contracts/call\";\n\n // Check if this is a local environment (localhost or 127.0.0.1)\n const mirrorNode = client._mirrorNetwork.getNextMirrorNode();\n const host = mirrorNode.address.address;\n const isLocalEnvironment = host === \"localhost\" || host === \"127.0.0.1\";\n\n if (isLocalEnvironment) {\n // For local environments, use HTTP scheme and port 8545\n const url = new URL(mirrorRestApiBaseUrl);\n url.protocol = \"http:\";\n url.port = \"8545\";\n mirrorRestApiBaseUrl = url.toString();\n }\n\n const contractCallEndpointUrl = `${mirrorRestApiBaseUrl}${contractCallEndpointPath}`;\n\n // eslint-disable-next-line n/no-unsupported-features/node-builtins\n const response = await fetch(contractCallEndpointUrl, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(jsonPayload),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const data = /** @type {MirrorNodeResponse} */ (await response.json());\n return data;\n }\n\n _fillEvmAddress() {\n if (this.senderEvmAddress == null && this.sender != null) {\n this._senderEvmAddress = this.sender.toEvmAddress();\n }\n }\n // eslint-disable-next-line jsdoc/require-returns-check\n /**\n * @returns {object}\n */\n get JSONPayload() {\n throw new Error(\n \"JSONPayload getter is not implemented. Please implement this method in the subclass.\",\n );\n }\n}\n"],"names":["MirrorNodeContractQuery","constructor","this","_contractId","_contractEvmAddress","_sender","_senderEvmAddress","_functionName","_functionParameters","_value","_gasLimit","_gasPrice","_blockNumber","setContractId","contractId","setSender","sender","setSenderEvmAddress","setFunction","name","functionParameters","_build","ContractFunctionParameters","setValue","value","setGasLimit","gasLimit","setGasPrice","gasPrice","setBlockNumber","blockNumber","contractEvmAddress","solidityAddress","toEvmAddress","Error","senderEvmAddress","callData","performMirrorNodeRequest","client","jsonPayload","_fillEvmAddress","mirrorRestApiBaseUrl","host","_mirrorNetwork","getNextMirrorNode","address","url","URL","protocol","port","toString","contractCallEndpointUrl","response","fetch","method","headers","body","JSON","stringify","ok","status","json","JSONPayload"],"mappings":"yDAkCe,MAAMA,EACjB,WAAAC,GACIC,KAAKC,YAAc,KACnBD,KAAKE,oBAAsB,KAC3BF,KAAKG,QAAU,KACfH,KAAKI,kBAAoB,KACzBJ,KAAKK,cAAgB,KACrBL,KAAKM,oBAAsB,KAC3BN,KAAKO,OAAS,KACdP,KAAKQ,UAAY,KACjBR,KAAKS,UAAY,KACjBT,KAAKU,aAAe,IAC5B,CAQI,aAAAC,CAAcC,GAEV,OADAZ,KAAKC,YAAcW,EACZZ,IACf,CAOI,SAAAa,CAAUC,GAEN,OADAd,KAAKG,QAAUW,EACRd,IACf,CAUI,mBAAAe,CAAoBD,GAEhB,OADAd,KAAKI,kBAAoBU,EAClBd,IACf,CASI,WAAAgB,CAAYC,EAAMC,GAMd,OALAlB,KAAKM,oBACqB,MAAtBY,EACMA,EAAmBC,OAAOF,IAC1B,IAAIG,GAA6BD,OAAOF,GAE3CjB,IACf,CAQI,QAAAqB,CAASC,GAEL,OAD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iC,MAAzBtC,KAAKiC,kBAA2C,MAAfjC,KAAKc,SACtCd,KAAKI,kBAAoBJ,KAAKc,OAAOiB,eAEjD,CAKI,eAAI6B,GACA,MAAM,IAAI5B,MACN,uFAEZ"}
|
package/lib/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const o="hiero-sdk-js",s="2.73.
|
|
1
|
+
const o="hiero-sdk-js",s="2.73.2";export{o as SDK_NAME,s as SDK_VERSION};
|
|
2
2
|
//# sourceMappingURL=version.js.map
|